Datasets:
Modalities:
Geospatial
Languages:
English
Size:
10B<n<100B
Tags:
crop-yield
remote-sensing
remote-sensing-integrated-crop-model
deep-learning-emulator
winter-wheat
germany
DOI:
License:
Remove old paths after relocating to projections_deferred/
Browse files- Scripts_DL_Climate_to_LAI_CC/main.py +0 -6
- Scripts_DL_Climate_to_LAI_CC/predict_cc_lai.py +0 -646
- Scripts_ML_ET/apply_et_to_states.py +0 -160
- Scripts_ML_ET/apply_et_to_states_CC.py +0 -148
- Scripts_ML_ET/combined_wheat_RSCM_out_v2.csv +0 -0
- Scripts_ML_ET/et_model_comparison.csv +0 -8
- Scripts_ML_ET/main.py +0 -6
- Scripts_ML_ET/train_et_models.py +0 -249
- Scripts_ML_GPP/apply_gpp_to_states.py +0 -160
- Scripts_ML_GPP/apply_gpp_to_states_CC.py +0 -148
- Scripts_ML_GPP/combined_wheat_RSCM_out_v2.csv +0 -0
- Scripts_ML_GPP/gpp_model_comparison.csv +0 -8
- Scripts_ML_GPP/main.py +0 -6
- Scripts_ML_GPP/train_gpp_models.py +0 -249
Scripts_DL_Climate_to_LAI_CC/main.py
DELETED
|
@@ -1,6 +0,0 @@
|
|
| 1 |
-
def main():
|
| 2 |
-
print("Hello from wheat-climate-to-lai-cc-uv!")
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
if __name__ == "__main__":
|
| 6 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_DL_Climate_to_LAI_CC/predict_cc_lai.py
DELETED
|
@@ -1,646 +0,0 @@
|
|
| 1 |
-
"""Generate per-state CC-projected LAI .npy files using per-state FFNN models.
|
| 2 |
-
|
| 3 |
-
Pipeline
|
| 4 |
-
--------
|
| 5 |
-
For each German federal state x climate-change scenario x future year, this
|
| 6 |
-
script:
|
| 7 |
-
|
| 8 |
-
1. Loads the historical base-year .npy at
|
| 9 |
-
``../{REGION}/data_LAI_geo_wx_2017_to_21/LAI_wx_geo_{REGION}_120d_{BASE}.npy``.
|
| 10 |
-
Shape ``(P, 120, 8)`` with channels
|
| 11 |
-
``[DOY1, LAI, lon, lat, DOY2, SSI, Tmax, Tmin]`` and DOY range 50..169.
|
| 12 |
-
2. Applies the monthly CC deltas from ``CC_Delta_German_States.csv`` to the
|
| 13 |
-
climate channels (per-pixel, per-DOY, looked up by the month each DOY
|
| 14 |
-
belongs to):
|
| 15 |
-
SSI_new = SSI + Globrad_Delta(month) (MJ m^-2 day^-1)
|
| 16 |
-
Tmax_new = Tmax + Tmax_Delta(month) (deg C)
|
| 17 |
-
Tmin_new = Tmin + Tmin_Delta(month) (deg C)
|
| 18 |
-
Tavg and Precip deltas exist in the CSV but are skipped: Tavg is a
|
| 19 |
-
derived quantity (not a model input) and the .npy has no precipitation
|
| 20 |
-
channel (the FFNN was not trained with precip).
|
| 21 |
-
3. Loads the per-state FFNN model + StandardScaler from
|
| 22 |
-
``../wheat_climate_to_LAI_uv/output_trained_wheat_FFNN_LOYO_{REGION}/
|
| 23 |
-
fold_test_2021/`` (model trained on 2017-2020, held out 2021 -- the
|
| 24 |
-
most recent fold available, chosen for forward projection).
|
| 25 |
-
4. Runs inference on features
|
| 26 |
-
``[DOY2, lon, lat, SSI_new, Tmax_new, Tmin_new]`` (same order as
|
| 27 |
-
training; same scaler) to get predicted LAI.
|
| 28 |
-
5. Writes the projected .npy with the SAME (P, 120, 8) shape and channel
|
| 29 |
-
order as the input -- the LAI channel is replaced with the prediction,
|
| 30 |
-
the climate channels reflect the CC-perturbed values, and DOY/lon/lat
|
| 31 |
-
are passed through unchanged.
|
| 32 |
-
|
| 33 |
-
Future-year mapping (5 files per state per scenario)
|
| 34 |
-
----------------------------------------------------
|
| 35 |
-
There are 5 historical base years (2017-2021) and the prompt asks for
|
| 36 |
-
"five year projection data" per scenario, so each base year is mapped to
|
| 37 |
-
one future year offset by a fixed amount per decade:
|
| 38 |
-
|
| 39 |
-
CC2050 decade (2041_2050 deltas):
|
| 40 |
-
2017 -> 2041, 2018 -> 2042, 2019 -> 2043, 2020 -> 2044, 2021 -> 2045
|
| 41 |
-
CC2070 decade (2061_2070 deltas):
|
| 42 |
-
2017 -> 2061, 2018 -> 2062, 2019 -> 2063, 2020 -> 2064, 2021 -> 2065
|
| 43 |
-
CC2090 decade (2081_2090 deltas):
|
| 44 |
-
2017 -> 2081, 2018 -> 2082, 2019 -> 2083, 2020 -> 2084, 2021 -> 2085
|
| 45 |
-
|
| 46 |
-
Outputs (one .npy per state per future year per scenario)
|
| 47 |
-
---------------------------------------------------------
|
| 48 |
-
../{REGION}/data_LAI_geo_wx_CC2050_RCP26/LAI_wx_geo_{REGION}_120d_2041.npy ... 2045.npy
|
| 49 |
-
../{REGION}/data_LAI_geo_wx_CC2050_RCP85/LAI_wx_geo_{REGION}_120d_2041.npy ... 2045.npy
|
| 50 |
-
../{REGION}/data_LAI_geo_wx_CC2070_RCP26/LAI_wx_geo_{REGION}_120d_2061.npy ... 2065.npy
|
| 51 |
-
../{REGION}/data_LAI_geo_wx_CC2070_RCP85/LAI_wx_geo_{REGION}_120d_2061.npy ... 2065.npy
|
| 52 |
-
../{REGION}/data_LAI_geo_wx_CC2090_RCP26/LAI_wx_geo_{REGION}_120d_2081.npy ... 2085.npy
|
| 53 |
-
../{REGION}/data_LAI_geo_wx_CC2090_RCP85/LAI_wx_geo_{REGION}_120d_2081.npy ... 2085.npy
|
| 54 |
-
|
| 55 |
-
Total: 13 states x 5 years x 6 scenarios = 390 projection .npy files.
|
| 56 |
-
|
| 57 |
-
Per-scenario manifest CSVs are written into ``cc_predictions_log/`` next to
|
| 58 |
-
this script.
|
| 59 |
-
|
| 60 |
-
Usage
|
| 61 |
-
-----
|
| 62 |
-
python predict_cc_lai.py # all states, all scenarios
|
| 63 |
-
python predict_cc_lai.py --regions BadenW # one state
|
| 64 |
-
python predict_cc_lai.py --scenarios CC2050_RCP26 # one scenario
|
| 65 |
-
python predict_cc_lai.py --dry-run # plan, do not write
|
| 66 |
-
python predict_cc_lai.py --gpus 0 # restrict to GPU 0
|
| 67 |
-
python predict_cc_lai.py --overwrite # overwrite existing .npy
|
| 68 |
-
"""
|
| 69 |
-
|
| 70 |
-
from __future__ import annotations
|
| 71 |
-
|
| 72 |
-
import argparse
|
| 73 |
-
import os
|
| 74 |
-
import re
|
| 75 |
-
import sys
|
| 76 |
-
import time
|
| 77 |
-
import warnings
|
| 78 |
-
from dataclasses import dataclass
|
| 79 |
-
from pathlib import Path
|
| 80 |
-
|
| 81 |
-
import joblib
|
| 82 |
-
import numpy as np
|
| 83 |
-
import pandas as pd
|
| 84 |
-
import torch
|
| 85 |
-
import torch.nn as nn
|
| 86 |
-
|
| 87 |
-
warnings.filterwarnings("ignore")
|
| 88 |
-
|
| 89 |
-
BASE_DIR = Path(__file__).parent
|
| 90 |
-
STATES_ROOT = BASE_DIR.parent
|
| 91 |
-
TRAINED_ROOT = BASE_DIR.parent / "wheat_climate_to_LAI_uv"
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
# ---------------------------------------------------------------------------
|
| 95 |
-
# Constants (data conventions inherited from the training pipeline)
|
| 96 |
-
# ---------------------------------------------------------------------------
|
| 97 |
-
|
| 98 |
-
CROP = "wheat"
|
| 99 |
-
|
| 100 |
-
REGIONS = [
|
| 101 |
-
"BadenW", "Bayern", "Brandenburg", "Hessen", "MecklenburgV",
|
| 102 |
-
"Niedersachsen", "NordrheinW", "RheinlandP", "Saarland", "Sachsen",
|
| 103 |
-
"SachsenA", "SchleswigH", "Thuringen",
|
| 104 |
-
]
|
| 105 |
-
|
| 106 |
-
# CC CSV uses the full German names; per-state folders use the project's short
|
| 107 |
-
# names. Maps full-name -> short-name. Berlin, Bremen, Hamburg are in the CSV
|
| 108 |
-
# but absent from our 13-state training set, so they are silently dropped.
|
| 109 |
-
CSV_TO_REGION = {
|
| 110 |
-
"Baden-Wurttemberg": "BadenW",
|
| 111 |
-
"Bayern": "Bayern",
|
| 112 |
-
"Brandenburg": "Brandenburg",
|
| 113 |
-
"Hessen": "Hessen",
|
| 114 |
-
"Mecklenburg-Vorpommern": "MecklenburgV",
|
| 115 |
-
"Niedersachsen": "Niedersachsen",
|
| 116 |
-
"Nordrhein-Westfalen": "NordrheinW",
|
| 117 |
-
"Rheinland-Pfalz": "RheinlandP",
|
| 118 |
-
"Saarland": "Saarland",
|
| 119 |
-
"Sachsen": "Sachsen",
|
| 120 |
-
"Sachsen-Anhalt": "SachsenA",
|
| 121 |
-
"Schleswig-Holstein": "SchleswigH",
|
| 122 |
-
"Thuringen": "Thuringen",
|
| 123 |
-
}
|
| 124 |
-
|
| 125 |
-
# Feature order the FFNN was trained with (see wheat_climate_to_LAI_FFNN.py).
|
| 126 |
-
FEATURE_COLS = ["DOY2", "lon", "lat", "SSI", "Tmax", "Tmin"]
|
| 127 |
-
|
| 128 |
-
# Channel layout in the on-disk .npy: 8 channels, DOY1 == DOY2 (byte-identical),
|
| 129 |
-
# kept as-is for backward compatibility with downstream tooling.
|
| 130 |
-
NPY_CHANNELS = ["DOY1", "LAI", "lon", "lat", "DOY2", "SSI", "Tmax", "Tmin"]
|
| 131 |
-
|
| 132 |
-
# Default FFNN architecture fallback if cv_summary.txt cannot be parsed.
|
| 133 |
-
DEFAULT_HP = {
|
| 134 |
-
"n_layers": 3,
|
| 135 |
-
"hidden_sizes": [256, 320, 512],
|
| 136 |
-
"dropout_rate": 0.2,
|
| 137 |
-
}
|
| 138 |
-
|
| 139 |
-
# Months tagged in CC_Delta_German_States.csv (abbrev -> 1..12).
|
| 140 |
-
MONTH_TO_INT = {
|
| 141 |
-
"Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6,
|
| 142 |
-
"Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10, "Nov": 11, "Dec": 12,
|
| 143 |
-
}
|
| 144 |
-
|
| 145 |
-
# Climate-change scenario catalogue: (folder_tag, decade_csv_key, rcp_csv_key,
|
| 146 |
-
# year_offset_from_2017). Output folder name is ``data_LAI_geo_wx_{TAG}``.
|
| 147 |
-
@dataclass(frozen=True)
|
| 148 |
-
class Scenario:
|
| 149 |
-
tag: str # e.g. "CC2050_RCP26"
|
| 150 |
-
decade: str # CSV value, e.g. "2041_2050"
|
| 151 |
-
rcp: str # CSV value, e.g. "RCP2.6"
|
| 152 |
-
year_offset: int # base 2017 -> future first_year_of_decade
|
| 153 |
-
|
| 154 |
-
ALL_SCENARIOS: list[Scenario] = [
|
| 155 |
-
Scenario("CC2050_RCP26", "2041_2050", "RCP2.6", 2041 - 2017),
|
| 156 |
-
Scenario("CC2050_RCP85", "2041_2050", "RCP8.5", 2041 - 2017),
|
| 157 |
-
Scenario("CC2070_RCP26", "2061_2070", "RCP2.6", 2061 - 2017),
|
| 158 |
-
Scenario("CC2070_RCP85", "2061_2070", "RCP8.5", 2061 - 2017),
|
| 159 |
-
Scenario("CC2090_RCP26", "2081_2090", "RCP2.6", 2081 - 2017),
|
| 160 |
-
Scenario("CC2090_RCP85", "2081_2090", "RCP8.5", 2081 - 2017),
|
| 161 |
-
]
|
| 162 |
-
|
| 163 |
-
BASE_YEARS = [2017, 2018, 2019, 2020, 2021]
|
| 164 |
-
DOY_RANGE = range(50, 170) # 50..169 inclusive (120 days)
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
# ---------------------------------------------------------------------------
|
| 168 |
-
# DOY -> month lookup (non-leap reference year)
|
| 169 |
-
# ---------------------------------------------------------------------------
|
| 170 |
-
# DOY 50..169 covers Feb..Jun in both leap and non-leap years to within +/-1
|
| 171 |
-
# day. The CC deltas are monthly averages, so the +/-1-day shift at month
|
| 172 |
-
# boundaries is well below the noise of the deltas themselves. We use the
|
| 173 |
-
# non-leap reference year for a single deterministic mapping.
|
| 174 |
-
|
| 175 |
-
def _build_doy_to_month(n_doys: int = 120, start_doy: int = 50) -> np.ndarray:
|
| 176 |
-
"""Return an (n_doys,) int array mapping each DOY (start_doy..start_doy+n-1)
|
| 177 |
-
to a 1..12 month index, using a non-leap reference year."""
|
| 178 |
-
boundaries = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
|
| 179 |
-
months = np.empty(n_doys, dtype=np.int32)
|
| 180 |
-
for i in range(n_doys):
|
| 181 |
-
doy = start_doy + i
|
| 182 |
-
for m_idx, end_doy in enumerate(boundaries):
|
| 183 |
-
if doy <= end_doy:
|
| 184 |
-
months[i] = m_idx + 1 # 1..12
|
| 185 |
-
break
|
| 186 |
-
return months
|
| 187 |
-
|
| 188 |
-
DOY_MONTH = _build_doy_to_month(n_doys=120, start_doy=50) # shape (120,)
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
# ---------------------------------------------------------------------------
|
| 192 |
-
# Model definition (matches the training script's FFNN class exactly)
|
| 193 |
-
# ---------------------------------------------------------------------------
|
| 194 |
-
|
| 195 |
-
class FFNN(nn.Module):
|
| 196 |
-
def __init__(self, input_size: int,
|
| 197 |
-
hidden_sizes: list[int] | tuple[int, ...] = (256, 320, 512),
|
| 198 |
-
dropout_rate: float = 0.2):
|
| 199 |
-
super().__init__()
|
| 200 |
-
layers: list[nn.Module] = []
|
| 201 |
-
prev = input_size
|
| 202 |
-
for i, h in enumerate(hidden_sizes):
|
| 203 |
-
layers.append(nn.Linear(prev, h))
|
| 204 |
-
layers.append(nn.ReLU())
|
| 205 |
-
if i < len(hidden_sizes) - 1:
|
| 206 |
-
layers.append(nn.Dropout(dropout_rate))
|
| 207 |
-
prev = h
|
| 208 |
-
layers.append(nn.Linear(prev, 1))
|
| 209 |
-
self.network = nn.Sequential(*layers)
|
| 210 |
-
|
| 211 |
-
def forward(self, x): # noqa: D401
|
| 212 |
-
return self.network(x)
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
# ---------------------------------------------------------------------------
|
| 216 |
-
# Per-state model + hyperparameter loading
|
| 217 |
-
# ---------------------------------------------------------------------------
|
| 218 |
-
|
| 219 |
-
_HP_LIST_RE = re.compile(r"\[\s*([\d,\s]+)\s*\]")
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
def per_state_fold_dir(region: str, year: int = 2021) -> Path:
|
| 223 |
-
return TRAINED_ROOT / f"output_trained_{CROP}_FFNN_LOYO_{region}" / f"fold_test_{year}"
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
def per_state_cv_summary(region: str) -> Path:
|
| 227 |
-
return TRAINED_ROOT / f"output_trained_{CROP}_FFNN_LOYO_{region}" / "cv_summary.txt"
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
def load_per_state_hyperparameters(region: str) -> dict:
|
| 231 |
-
"""Read n_layers / hidden_sizes / dropout_rate from per-state cv_summary.txt."""
|
| 232 |
-
hp = dict(DEFAULT_HP)
|
| 233 |
-
p = per_state_cv_summary(region)
|
| 234 |
-
if not p.is_file():
|
| 235 |
-
print(f" [warn] {region}: cv_summary.txt missing, using DEFAULT_HP {DEFAULT_HP}")
|
| 236 |
-
return hp
|
| 237 |
-
|
| 238 |
-
in_block = False
|
| 239 |
-
for line in p.read_text().splitlines():
|
| 240 |
-
if "Hyperparameters used" in line:
|
| 241 |
-
in_block = True
|
| 242 |
-
continue
|
| 243 |
-
if not in_block:
|
| 244 |
-
continue
|
| 245 |
-
m = re.match(r"\s+([A-Za-z_]\w*)\s*:\s*(.+?)\s*$", line)
|
| 246 |
-
if not m:
|
| 247 |
-
continue
|
| 248 |
-
key, raw = m.group(1), m.group(2)
|
| 249 |
-
if key == "n_layers":
|
| 250 |
-
hp["n_layers"] = int(raw)
|
| 251 |
-
elif key == "hidden_sizes":
|
| 252 |
-
inner = _HP_LIST_RE.search(raw)
|
| 253 |
-
if inner:
|
| 254 |
-
hp["hidden_sizes"] = [int(x) for x in inner.group(1).split(",") if x.strip()]
|
| 255 |
-
elif key == "dropout_rate":
|
| 256 |
-
hp["dropout_rate"] = float(raw)
|
| 257 |
-
return hp
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
def load_per_state_artifacts(region: str, device: torch.device) -> tuple[FFNN, object, dict]:
|
| 261 |
-
"""Return (model, scaler, hyperparams) for the per-state FFNN (fold 2021)."""
|
| 262 |
-
fdir = per_state_fold_dir(region, 2021)
|
| 263 |
-
pth = fdir / f"FFNN_{CROP}_germany.pth"
|
| 264 |
-
scal = fdir / f"scaler_{CROP}_germany.pkl"
|
| 265 |
-
if not pth.is_file() or not scal.is_file():
|
| 266 |
-
raise FileNotFoundError(
|
| 267 |
-
f"Missing FFNN artifacts for {region} (fold_test_2021).\n"
|
| 268 |
-
f" expected model: {pth}\n expected scaler: {scal}"
|
| 269 |
-
)
|
| 270 |
-
|
| 271 |
-
hp = load_per_state_hyperparameters(region)
|
| 272 |
-
hidden = hp["hidden_sizes"][: hp["n_layers"]]
|
| 273 |
-
model = FFNN(input_size=len(FEATURE_COLS), hidden_sizes=hidden,
|
| 274 |
-
dropout_rate=hp["dropout_rate"]).to(device)
|
| 275 |
-
state = torch.load(pth, map_location=device)
|
| 276 |
-
model.load_state_dict(state)
|
| 277 |
-
model.eval()
|
| 278 |
-
scaler = joblib.load(scal)
|
| 279 |
-
return model, scaler, hp
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
# ---------------------------------------------------------------------------
|
| 283 |
-
# CC delta lookup
|
| 284 |
-
# ---------------------------------------------------------------------------
|
| 285 |
-
|
| 286 |
-
def load_cc_csv(csv_path: Path) -> pd.DataFrame:
|
| 287 |
-
df = pd.read_csv(csv_path)
|
| 288 |
-
df["RegionShort"] = df["State"].map(CSV_TO_REGION)
|
| 289 |
-
df["MonthInt"] = df["Month"].map(MONTH_TO_INT)
|
| 290 |
-
keep_cols = [
|
| 291 |
-
"RegionShort", "Decade", "MonthInt", "RCP",
|
| 292 |
-
"Tmax_Delta", "Tmin_Delta", "Globrad_Delta", "Precip_Delta",
|
| 293 |
-
]
|
| 294 |
-
return df[keep_cols].copy()
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
def monthly_delta_vector(cc_df: pd.DataFrame, region: str, decade: str, rcp: str
|
| 298 |
-
) -> np.ndarray:
|
| 299 |
-
"""Return a (120,) array of (tmax_d, tmin_d, ssi_d) tuples ordered by DOY.
|
| 300 |
-
|
| 301 |
-
Shape is (120, 3) actually -- columns: [tmax_delta, tmin_delta, ssi_delta].
|
| 302 |
-
Aligned with DOY_RANGE.
|
| 303 |
-
"""
|
| 304 |
-
sub = cc_df[(cc_df["RegionShort"] == region)
|
| 305 |
-
& (cc_df["Decade"] == decade)
|
| 306 |
-
& (cc_df["RCP"] == rcp)]
|
| 307 |
-
if sub.empty:
|
| 308 |
-
raise ValueError(f"No CC rows for region={region} decade={decade} rcp={rcp}")
|
| 309 |
-
by_month = {int(r.MonthInt): (float(r.Tmax_Delta), float(r.Tmin_Delta),
|
| 310 |
-
float(r.Globrad_Delta))
|
| 311 |
-
for r in sub.itertuples()}
|
| 312 |
-
out = np.zeros((len(DOY_MONTH), 3), dtype=np.float32)
|
| 313 |
-
for i, m in enumerate(DOY_MONTH):
|
| 314 |
-
if int(m) not in by_month:
|
| 315 |
-
raise ValueError(f"Missing month={int(m)} CC delta for {region}/{decade}/{rcp}")
|
| 316 |
-
out[i] = by_month[int(m)]
|
| 317 |
-
return out
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
# ---------------------------------------------------------------------------
|
| 321 |
-
# Per-(state, scenario, base_year) projection
|
| 322 |
-
# ---------------------------------------------------------------------------
|
| 323 |
-
|
| 324 |
-
def base_npy_path(region: str, base_year: int) -> Path:
|
| 325 |
-
return STATES_ROOT / region / "data_LAI_geo_wx_2017_to_21" / \
|
| 326 |
-
f"LAI_wx_geo_{region}_120d_{base_year}.npy"
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
def scenario_output_path(region: str, scenario: Scenario, future_year: int) -> Path:
|
| 330 |
-
return STATES_ROOT / region / f"data_LAI_geo_wx_{scenario.tag}" / \
|
| 331 |
-
f"LAI_wx_geo_{region}_120d_{future_year}.npy"
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
def project_one(region: str, scenario: Scenario, base_year: int,
|
| 335 |
-
model: FFNN, scaler, cc_df: pd.DataFrame,
|
| 336 |
-
device: torch.device, batch_size: int = 1_048_576,
|
| 337 |
-
) -> dict | None:
|
| 338 |
-
"""Build the CC-projected .npy for (region, scenario, base_year)."""
|
| 339 |
-
future_year = 2017 + (base_year - 2017) + scenario.year_offset
|
| 340 |
-
|
| 341 |
-
in_path = base_npy_path(region, base_year)
|
| 342 |
-
if not in_path.is_file():
|
| 343 |
-
print(f" [skip] {region}/{base_year}: base .npy not found: {in_path}")
|
| 344 |
-
return None
|
| 345 |
-
|
| 346 |
-
arr = np.load(in_path)
|
| 347 |
-
if arr.ndim != 3 or arr.shape[1] != 120 or arr.shape[2] != 8:
|
| 348 |
-
print(f" [skip] {region}/{base_year}: unexpected shape {arr.shape}, want (P, 120, 8)")
|
| 349 |
-
return None
|
| 350 |
-
|
| 351 |
-
in_dtype = arr.dtype
|
| 352 |
-
# Make a float32 working copy for inference. The original `arr` is kept
|
| 353 |
-
# untouched so DOY1/lon/lat/DOY2 passthrough channels stay bit-exact at
|
| 354 |
-
# the input dtype (otherwise a float64->float32->float64 round-trip on
|
| 355 |
-
# UTM-scale lon/lat introduces ~1e-3 m of noise that looks suspicious
|
| 356 |
-
# in downstream byte-equality checks).
|
| 357 |
-
work = np.asarray(arr, dtype=np.float32)
|
| 358 |
-
n_nan = int(np.isnan(work).sum())
|
| 359 |
-
n_inf = int(np.isinf(work).sum())
|
| 360 |
-
if n_nan or n_inf:
|
| 361 |
-
work = np.nan_to_num(work, nan=0.0, posinf=1e6, neginf=-1e6)
|
| 362 |
-
|
| 363 |
-
# Passthrough channels: keep original dtype (bit-exact views).
|
| 364 |
-
doy1_o = arr[:, :, 0]
|
| 365 |
-
lon_o = arr[:, :, 2]
|
| 366 |
-
lat_o = arr[:, :, 3]
|
| 367 |
-
doy2_o = arr[:, :, 4]
|
| 368 |
-
|
| 369 |
-
# Working-copy climate channels (float32) we will perturb and feed the model.
|
| 370 |
-
lon_f = work[:, :, 2]
|
| 371 |
-
lat_f = work[:, :, 3]
|
| 372 |
-
doy2_f = work[:, :, 4]
|
| 373 |
-
ssi_f = work[:, :, 5]
|
| 374 |
-
tmax_f = work[:, :, 6]
|
| 375 |
-
tmin_f = work[:, :, 7]
|
| 376 |
-
|
| 377 |
-
# Apply per-month CC deltas (deltas shape (120, 3) = tmax / tmin / ssi).
|
| 378 |
-
deltas = monthly_delta_vector(cc_df, region, scenario.decade, scenario.rcp)
|
| 379 |
-
tmax_d = deltas[:, 0]
|
| 380 |
-
tmin_d = deltas[:, 1]
|
| 381 |
-
ssi_d = deltas[:, 2]
|
| 382 |
-
|
| 383 |
-
# Broadcast (120,) -> (P, 120) and add; new arrays, do not mutate `work`.
|
| 384 |
-
ssi_new = ssi_f + ssi_d[None, :]
|
| 385 |
-
tmax_new = tmax_f + tmax_d[None, :]
|
| 386 |
-
tmin_new = tmin_f + tmin_d[None, :]
|
| 387 |
-
|
| 388 |
-
# Build feature matrix: (P*120, 6) in FEATURE_COLS order
|
| 389 |
-
# ['DOY2', 'lon', 'lat', 'SSI', 'Tmax', 'Tmin'].
|
| 390 |
-
P, T = arr.shape[0], arr.shape[1]
|
| 391 |
-
feats = np.stack([
|
| 392 |
-
doy2_f.reshape(-1),
|
| 393 |
-
lon_f.reshape(-1),
|
| 394 |
-
lat_f.reshape(-1),
|
| 395 |
-
ssi_new.reshape(-1),
|
| 396 |
-
tmax_new.reshape(-1),
|
| 397 |
-
tmin_new.reshape(-1),
|
| 398 |
-
], axis=1) # already float32
|
| 399 |
-
|
| 400 |
-
X = scaler.transform(feats).astype(np.float32, copy=False)
|
| 401 |
-
out = np.empty(X.shape[0], dtype=np.float32)
|
| 402 |
-
# Adaptive batching: halve the batch on CUDA OOM and retry that chunk.
|
| 403 |
-
# Some per-state models (e.g. Bayern, Niedersachsen) have wide
|
| 404 |
-
# [1024, 1024, 1024] hidden layers whose intermediate activations blow
|
| 405 |
-
# past the default 1M-row batch on 12 GB GPUs.
|
| 406 |
-
cur_bs = batch_size
|
| 407 |
-
min_bs = 4096
|
| 408 |
-
with torch.no_grad():
|
| 409 |
-
start = 0
|
| 410 |
-
while start < X.shape[0]:
|
| 411 |
-
end = min(start + cur_bs, X.shape[0])
|
| 412 |
-
try:
|
| 413 |
-
t = torch.from_numpy(X[start:end]).to(device)
|
| 414 |
-
y = model(t).squeeze(-1).cpu().numpy()
|
| 415 |
-
out[start:end] = y
|
| 416 |
-
start = end
|
| 417 |
-
except torch.cuda.OutOfMemoryError:
|
| 418 |
-
torch.cuda.empty_cache()
|
| 419 |
-
if cur_bs <= min_bs:
|
| 420 |
-
raise
|
| 421 |
-
cur_bs = max(min_bs, cur_bs // 2)
|
| 422 |
-
print(f" [retry] OOM at batch {start}; reducing batch_size -> {cur_bs}")
|
| 423 |
-
pred_lai = out.reshape(P, T)
|
| 424 |
-
|
| 425 |
-
# Assemble output array. Passthrough channels keep their bit-exact source
|
| 426 |
-
# views; predicted/perturbed channels are cast up to `in_dtype` for a
|
| 427 |
-
# uniform on-disk dtype that matches the base-year .npy.
|
| 428 |
-
proj = np.empty((P, T, 8), dtype=in_dtype)
|
| 429 |
-
proj[:, :, 0] = doy1_o # DOY1 (passthrough)
|
| 430 |
-
proj[:, :, 1] = pred_lai # LAI (predicted)
|
| 431 |
-
proj[:, :, 2] = lon_o # lon (passthrough)
|
| 432 |
-
proj[:, :, 3] = lat_o # lat (passthrough)
|
| 433 |
-
proj[:, :, 4] = doy2_o # DOY2 (passthrough)
|
| 434 |
-
proj[:, :, 5] = ssi_new # SSI (perturbed)
|
| 435 |
-
proj[:, :, 6] = tmax_new # Tmax (perturbed)
|
| 436 |
-
proj[:, :, 7] = tmin_new # Tmin (perturbed)
|
| 437 |
-
|
| 438 |
-
out_path = scenario_output_path(region, scenario, future_year)
|
| 439 |
-
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 440 |
-
np.save(out_path, proj)
|
| 441 |
-
|
| 442 |
-
return {
|
| 443 |
-
"region": region,
|
| 444 |
-
"scenario": scenario.tag,
|
| 445 |
-
"decade": scenario.decade,
|
| 446 |
-
"rcp": scenario.rcp,
|
| 447 |
-
"base_year": base_year,
|
| 448 |
-
"future_year": future_year,
|
| 449 |
-
"pixels": int(P),
|
| 450 |
-
"doys": int(T),
|
| 451 |
-
"n_nan_in_base": n_nan,
|
| 452 |
-
"n_inf_in_base": n_inf,
|
| 453 |
-
"pred_lai_mean": float(pred_lai.mean()),
|
| 454 |
-
"pred_lai_min": float(pred_lai.min()),
|
| 455 |
-
"pred_lai_max": float(pred_lai.max()),
|
| 456 |
-
"obs_lai_mean": float(arr[:, :, 1].mean()),
|
| 457 |
-
"tmax_delta_mean_C": float(tmax_d.mean()),
|
| 458 |
-
"tmin_delta_mean_C": float(tmin_d.mean()),
|
| 459 |
-
"ssi_delta_mean": float(ssi_d.mean()),
|
| 460 |
-
"out_path": str(out_path.resolve()),
|
| 461 |
-
}
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
# ---------------------------------------------------------------------------
|
| 465 |
-
# Orchestration
|
| 466 |
-
# ---------------------------------------------------------------------------
|
| 467 |
-
|
| 468 |
-
def pick_device(gpus: list[int] | None) -> torch.device:
|
| 469 |
-
if not torch.cuda.is_available():
|
| 470 |
-
return torch.device("cpu")
|
| 471 |
-
if gpus is None:
|
| 472 |
-
return torch.device("cuda:0")
|
| 473 |
-
if len(gpus) != 1:
|
| 474 |
-
# If multiple selected we just use the first; this script is small enough
|
| 475 |
-
# to fit on a single GPU and benefit zero from DataParallel.
|
| 476 |
-
print(f"[info] multiple GPUs given ({gpus}); using cuda:{gpus[0]} only")
|
| 477 |
-
os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(str(g) for g in gpus)
|
| 478 |
-
return torch.device("cuda:0")
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
def parse_int_list(raw: str | None) -> list[int] | None:
|
| 482 |
-
if not raw:
|
| 483 |
-
return None
|
| 484 |
-
parts = []
|
| 485 |
-
for chunk in raw.split(","):
|
| 486 |
-
chunk = chunk.strip()
|
| 487 |
-
if "-" in chunk:
|
| 488 |
-
a, b = chunk.split("-")
|
| 489 |
-
parts.extend(range(int(a), int(b) + 1))
|
| 490 |
-
elif chunk:
|
| 491 |
-
parts.append(int(chunk))
|
| 492 |
-
return parts
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
def parse_str_list(raw: str | None, valid: list[str]) -> list[str]:
|
| 496 |
-
if not raw or raw.lower() == "all":
|
| 497 |
-
return list(valid)
|
| 498 |
-
out = [s.strip() for s in raw.split(",") if s.strip()]
|
| 499 |
-
bad = [s for s in out if s not in valid]
|
| 500 |
-
if bad:
|
| 501 |
-
raise SystemExit(f"Unknown items {bad}; valid options: {valid}")
|
| 502 |
-
return out
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
def main() -> int:
|
| 506 |
-
ap = argparse.ArgumentParser(description=__doc__,
|
| 507 |
-
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 508 |
-
ap.add_argument("--csv", type=str,
|
| 509 |
-
default=str(BASE_DIR / "CC_Delta_German_States.csv"),
|
| 510 |
-
help="Path to CC_Delta_German_States.csv")
|
| 511 |
-
ap.add_argument("--regions", type=str, default="all",
|
| 512 |
-
help='Comma-separated states, or "all" (default).')
|
| 513 |
-
ap.add_argument("--scenarios", type=str, default="all",
|
| 514 |
-
help='Comma-separated scenario tags, or "all" (default). '
|
| 515 |
-
"Tags: " + ", ".join(s.tag for s in ALL_SCENARIOS))
|
| 516 |
-
ap.add_argument("--base-years", type=str, default=",".join(map(str, BASE_YEARS)),
|
| 517 |
-
help="Comma-separated historical base years (default: 2017-2021).")
|
| 518 |
-
ap.add_argument("--gpus", type=str, default=None,
|
| 519 |
-
help="Restrict to specific GPU id(s), e.g. '0' or '1,2'.")
|
| 520 |
-
ap.add_argument("--batch-size", type=int, default=1_048_576,
|
| 521 |
-
help="Inference batch size (default 1,048,576 rows).")
|
| 522 |
-
ap.add_argument("--overwrite", action="store_true",
|
| 523 |
-
help="Overwrite existing .npy files (default: skip).")
|
| 524 |
-
ap.add_argument("--dry-run", action="store_true",
|
| 525 |
-
help="Plan and print what would happen, do not write.")
|
| 526 |
-
ap.add_argument("--log-dir", type=str,
|
| 527 |
-
default=str(BASE_DIR / "cc_predictions_log"),
|
| 528 |
-
help="Directory for per-scenario manifest CSVs.")
|
| 529 |
-
args = ap.parse_args()
|
| 530 |
-
|
| 531 |
-
csv_path = Path(args.csv)
|
| 532 |
-
if not csv_path.is_file():
|
| 533 |
-
raise SystemExit(f"CC CSV not found: {csv_path}")
|
| 534 |
-
|
| 535 |
-
regions = parse_str_list(args.regions, REGIONS)
|
| 536 |
-
scenario_tags = parse_str_list(args.scenarios, [s.tag for s in ALL_SCENARIOS])
|
| 537 |
-
scenarios = [s for s in ALL_SCENARIOS if s.tag in scenario_tags]
|
| 538 |
-
base_years = parse_int_list(args.base_years) or BASE_YEARS
|
| 539 |
-
gpus = parse_int_list(args.gpus)
|
| 540 |
-
|
| 541 |
-
log_dir = Path(args.log_dir)
|
| 542 |
-
log_dir.mkdir(parents=True, exist_ok=True)
|
| 543 |
-
|
| 544 |
-
print("=" * 76)
|
| 545 |
-
print(f"CC LAI projection - {CROP}")
|
| 546 |
-
print(f" CSV : {csv_path}")
|
| 547 |
-
print(f" States ({len(regions)}) : {regions}")
|
| 548 |
-
print(f" Scenarios ({len(scenarios)}) : {[s.tag for s in scenarios]}")
|
| 549 |
-
print(f" Base years : {base_years} -> 5 future years per scenario")
|
| 550 |
-
print(f" Overwrite : {args.overwrite} Dry-run: {args.dry_run}")
|
| 551 |
-
print(f" Log dir : {log_dir}")
|
| 552 |
-
print("=" * 76)
|
| 553 |
-
|
| 554 |
-
cc_df = load_cc_csv(csv_path)
|
| 555 |
-
missing_in_csv = [r for r in regions if r not in cc_df["RegionShort"].dropna().unique()]
|
| 556 |
-
if missing_in_csv:
|
| 557 |
-
raise SystemExit(f"States missing from CC CSV: {missing_in_csv}")
|
| 558 |
-
|
| 559 |
-
device = pick_device(gpus)
|
| 560 |
-
print(f"[info] device: {device}")
|
| 561 |
-
|
| 562 |
-
total_planned = len(regions) * len(scenarios) * len(base_years)
|
| 563 |
-
print(f"[info] total planned projections: {total_planned}")
|
| 564 |
-
print()
|
| 565 |
-
|
| 566 |
-
if args.dry_run:
|
| 567 |
-
for region in regions:
|
| 568 |
-
print(f"-- {region}")
|
| 569 |
-
for sc in scenarios:
|
| 570 |
-
for by in base_years:
|
| 571 |
-
fy = 2017 + (by - 2017) + sc.year_offset
|
| 572 |
-
out_p = scenario_output_path(region, sc, fy)
|
| 573 |
-
print(f" {sc.tag} base {by} -> {fy} -> {out_p}")
|
| 574 |
-
print("\n[dry-run] no files written.")
|
| 575 |
-
return 0
|
| 576 |
-
|
| 577 |
-
records: list[dict] = []
|
| 578 |
-
t0 = time.time()
|
| 579 |
-
n_done = 0
|
| 580 |
-
n_skip = 0
|
| 581 |
-
n_err = 0
|
| 582 |
-
|
| 583 |
-
for region in regions:
|
| 584 |
-
print(f"=== {region} ===")
|
| 585 |
-
try:
|
| 586 |
-
model, scaler, hp = load_per_state_artifacts(region, device)
|
| 587 |
-
except FileNotFoundError as e:
|
| 588 |
-
print(f" [error] {e}")
|
| 589 |
-
n_err += len(scenarios) * len(base_years)
|
| 590 |
-
continue
|
| 591 |
-
print(f" loaded FFNN layers={hp['hidden_sizes'][:hp['n_layers']]} "
|
| 592 |
-
f"dropout={hp['dropout_rate']:.3f}")
|
| 593 |
-
|
| 594 |
-
for sc in scenarios:
|
| 595 |
-
for by in base_years:
|
| 596 |
-
fy = 2017 + (by - 2017) + sc.year_offset
|
| 597 |
-
out_p = scenario_output_path(region, sc, fy)
|
| 598 |
-
if out_p.is_file() and not args.overwrite:
|
| 599 |
-
print(f" [skip-exists] {sc.tag} {by}->{fy}")
|
| 600 |
-
n_skip += 1
|
| 601 |
-
continue
|
| 602 |
-
try:
|
| 603 |
-
rec = project_one(region, sc, by, model, scaler, cc_df,
|
| 604 |
-
device, batch_size=args.batch_size)
|
| 605 |
-
except Exception as e: # noqa: BLE001
|
| 606 |
-
print(f" [error] {region}/{sc.tag}/{by}: {type(e).__name__}: {e}")
|
| 607 |
-
n_err += 1
|
| 608 |
-
continue
|
| 609 |
-
if rec is None:
|
| 610 |
-
n_err += 1
|
| 611 |
-
continue
|
| 612 |
-
records.append(rec)
|
| 613 |
-
n_done += 1
|
| 614 |
-
print(f" ok {sc.tag} {by}->{fy} "
|
| 615 |
-
f"px={rec['pixels']:>6} "
|
| 616 |
-
f"mean(LAI pred)={rec['pred_lai_mean']:.3f} "
|
| 617 |
-
f"dTmax={rec['tmax_delta_mean_C']:+.2f}C "
|
| 618 |
-
f"dTmin={rec['tmin_delta_mean_C']:+.2f}C "
|
| 619 |
-
f"dSSI={rec['ssi_delta_mean']:+.2f}")
|
| 620 |
-
|
| 621 |
-
# Free model so next state's load isn't memory-pressured (CPU or GPU).
|
| 622 |
-
del model
|
| 623 |
-
if device.type == "cuda":
|
| 624 |
-
torch.cuda.empty_cache()
|
| 625 |
-
|
| 626 |
-
# Write manifest CSVs grouped by scenario.
|
| 627 |
-
if records:
|
| 628 |
-
all_df = pd.DataFrame.from_records(records)
|
| 629 |
-
all_df.to_csv(log_dir / "manifest_all.csv", index=False)
|
| 630 |
-
for sc in scenarios:
|
| 631 |
-
sub = all_df[all_df["scenario"] == sc.tag]
|
| 632 |
-
if not sub.empty:
|
| 633 |
-
sub.to_csv(log_dir / f"manifest_{sc.tag}.csv", index=False)
|
| 634 |
-
|
| 635 |
-
elapsed = time.time() - t0
|
| 636 |
-
print()
|
| 637 |
-
print("=" * 76)
|
| 638 |
-
print(f"Done in {elapsed:.1f}s -- written={n_done} skipped_existing={n_skip} errors={n_err}")
|
| 639 |
-
if records:
|
| 640 |
-
print(f"Manifest CSVs in: {log_dir}")
|
| 641 |
-
print("=" * 76)
|
| 642 |
-
return 0 if n_err == 0 else 1
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
if __name__ == "__main__":
|
| 646 |
-
sys.exit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_ML_ET/apply_et_to_states.py
DELETED
|
@@ -1,160 +0,0 @@
|
|
| 1 |
-
"""Apply the trained ET model to per-state LAI+weather .npy files.
|
| 2 |
-
|
| 3 |
-
Reads:
|
| 4 |
-
../{state}/data_LAI_geo_wx_2017_to_21/LAI_wx_geo_{state}_120d_{year}.npy
|
| 5 |
-
each of shape (n_pixels, 120, 8) with channels:
|
| 6 |
-
[DOY1, LAI, lon, lat, DOY2, SSI(=SRad), Tmax, Tmin]
|
| 7 |
-
|
| 8 |
-
Writes (per state, per year):
|
| 9 |
-
../{state}/data_ET_2017_to_21/ET_{state}_120d_{year}.npy
|
| 10 |
-
shape (n_pixels, 120, 2) with channels [DOY, ET]
|
| 11 |
-
../{state}/data_ET_2017_to_21/ET_{state}_120d_{year}_summary.csv
|
| 12 |
-
per-DOY mean/std/min/max across pixels (handy quick-look)
|
| 13 |
-
|
| 14 |
-
Usage:
|
| 15 |
-
uv run python apply_et_to_states.py
|
| 16 |
-
uv run python apply_et_to_states.py --states BadenW Bayern --years 2020 2021
|
| 17 |
-
uv run python apply_et_to_states.py --bundle et_best_model.joblib
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
from __future__ import annotations
|
| 21 |
-
|
| 22 |
-
import argparse
|
| 23 |
-
from pathlib import Path
|
| 24 |
-
|
| 25 |
-
import joblib
|
| 26 |
-
import numpy as np
|
| 27 |
-
import pandas as pd
|
| 28 |
-
|
| 29 |
-
HERE = Path(__file__).resolve().parent
|
| 30 |
-
PROJECT_ROOT = HERE.parent
|
| 31 |
-
DEFAULT_BUNDLE = HERE / "et_best_model.joblib"
|
| 32 |
-
|
| 33 |
-
DEFAULT_STATES = [
|
| 34 |
-
"BadenW", "Bayern", "Brandenburg", "Hessen", "MecklenburgV",
|
| 35 |
-
"Niedersachsen", "NordrheinW", "RheinlandP", "Saarland",
|
| 36 |
-
"Sachsen", "SachsenA", "SchleswigH", "Thuringen",
|
| 37 |
-
]
|
| 38 |
-
DEFAULT_YEARS = [2017, 2018, 2019, 2020, 2021]
|
| 39 |
-
|
| 40 |
-
NPY_CHANNELS = ["DOY1", "LAI", "lon", "lat", "DOY2", "SSI", "Tmax", "Tmin"]
|
| 41 |
-
NPY_IDX = {name: i for i, name in enumerate(NPY_CHANNELS)}
|
| 42 |
-
|
| 43 |
-
CSV_TO_NPY = {"DOY": "DOY2", "SLAI": "LAI", "Tmax": "Tmax", "Tmin": "Tmin", "SRad": "SSI"}
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def build_feature_matrix(arr: np.ndarray, feature_names: list[str]) -> np.ndarray:
|
| 47 |
-
"""Map (pixels, 120, 8) -> (pixels*120, len(feature_names)) using CSV->npy mapping."""
|
| 48 |
-
|
| 49 |
-
pixels, days, n_chan = arr.shape
|
| 50 |
-
if n_chan != len(NPY_CHANNELS):
|
| 51 |
-
raise ValueError(
|
| 52 |
-
f"Expected {len(NPY_CHANNELS)} channels in .npy file, got {n_chan}. "
|
| 53 |
-
f"Update NPY_CHANNELS if the layout changed."
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
cols = []
|
| 57 |
-
for f in feature_names:
|
| 58 |
-
if f not in CSV_TO_NPY:
|
| 59 |
-
raise KeyError(
|
| 60 |
-
f"Don't know how to map training feature {f!r} to a channel in the .npy file. "
|
| 61 |
-
f"Known mappings: {CSV_TO_NPY}"
|
| 62 |
-
)
|
| 63 |
-
cols.append(arr[:, :, NPY_IDX[CSV_TO_NPY[f]]].reshape(-1))
|
| 64 |
-
return np.stack(cols, axis=1)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def per_doy_summary(doy: np.ndarray, et: np.ndarray) -> pd.DataFrame:
|
| 68 |
-
"""Summarise ET across pixels for each DOY column (length 120)."""
|
| 69 |
-
|
| 70 |
-
n_pixels, n_days = et.shape
|
| 71 |
-
doy_per_day = doy[0]
|
| 72 |
-
return pd.DataFrame({
|
| 73 |
-
"DOY": doy_per_day.astype(int),
|
| 74 |
-
"ET_mean": et.mean(axis=0),
|
| 75 |
-
"ET_std": et.std(axis=0),
|
| 76 |
-
"ET_min": et.min(axis=0),
|
| 77 |
-
"ET_max": et.max(axis=0),
|
| 78 |
-
"n_pixels": np.full(n_days, n_pixels, dtype=int),
|
| 79 |
-
})
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def process_one(arr_path: Path, out_dir: Path, model, feature_names: list[str]) -> Path:
|
| 83 |
-
arr = np.load(arr_path)
|
| 84 |
-
pixels, days, _ = arr.shape
|
| 85 |
-
|
| 86 |
-
X = build_feature_matrix(arr, feature_names)
|
| 87 |
-
yhat = model.predict(X).astype(np.float32).reshape(pixels, days)
|
| 88 |
-
|
| 89 |
-
doy = arr[:, :, NPY_IDX["DOY2"]].astype(np.float32)
|
| 90 |
-
out = np.stack([doy, yhat], axis=2)
|
| 91 |
-
|
| 92 |
-
out_dir.mkdir(parents=True, exist_ok=True)
|
| 93 |
-
out_path = out_dir / arr_path.name.replace("LAI_wx_geo_", "ET_")
|
| 94 |
-
np.save(out_path, out)
|
| 95 |
-
|
| 96 |
-
summary_path = out_path.with_name(out_path.stem + "_summary.csv")
|
| 97 |
-
per_doy_summary(doy, yhat).to_csv(summary_path, index=False)
|
| 98 |
-
return out_path
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def parse_args() -> argparse.Namespace:
|
| 102 |
-
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
|
| 103 |
-
p.add_argument("--bundle", default=str(DEFAULT_BUNDLE),
|
| 104 |
-
help=f"joblib bundle saved by train_et_models.py (default: {DEFAULT_BUNDLE.name})")
|
| 105 |
-
p.add_argument("--root", default=str(PROJECT_ROOT),
|
| 106 |
-
help=f"Project root that contains per-state folders (default: {PROJECT_ROOT})")
|
| 107 |
-
p.add_argument("--states", nargs="+", default=DEFAULT_STATES,
|
| 108 |
-
help="Subset of state folder names to process.")
|
| 109 |
-
p.add_argument("--years", nargs="+", type=int, default=DEFAULT_YEARS,
|
| 110 |
-
help="Subset of years to process.")
|
| 111 |
-
p.add_argument("--out-folder", default="data_ET_2017_to_21",
|
| 112 |
-
help="Output sub-folder name created inside each state directory.")
|
| 113 |
-
return p.parse_args()
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
def main() -> int:
|
| 117 |
-
args = parse_args()
|
| 118 |
-
bundle_path = Path(args.bundle)
|
| 119 |
-
if not bundle_path.exists():
|
| 120 |
-
raise SystemExit(
|
| 121 |
-
f"Model bundle {bundle_path} not found. Run train_et_models.py first."
|
| 122 |
-
)
|
| 123 |
-
|
| 124 |
-
bundle = joblib.load(bundle_path)
|
| 125 |
-
model = bundle["model"]
|
| 126 |
-
feature_names = bundle["feature_names"]
|
| 127 |
-
metrics = bundle.get("metrics", {})
|
| 128 |
-
print(f"[load] {bundle_path}")
|
| 129 |
-
print(f"[load] model='{metrics.get('model', type(model).__name__)}' "
|
| 130 |
-
f"test_R2={metrics.get('test_R2', float('nan')):.4f} "
|
| 131 |
-
f"features={feature_names}")
|
| 132 |
-
|
| 133 |
-
root = Path(args.root)
|
| 134 |
-
n_done = n_skipped = 0
|
| 135 |
-
for state in args.states:
|
| 136 |
-
in_dir = root / state / "data_LAI_geo_wx_2017_to_21"
|
| 137 |
-
out_dir = root / state / args.out_folder
|
| 138 |
-
if not in_dir.is_dir():
|
| 139 |
-
print(f"[skip] {state}: no folder {in_dir}")
|
| 140 |
-
n_skipped += 1
|
| 141 |
-
continue
|
| 142 |
-
for year in args.years:
|
| 143 |
-
arr_path = in_dir / f"LAI_wx_geo_{state}_120d_{year}.npy"
|
| 144 |
-
if not arr_path.exists():
|
| 145 |
-
print(f"[skip] {state} {year}: missing {arr_path.name}")
|
| 146 |
-
n_skipped += 1
|
| 147 |
-
continue
|
| 148 |
-
out_path = process_one(arr_path, out_dir, model, feature_names)
|
| 149 |
-
arr_size_mb = arr_path.stat().st_size / 1e6
|
| 150 |
-
out_size_mb = out_path.stat().st_size / 1e6
|
| 151 |
-
print(f"[ok ] {state:14s} {year} "
|
| 152 |
-
f"in={arr_size_mb:6.1f}MB out={out_size_mb:5.1f}MB -> {out_path}")
|
| 153 |
-
n_done += 1
|
| 154 |
-
|
| 155 |
-
print(f"\n[done] {n_done} files written, {n_skipped} skipped")
|
| 156 |
-
return 0
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
if __name__ == "__main__":
|
| 160 |
-
raise SystemExit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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per year):
|
| 5 |
-
../{state}/data_LAI_geo_wx_CC{ref_year}_{rcp}/LAI_wx_geo_{state}_120d_{file_year}.npy
|
| 6 |
-
each of shape (n_pixels, 120, 8) with channels:
|
| 7 |
-
[DOY1, LAI, lon, lat, DOY2, SSI(=SRad), Tmax, Tmin]
|
| 8 |
-
|
| 9 |
-
Note: each CC folder typically contains 5 yearly files spanning a 5-year window
|
| 10 |
-
ending shortly before the reference year, e.g.:
|
| 11 |
-
CC2050 -> 2041..2045
|
| 12 |
-
CC2070 -> 2061..2065
|
| 13 |
-
CC2090 -> 2081..2085
|
| 14 |
-
This script discovers every .npy in each scenario folder, so it works regardless
|
| 15 |
-
of which file_years are present.
|
| 16 |
-
|
| 17 |
-
Writes (per state, per scenario, per year):
|
| 18 |
-
../{state}/data_ET_CC{ref_year}_{rcp}_ML/ET_{state}_120d_{file_year}.npy
|
| 19 |
-
shape (n_pixels, 120, 2) with channels [DOY, ET]
|
| 20 |
-
../{state}/data_ET_CC{ref_year}_{rcp}_ML/ET_{state}_120d_{file_year}_summary.csv
|
| 21 |
-
per-DOY mean/std/min/max across pixels.
|
| 22 |
-
|
| 23 |
-
Usage:
|
| 24 |
-
uv run python apply_et_to_states_CC.py
|
| 25 |
-
uv run python apply_et_to_states_CC.py --states BadenW Bayern
|
| 26 |
-
uv run python apply_et_to_states_CC.py --ref-years 2050 2090 --rcps RCP85
|
| 27 |
-
uv run python apply_et_to_states_CC.py --bundle et_best_model.joblib
|
| 28 |
-
"""
|
| 29 |
-
|
| 30 |
-
from __future__ import annotations
|
| 31 |
-
|
| 32 |
-
import argparse
|
| 33 |
-
from pathlib import Path
|
| 34 |
-
|
| 35 |
-
import joblib
|
| 36 |
-
import numpy as np
|
| 37 |
-
|
| 38 |
-
from apply_et_to_states import (
|
| 39 |
-
DEFAULT_STATES,
|
| 40 |
-
NPY_IDX,
|
| 41 |
-
build_feature_matrix,
|
| 42 |
-
per_doy_summary,
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
HERE = Path(__file__).resolve().parent
|
| 46 |
-
PROJECT_ROOT = HERE.parent
|
| 47 |
-
DEFAULT_BUNDLE = HERE / "et_best_model.joblib"
|
| 48 |
-
|
| 49 |
-
DEFAULT_REF_YEARS = [2050, 2070, 2090]
|
| 50 |
-
DEFAULT_RCPS = ["RCP26", "RCP85"]
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def process_one(arr_path: Path, out_dir: Path, model, feature_names: list[str]) -> Path | None:
|
| 54 |
-
"""Run inference on a single CC .npy file. Returns None if the file is empty/corrupt."""
|
| 55 |
-
|
| 56 |
-
if arr_path.stat().st_size == 0:
|
| 57 |
-
return None
|
| 58 |
-
try:
|
| 59 |
-
arr = np.load(arr_path)
|
| 60 |
-
except (EOFError, ValueError, OSError):
|
| 61 |
-
return None
|
| 62 |
-
if arr.ndim != 3:
|
| 63 |
-
return None
|
| 64 |
-
pixels, days, _ = arr.shape
|
| 65 |
-
|
| 66 |
-
X = build_feature_matrix(arr, feature_names)
|
| 67 |
-
yhat = model.predict(X).astype(np.float32).reshape(pixels, days)
|
| 68 |
-
|
| 69 |
-
doy = arr[:, :, NPY_IDX["DOY2"]].astype(np.float32)
|
| 70 |
-
out = np.stack([doy, yhat], axis=2)
|
| 71 |
-
|
| 72 |
-
out_dir.mkdir(parents=True, exist_ok=True)
|
| 73 |
-
out_path = out_dir / arr_path.name.replace("LAI_wx_geo_", "ET_")
|
| 74 |
-
np.save(out_path, out)
|
| 75 |
-
|
| 76 |
-
summary_path = out_path.with_name(out_path.stem + "_summary.csv")
|
| 77 |
-
per_doy_summary(doy, yhat).to_csv(summary_path, index=False)
|
| 78 |
-
return out_path
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def parse_args() -> argparse.Namespace:
|
| 82 |
-
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
|
| 83 |
-
p.add_argument("--bundle", default=str(DEFAULT_BUNDLE),
|
| 84 |
-
help=f"joblib bundle saved by train_et_models.py (default: {DEFAULT_BUNDLE.name})")
|
| 85 |
-
p.add_argument("--root", default=str(PROJECT_ROOT),
|
| 86 |
-
help=f"Project root that contains per-state folders (default: {PROJECT_ROOT})")
|
| 87 |
-
p.add_argument("--states", nargs="+", default=DEFAULT_STATES,
|
| 88 |
-
help="Subset of state folder names to process.")
|
| 89 |
-
p.add_argument("--ref-years", nargs="+", type=int, default=DEFAULT_REF_YEARS,
|
| 90 |
-
help="Reference years (folder labels): default 2050 2070 2090.")
|
| 91 |
-
p.add_argument("--rcps", nargs="+", default=DEFAULT_RCPS,
|
| 92 |
-
help="Scenario tags (default: RCP26 RCP85).")
|
| 93 |
-
return p.parse_args()
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def main() -> int:
|
| 97 |
-
args = parse_args()
|
| 98 |
-
bundle_path = Path(args.bundle)
|
| 99 |
-
if not bundle_path.exists():
|
| 100 |
-
raise SystemExit(
|
| 101 |
-
f"Model bundle {bundle_path} not found. Run train_et_models.py first."
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
bundle = joblib.load(bundle_path)
|
| 105 |
-
model = bundle["model"]
|
| 106 |
-
feature_names = bundle["feature_names"]
|
| 107 |
-
metrics = bundle.get("metrics", {})
|
| 108 |
-
print(f"[load] {bundle_path}")
|
| 109 |
-
print(f"[load] model='{metrics.get('model', type(model).__name__)}' "
|
| 110 |
-
f"test_R2={metrics.get('test_R2', float('nan')):.4f} "
|
| 111 |
-
f"features={feature_names}")
|
| 112 |
-
|
| 113 |
-
root = Path(args.root)
|
| 114 |
-
n_done = n_skipped = 0
|
| 115 |
-
for state in args.states:
|
| 116 |
-
for ref_year in args.ref_years:
|
| 117 |
-
for rcp in args.rcps:
|
| 118 |
-
in_dir = root / state / f"data_LAI_geo_wx_CC{ref_year}_{rcp}"
|
| 119 |
-
out_dir = root / state / f"data_ET_CC{ref_year}_{rcp}_ML"
|
| 120 |
-
if not in_dir.is_dir():
|
| 121 |
-
print(f"[skip] {state} CC{ref_year} {rcp}: no folder {in_dir}")
|
| 122 |
-
n_skipped += 1
|
| 123 |
-
continue
|
| 124 |
-
arr_paths = sorted(in_dir.glob(f"LAI_wx_geo_{state}_120d_*.npy"))
|
| 125 |
-
if not arr_paths:
|
| 126 |
-
print(f"[skip] {state} CC{ref_year} {rcp}: no .npy files in {in_dir}")
|
| 127 |
-
n_skipped += 1
|
| 128 |
-
continue
|
| 129 |
-
for arr_path in arr_paths:
|
| 130 |
-
file_year = arr_path.stem.split("_")[-1]
|
| 131 |
-
out_path = process_one(arr_path, out_dir, model, feature_names)
|
| 132 |
-
if out_path is None:
|
| 133 |
-
print(f"[skip] {state:14s} CC{ref_year} {rcp} "
|
| 134 |
-
f"yr={file_year} empty/corrupt input ({arr_path.name})")
|
| 135 |
-
n_skipped += 1
|
| 136 |
-
continue
|
| 137 |
-
in_mb = arr_path.stat().st_size / 1e6
|
| 138 |
-
out_mb = out_path.stat().st_size / 1e6
|
| 139 |
-
print(f"[ok ] {state:14s} CC{ref_year} {rcp} "
|
| 140 |
-
f"yr={file_year} in={in_mb:6.1f}MB out={out_mb:5.1f}MB -> {out_path}")
|
| 141 |
-
n_done += 1
|
| 142 |
-
|
| 143 |
-
print(f"\n[done] {n_done} files written, {n_skipped} skipped")
|
| 144 |
-
return 0
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
if __name__ == "__main__":
|
| 148 |
-
raise SystemExit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_ML_ET/combined_wheat_RSCM_out_v2.csv
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Scripts_ML_ET/et_model_comparison.csv
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
model,train_R2,test_R2,test_RMSE,test_MAE,short
|
| 2 |
-
ExT,0.9999997520230427,0.5841162854181792,0.7558305771305526,0.5596282568807341,et
|
| 3 |
-
RF,0.9402780130180641,0.5629794742046232,0.774799653377884,0.5795767837483615,rf
|
| 4 |
-
XGB,0.9728913671761259,0.5560205752051268,0.7809440533807773,0.5812149235239816,xgb
|
| 5 |
-
GB,0.7737269432350296,0.5324292475100935,0.8014236767702441,0.5977385514514458,gb
|
| 6 |
-
HGB,0.9164845177233168,0.5179223543091451,0.8137612335814248,0.6045447165895007,hgb
|
| 7 |
-
LightGBM,0.9914365906915804,0.5177557205984851,0.8139018627304726,0.6018338876139192,lgbm
|
| 8 |
-
SVR,0.5280836507420024,0.48929983633173046,0.8375707429625091,0.6342273220726324,svr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_ML_ET/main.py
DELETED
|
@@ -1,6 +0,0 @@
|
|
| 1 |
-
def main():
|
| 2 |
-
print("Hello from sim-et-wh-uv!")
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
if __name__ == "__main__":
|
| 6 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_ML_ET/train_et_models.py
DELETED
|
@@ -1,249 +0,0 @@
|
|
| 1 |
-
"""Train ML regressors to simulate ET from DOY, LAI, Tmax, Tmin, SRad.
|
| 2 |
-
|
| 3 |
-
Inputs: combined_wheat_RSCM_out_v2.csv (columns include DOY, SLAI, Tmax, Tmin, SRad, ET)
|
| 4 |
-
Models: SVR, RandomForest, ExtraTrees, HistGradientBoosting, GradientBoosting, XGBoost, LightGBM
|
| 5 |
-
Output: et_best_model.joblib (chosen model bundled with its StandardScaler and feature names)
|
| 6 |
-
et_model_comparison.csv
|
| 7 |
-
et_parity_<model>.png (one parity plot per model on the test split)
|
| 8 |
-
|
| 9 |
-
Usage:
|
| 10 |
-
uv run python train_et_models.py # interactive: pick the model after table is shown
|
| 11 |
-
uv run python train_et_models.py --auto # auto-pick the model with the best test R^2
|
| 12 |
-
uv run python train_et_models.py --pick xgb # pick a specific model by short name
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
from __future__ import annotations
|
| 16 |
-
|
| 17 |
-
import argparse
|
| 18 |
-
import sys
|
| 19 |
-
from pathlib import Path
|
| 20 |
-
|
| 21 |
-
import joblib
|
| 22 |
-
import matplotlib.pyplot as plt
|
| 23 |
-
import numpy as np
|
| 24 |
-
import pandas as pd
|
| 25 |
-
from sklearn.ensemble import (
|
| 26 |
-
ExtraTreesRegressor,
|
| 27 |
-
GradientBoostingRegressor,
|
| 28 |
-
HistGradientBoostingRegressor,
|
| 29 |
-
RandomForestRegressor,
|
| 30 |
-
)
|
| 31 |
-
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
|
| 32 |
-
from sklearn.model_selection import train_test_split
|
| 33 |
-
from sklearn.pipeline import Pipeline
|
| 34 |
-
from sklearn.preprocessing import StandardScaler
|
| 35 |
-
from sklearn.svm import SVR
|
| 36 |
-
|
| 37 |
-
import lightgbm as lgb
|
| 38 |
-
import xgboost as xgb
|
| 39 |
-
|
| 40 |
-
HERE = Path(__file__).resolve().parent
|
| 41 |
-
CSV_PATH = HERE / "combined_wheat_RSCM_out_v2.csv"
|
| 42 |
-
OUT_BUNDLE = HERE / "et_best_model.joblib"
|
| 43 |
-
OUT_TABLE = HERE / "et_model_comparison.csv"
|
| 44 |
-
|
| 45 |
-
FEATURE_COLS = ["DOY", "SLAI", "Tmax", "Tmin", "SRad"]
|
| 46 |
-
TARGET_COL = "ET"
|
| 47 |
-
RANDOM_STATE = 42
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def build_models() -> dict[str, tuple[str, Pipeline]]:
|
| 51 |
-
"""Return short_name -> (display_name, sklearn Pipeline)."""
|
| 52 |
-
|
| 53 |
-
return {
|
| 54 |
-
"svr": (
|
| 55 |
-
"Support Vector Regression",
|
| 56 |
-
Pipeline([
|
| 57 |
-
("scaler", StandardScaler()),
|
| 58 |
-
("model", SVR(kernel="rbf", C=10.0, gamma="scale", epsilon=0.1)),
|
| 59 |
-
]),
|
| 60 |
-
),
|
| 61 |
-
"rf": (
|
| 62 |
-
"Random Forest",
|
| 63 |
-
Pipeline([
|
| 64 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 65 |
-
("model", RandomForestRegressor(
|
| 66 |
-
n_estimators=400, max_depth=None, n_jobs=-1, random_state=RANDOM_STATE,
|
| 67 |
-
)),
|
| 68 |
-
]),
|
| 69 |
-
),
|
| 70 |
-
"et": (
|
| 71 |
-
"Extra Trees",
|
| 72 |
-
Pipeline([
|
| 73 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 74 |
-
("model", ExtraTreesRegressor(
|
| 75 |
-
n_estimators=500, max_depth=None, n_jobs=-1, random_state=RANDOM_STATE,
|
| 76 |
-
)),
|
| 77 |
-
]),
|
| 78 |
-
),
|
| 79 |
-
"hgb": (
|
| 80 |
-
"Histogram Gradient Boosting",
|
| 81 |
-
Pipeline([
|
| 82 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 83 |
-
("model", HistGradientBoostingRegressor(
|
| 84 |
-
max_iter=500, learning_rate=0.05, max_depth=None,
|
| 85 |
-
random_state=RANDOM_STATE,
|
| 86 |
-
)),
|
| 87 |
-
]),
|
| 88 |
-
),
|
| 89 |
-
"gb": (
|
| 90 |
-
"Gradient Boosting",
|
| 91 |
-
Pipeline([
|
| 92 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 93 |
-
("model", GradientBoostingRegressor(
|
| 94 |
-
n_estimators=400, learning_rate=0.05, max_depth=4,
|
| 95 |
-
random_state=RANDOM_STATE,
|
| 96 |
-
)),
|
| 97 |
-
]),
|
| 98 |
-
),
|
| 99 |
-
"xgb": (
|
| 100 |
-
"XGBoost",
|
| 101 |
-
Pipeline([
|
| 102 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 103 |
-
("model", xgb.XGBRegressor(
|
| 104 |
-
n_estimators=600, learning_rate=0.05, max_depth=6,
|
| 105 |
-
subsample=0.9, colsample_bytree=0.9,
|
| 106 |
-
objective="reg:squarederror", tree_method="hist",
|
| 107 |
-
n_jobs=-1, random_state=RANDOM_STATE, verbosity=0,
|
| 108 |
-
)),
|
| 109 |
-
]),
|
| 110 |
-
),
|
| 111 |
-
"lgbm": (
|
| 112 |
-
"LightGBM",
|
| 113 |
-
Pipeline([
|
| 114 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 115 |
-
("model", lgb.LGBMRegressor(
|
| 116 |
-
n_estimators=800, learning_rate=0.05, num_leaves=63,
|
| 117 |
-
subsample=0.9, colsample_bytree=0.9, min_child_samples=20,
|
| 118 |
-
n_jobs=-1, random_state=RANDOM_STATE, verbosity=-1,
|
| 119 |
-
)),
|
| 120 |
-
]),
|
| 121 |
-
),
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def load_dataset(csv_path: Path) -> tuple[np.ndarray, np.ndarray, pd.DataFrame]:
|
| 126 |
-
df = pd.read_csv(csv_path)
|
| 127 |
-
needed = FEATURE_COLS + [TARGET_COL]
|
| 128 |
-
missing = [c for c in needed if c not in df.columns]
|
| 129 |
-
if missing:
|
| 130 |
-
raise SystemExit(f"CSV {csv_path} is missing required columns: {missing}")
|
| 131 |
-
|
| 132 |
-
df = df.dropna(subset=needed).copy()
|
| 133 |
-
X = df[FEATURE_COLS].to_numpy(dtype=np.float64)
|
| 134 |
-
y = df[TARGET_COL].to_numpy(dtype=np.float64)
|
| 135 |
-
return X, y, df
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
def evaluate(name: str, model: Pipeline, X_train, X_test, y_train, y_test) -> dict:
|
| 139 |
-
model.fit(X_train, y_train)
|
| 140 |
-
yhat_train = model.predict(X_train)
|
| 141 |
-
yhat_test = model.predict(X_test)
|
| 142 |
-
return {
|
| 143 |
-
"model": name,
|
| 144 |
-
"train_R2": r2_score(y_train, yhat_train),
|
| 145 |
-
"test_R2": r2_score(y_test, yhat_test),
|
| 146 |
-
"test_RMSE": float(np.sqrt(mean_squared_error(y_test, yhat_test))),
|
| 147 |
-
"test_MAE": mean_absolute_error(y_test, yhat_test),
|
| 148 |
-
"_yhat_test": yhat_test,
|
| 149 |
-
"_pipeline": model,
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
def parity_plot(y_true, y_pred, title: str, out_png: Path) -> None:
|
| 154 |
-
fig, ax = plt.subplots(figsize=(5.0, 5.0))
|
| 155 |
-
ax.scatter(y_true, y_pred, s=8, alpha=0.4, edgecolor="none")
|
| 156 |
-
lo = float(min(y_true.min(), y_pred.min()))
|
| 157 |
-
hi = float(max(y_true.max(), y_pred.max()))
|
| 158 |
-
ax.plot([lo, hi], [lo, hi], "k--", lw=1.0)
|
| 159 |
-
r2 = r2_score(y_true, y_pred)
|
| 160 |
-
rmse = float(np.sqrt(mean_squared_error(y_true, y_pred)))
|
| 161 |
-
ax.set_xlabel(f"Observed {TARGET_COL}")
|
| 162 |
-
ax.set_ylabel(f"Predicted {TARGET_COL}")
|
| 163 |
-
ax.set_title(f"{title}\nR^2 = {r2:.3f} | RMSE = {rmse:.3f}")
|
| 164 |
-
ax.grid(True, alpha=0.3)
|
| 165 |
-
fig.tight_layout()
|
| 166 |
-
fig.savefig(out_png, dpi=140)
|
| 167 |
-
plt.close(fig)
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
def parse_args() -> argparse.Namespace:
|
| 171 |
-
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
|
| 172 |
-
p.add_argument("--csv", default=str(CSV_PATH), help=f"Path to CSV (default: {CSV_PATH.name})")
|
| 173 |
-
p.add_argument("--test-size", type=float, default=0.2)
|
| 174 |
-
p.add_argument("--seed", type=int, default=RANDOM_STATE)
|
| 175 |
-
p.add_argument("--auto", action="store_true",
|
| 176 |
-
help="Skip the prompt and pick the model with the best test R^2.")
|
| 177 |
-
p.add_argument("--pick", default=None,
|
| 178 |
-
help="Pick a specific model by short name (svr, rf, et, hgb, gb, xgb, lgbm).")
|
| 179 |
-
return p.parse_args()
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
def main() -> int:
|
| 183 |
-
args = parse_args()
|
| 184 |
-
|
| 185 |
-
print(f"[load] {args.csv}")
|
| 186 |
-
X, y, df = load_dataset(Path(args.csv))
|
| 187 |
-
print(f"[load] features={FEATURE_COLS} target={TARGET_COL} rows={len(df):,}")
|
| 188 |
-
|
| 189 |
-
X_train, X_test, y_train, y_test = train_test_split(
|
| 190 |
-
X, y, test_size=args.test_size, random_state=args.seed,
|
| 191 |
-
)
|
| 192 |
-
print(f"[split] train={len(X_train):,} test={len(X_test):,}")
|
| 193 |
-
|
| 194 |
-
models = build_models()
|
| 195 |
-
results: list[dict] = []
|
| 196 |
-
for short, (display, pipe) in models.items():
|
| 197 |
-
print(f"[fit ] {display:32s} ...", end=" ", flush=True)
|
| 198 |
-
res = evaluate(display, pipe, X_train, X_test, y_train, y_test)
|
| 199 |
-
res["short"] = short
|
| 200 |
-
results.append(res)
|
| 201 |
-
print(f"R2={res['test_R2']:.3f} RMSE={res['test_RMSE']:.3f} MAE={res['test_MAE']:.3f}")
|
| 202 |
-
parity_plot(y_test, res["_yhat_test"], display,
|
| 203 |
-
HERE / f"et_parity_{short}.png")
|
| 204 |
-
|
| 205 |
-
table = pd.DataFrame([
|
| 206 |
-
{k: v for k, v in r.items() if not k.startswith("_") and k != "short"}
|
| 207 |
-
| {"short": r["short"]}
|
| 208 |
-
for r in results
|
| 209 |
-
]).sort_values("test_R2", ascending=False).reset_index(drop=True)
|
| 210 |
-
print("\n=== Model comparison (sorted by test R^2) ===")
|
| 211 |
-
print(table.to_string(index=False, float_format=lambda v: f"{v:.4f}"))
|
| 212 |
-
table.to_csv(OUT_TABLE, index=False)
|
| 213 |
-
print(f"[save] {OUT_TABLE}")
|
| 214 |
-
|
| 215 |
-
by_short = {r["short"]: r for r in results}
|
| 216 |
-
if args.pick is not None:
|
| 217 |
-
if args.pick not in by_short:
|
| 218 |
-
raise SystemExit(f"--pick {args.pick!r} unknown. choose one of {list(by_short)}")
|
| 219 |
-
chosen = by_short[args.pick]
|
| 220 |
-
elif args.auto or not sys.stdin.isatty():
|
| 221 |
-
chosen = by_short[table.iloc[0]["short"]]
|
| 222 |
-
print(f"[auto] picking {chosen['model']} (best test R^2)")
|
| 223 |
-
else:
|
| 224 |
-
prompt = (
|
| 225 |
-
"\nEnter the short name of the model to keep "
|
| 226 |
-
f"({'/'.join(by_short)}), or press Enter for the best test R^2: "
|
| 227 |
-
)
|
| 228 |
-
ans = input(prompt).strip().lower()
|
| 229 |
-
if not ans:
|
| 230 |
-
chosen = by_short[table.iloc[0]["short"]]
|
| 231 |
-
elif ans in by_short:
|
| 232 |
-
chosen = by_short[ans]
|
| 233 |
-
else:
|
| 234 |
-
raise SystemExit(f"Unknown choice {ans!r}; expected one of {list(by_short)}")
|
| 235 |
-
|
| 236 |
-
bundle = {
|
| 237 |
-
"model": chosen["_pipeline"],
|
| 238 |
-
"feature_names": FEATURE_COLS,
|
| 239 |
-
"target_name": TARGET_COL,
|
| 240 |
-
"metrics": {k: chosen[k] for k in ("model", "train_R2", "test_R2", "test_RMSE", "test_MAE")},
|
| 241 |
-
}
|
| 242 |
-
joblib.dump(bundle, OUT_BUNDLE)
|
| 243 |
-
print(f"\n[save] {OUT_BUNDLE}")
|
| 244 |
-
print(f"[done] kept: {chosen['model']} test_R2={chosen['test_R2']:.4f}")
|
| 245 |
-
return 0
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
if __name__ == "__main__":
|
| 249 |
-
raise SystemExit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_ML_GPP/apply_gpp_to_states.py
DELETED
|
@@ -1,160 +0,0 @@
|
|
| 1 |
-
"""Apply the trained GPP model to per-state LAI+weather .npy files.
|
| 2 |
-
|
| 3 |
-
Reads:
|
| 4 |
-
../{state}/data_LAI_geo_wx_2017_to_21/LAI_wx_geo_{state}_120d_{year}.npy
|
| 5 |
-
each of shape (n_pixels, 120, 8) with channels:
|
| 6 |
-
[DOY1, LAI, lon, lat, DOY2, SSI(=SRad), Tmax, Tmin]
|
| 7 |
-
|
| 8 |
-
Writes (per state, per year):
|
| 9 |
-
../{state}/data_GPP_2017_to_21/GPP_{state}_120d_{year}.npy
|
| 10 |
-
shape (n_pixels, 120, 2) with channels [DOY, GPP]
|
| 11 |
-
../{state}/data_GPP_2017_to_21/GPP_{state}_120d_{year}_summary.csv
|
| 12 |
-
per-DOY mean/std/min/max across pixels (handy quick-look)
|
| 13 |
-
|
| 14 |
-
Usage:
|
| 15 |
-
uv run python apply_gpp_to_states.py
|
| 16 |
-
uv run python apply_gpp_to_states.py --states BadenW Bayern --years 2020 2021
|
| 17 |
-
uv run python apply_gpp_to_states.py --bundle gpp_best_model.joblib
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
from __future__ import annotations
|
| 21 |
-
|
| 22 |
-
import argparse
|
| 23 |
-
from pathlib import Path
|
| 24 |
-
|
| 25 |
-
import joblib
|
| 26 |
-
import numpy as np
|
| 27 |
-
import pandas as pd
|
| 28 |
-
|
| 29 |
-
HERE = Path(__file__).resolve().parent
|
| 30 |
-
PROJECT_ROOT = HERE.parent
|
| 31 |
-
DEFAULT_BUNDLE = HERE / "gpp_best_model.joblib"
|
| 32 |
-
|
| 33 |
-
DEFAULT_STATES = [
|
| 34 |
-
"BadenW", "Bayern", "Brandenburg", "Hessen", "MecklenburgV",
|
| 35 |
-
"Niedersachsen", "NordrheinW", "RheinlandP", "Saarland",
|
| 36 |
-
"Sachsen", "SachsenA", "SchleswigH", "Thuringen",
|
| 37 |
-
]
|
| 38 |
-
DEFAULT_YEARS = [2017, 2018, 2019, 2020, 2021]
|
| 39 |
-
|
| 40 |
-
NPY_CHANNELS = ["DOY1", "LAI", "lon", "lat", "DOY2", "SSI", "Tmax", "Tmin"]
|
| 41 |
-
NPY_IDX = {name: i for i, name in enumerate(NPY_CHANNELS)}
|
| 42 |
-
|
| 43 |
-
CSV_TO_NPY = {"DOY": "DOY2", "SLAI": "LAI", "Tmax": "Tmax", "Tmin": "Tmin", "SRad": "SSI"}
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def build_feature_matrix(arr: np.ndarray, feature_names: list[str]) -> np.ndarray:
|
| 47 |
-
"""Map (pixels, 120, 8) -> (pixels*120, len(feature_names)) using CSV->npy mapping."""
|
| 48 |
-
|
| 49 |
-
pixels, days, n_chan = arr.shape
|
| 50 |
-
if n_chan != len(NPY_CHANNELS):
|
| 51 |
-
raise ValueError(
|
| 52 |
-
f"Expected {len(NPY_CHANNELS)} channels in .npy file, got {n_chan}. "
|
| 53 |
-
f"Update NPY_CHANNELS if the layout changed."
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
cols = []
|
| 57 |
-
for f in feature_names:
|
| 58 |
-
if f not in CSV_TO_NPY:
|
| 59 |
-
raise KeyError(
|
| 60 |
-
f"Don't know how to map training feature {f!r} to a channel in the .npy file. "
|
| 61 |
-
f"Known mappings: {CSV_TO_NPY}"
|
| 62 |
-
)
|
| 63 |
-
cols.append(arr[:, :, NPY_IDX[CSV_TO_NPY[f]]].reshape(-1))
|
| 64 |
-
return np.stack(cols, axis=1)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def per_doy_summary(doy: np.ndarray, gpp: np.ndarray) -> pd.DataFrame:
|
| 68 |
-
"""Summarise GPP across pixels for each DOY column (length 120)."""
|
| 69 |
-
|
| 70 |
-
n_pixels, n_days = gpp.shape
|
| 71 |
-
doy_per_day = doy[0]
|
| 72 |
-
return pd.DataFrame({
|
| 73 |
-
"DOY": doy_per_day.astype(int),
|
| 74 |
-
"GPP_mean": gpp.mean(axis=0),
|
| 75 |
-
"GPP_std": gpp.std(axis=0),
|
| 76 |
-
"GPP_min": gpp.min(axis=0),
|
| 77 |
-
"GPP_max": gpp.max(axis=0),
|
| 78 |
-
"n_pixels": np.full(n_days, n_pixels, dtype=int),
|
| 79 |
-
})
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def process_one(arr_path: Path, out_dir: Path, model, feature_names: list[str]) -> Path:
|
| 83 |
-
arr = np.load(arr_path)
|
| 84 |
-
pixels, days, _ = arr.shape
|
| 85 |
-
|
| 86 |
-
X = build_feature_matrix(arr, feature_names)
|
| 87 |
-
yhat = model.predict(X).astype(np.float32).reshape(pixels, days)
|
| 88 |
-
|
| 89 |
-
doy = arr[:, :, NPY_IDX["DOY2"]].astype(np.float32)
|
| 90 |
-
out = np.stack([doy, yhat], axis=2)
|
| 91 |
-
|
| 92 |
-
out_dir.mkdir(parents=True, exist_ok=True)
|
| 93 |
-
out_path = out_dir / arr_path.name.replace("LAI_wx_geo_", "GPP_")
|
| 94 |
-
np.save(out_path, out)
|
| 95 |
-
|
| 96 |
-
summary_path = out_path.with_name(out_path.stem + "_summary.csv")
|
| 97 |
-
per_doy_summary(doy, yhat).to_csv(summary_path, index=False)
|
| 98 |
-
return out_path
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def parse_args() -> argparse.Namespace:
|
| 102 |
-
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
|
| 103 |
-
p.add_argument("--bundle", default=str(DEFAULT_BUNDLE),
|
| 104 |
-
help=f"joblib bundle saved by train_gpp_models.py (default: {DEFAULT_BUNDLE.name})")
|
| 105 |
-
p.add_argument("--root", default=str(PROJECT_ROOT),
|
| 106 |
-
help=f"Project root that contains per-state folders (default: {PROJECT_ROOT})")
|
| 107 |
-
p.add_argument("--states", nargs="+", default=DEFAULT_STATES,
|
| 108 |
-
help="Subset of state folder names to process.")
|
| 109 |
-
p.add_argument("--years", nargs="+", type=int, default=DEFAULT_YEARS,
|
| 110 |
-
help="Subset of years to process.")
|
| 111 |
-
p.add_argument("--out-folder", default="data_GPP_2017_to_21",
|
| 112 |
-
help="Output sub-folder name created inside each state directory.")
|
| 113 |
-
return p.parse_args()
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
def main() -> int:
|
| 117 |
-
args = parse_args()
|
| 118 |
-
bundle_path = Path(args.bundle)
|
| 119 |
-
if not bundle_path.exists():
|
| 120 |
-
raise SystemExit(
|
| 121 |
-
f"Model bundle {bundle_path} not found. Run train_gpp_models.py first."
|
| 122 |
-
)
|
| 123 |
-
|
| 124 |
-
bundle = joblib.load(bundle_path)
|
| 125 |
-
model = bundle["model"]
|
| 126 |
-
feature_names = bundle["feature_names"]
|
| 127 |
-
metrics = bundle.get("metrics", {})
|
| 128 |
-
print(f"[load] {bundle_path}")
|
| 129 |
-
print(f"[load] model='{metrics.get('model', type(model).__name__)}' "
|
| 130 |
-
f"test_R2={metrics.get('test_R2', float('nan')):.4f} "
|
| 131 |
-
f"features={feature_names}")
|
| 132 |
-
|
| 133 |
-
root = Path(args.root)
|
| 134 |
-
n_done = n_skipped = 0
|
| 135 |
-
for state in args.states:
|
| 136 |
-
in_dir = root / state / "data_LAI_geo_wx_2017_to_21"
|
| 137 |
-
out_dir = root / state / args.out_folder
|
| 138 |
-
if not in_dir.is_dir():
|
| 139 |
-
print(f"[skip] {state}: no folder {in_dir}")
|
| 140 |
-
n_skipped += 1
|
| 141 |
-
continue
|
| 142 |
-
for year in args.years:
|
| 143 |
-
arr_path = in_dir / f"LAI_wx_geo_{state}_120d_{year}.npy"
|
| 144 |
-
if not arr_path.exists():
|
| 145 |
-
print(f"[skip] {state} {year}: missing {arr_path.name}")
|
| 146 |
-
n_skipped += 1
|
| 147 |
-
continue
|
| 148 |
-
out_path = process_one(arr_path, out_dir, model, feature_names)
|
| 149 |
-
arr_size_mb = arr_path.stat().st_size / 1e6
|
| 150 |
-
out_size_mb = out_path.stat().st_size / 1e6
|
| 151 |
-
print(f"[ok ] {state:14s} {year} "
|
| 152 |
-
f"in={arr_size_mb:6.1f}MB out={out_size_mb:5.1f}MB -> {out_path}")
|
| 153 |
-
n_done += 1
|
| 154 |
-
|
| 155 |
-
print(f"\n[done] {n_done} files written, {n_skipped} skipped")
|
| 156 |
-
return 0
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
if __name__ == "__main__":
|
| 160 |
-
raise SystemExit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_ML_GPP/apply_gpp_to_states_CC.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
"""Apply the trained GPP model to per-state LAI+weather .npy files
|
| 2 |
-
under climate-change (CC) scenarios.
|
| 3 |
-
|
| 4 |
-
Reads (per state, per scenario, per year):
|
| 5 |
-
../{state}/data_LAI_geo_wx_CC{ref_year}_{rcp}/LAI_wx_geo_{state}_120d_{file_year}.npy
|
| 6 |
-
each of shape (n_pixels, 120, 8) with channels:
|
| 7 |
-
[DOY1, LAI, lon, lat, DOY2, SSI(=SRad), Tmax, Tmin]
|
| 8 |
-
|
| 9 |
-
Note: each CC folder typically contains 5 yearly files spanning a 5-year window
|
| 10 |
-
ending shortly before the reference year, e.g.:
|
| 11 |
-
CC2050 -> 2041..2045
|
| 12 |
-
CC2070 -> 2061..2065
|
| 13 |
-
CC2090 -> 2081..2085
|
| 14 |
-
This script discovers every .npy in each scenario folder, so it works regardless
|
| 15 |
-
of which file_years are present.
|
| 16 |
-
|
| 17 |
-
Writes (per state, per scenario, per year):
|
| 18 |
-
../{state}/data_GPP_CC{ref_year}_{rcp}_ML/GPP_{state}_120d_{file_year}.npy
|
| 19 |
-
shape (n_pixels, 120, 2) with channels [DOY, GPP]
|
| 20 |
-
../{state}/data_GPP_CC{ref_year}_{rcp}_ML/GPP_{state}_120d_{file_year}_summary.csv
|
| 21 |
-
per-DOY mean/std/min/max across pixels.
|
| 22 |
-
|
| 23 |
-
Usage:
|
| 24 |
-
uv run python apply_gpp_to_states_CC.py
|
| 25 |
-
uv run python apply_gpp_to_states_CC.py --states BadenW Bayern
|
| 26 |
-
uv run python apply_gpp_to_states_CC.py --ref-years 2050 2090 --rcps RCP85
|
| 27 |
-
uv run python apply_gpp_to_states_CC.py --bundle gpp_best_model.joblib
|
| 28 |
-
"""
|
| 29 |
-
|
| 30 |
-
from __future__ import annotations
|
| 31 |
-
|
| 32 |
-
import argparse
|
| 33 |
-
from pathlib import Path
|
| 34 |
-
|
| 35 |
-
import joblib
|
| 36 |
-
import numpy as np
|
| 37 |
-
|
| 38 |
-
from apply_gpp_to_states import (
|
| 39 |
-
DEFAULT_STATES,
|
| 40 |
-
NPY_IDX,
|
| 41 |
-
build_feature_matrix,
|
| 42 |
-
per_doy_summary,
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
HERE = Path(__file__).resolve().parent
|
| 46 |
-
PROJECT_ROOT = HERE.parent
|
| 47 |
-
DEFAULT_BUNDLE = HERE / "gpp_best_model.joblib"
|
| 48 |
-
|
| 49 |
-
DEFAULT_REF_YEARS = [2050, 2070, 2090]
|
| 50 |
-
DEFAULT_RCPS = ["RCP26", "RCP85"]
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def process_one(arr_path: Path, out_dir: Path, model, feature_names: list[str]) -> Path | None:
|
| 54 |
-
"""Run inference on a single CC .npy file. Returns None if the file is empty/corrupt."""
|
| 55 |
-
|
| 56 |
-
if arr_path.stat().st_size == 0:
|
| 57 |
-
return None
|
| 58 |
-
try:
|
| 59 |
-
arr = np.load(arr_path)
|
| 60 |
-
except (EOFError, ValueError, OSError):
|
| 61 |
-
return None
|
| 62 |
-
if arr.ndim != 3:
|
| 63 |
-
return None
|
| 64 |
-
pixels, days, _ = arr.shape
|
| 65 |
-
|
| 66 |
-
X = build_feature_matrix(arr, feature_names)
|
| 67 |
-
yhat = model.predict(X).astype(np.float32).reshape(pixels, days)
|
| 68 |
-
|
| 69 |
-
doy = arr[:, :, NPY_IDX["DOY2"]].astype(np.float32)
|
| 70 |
-
out = np.stack([doy, yhat], axis=2)
|
| 71 |
-
|
| 72 |
-
out_dir.mkdir(parents=True, exist_ok=True)
|
| 73 |
-
out_path = out_dir / arr_path.name.replace("LAI_wx_geo_", "GPP_")
|
| 74 |
-
np.save(out_path, out)
|
| 75 |
-
|
| 76 |
-
summary_path = out_path.with_name(out_path.stem + "_summary.csv")
|
| 77 |
-
per_doy_summary(doy, yhat).to_csv(summary_path, index=False)
|
| 78 |
-
return out_path
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def parse_args() -> argparse.Namespace:
|
| 82 |
-
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
|
| 83 |
-
p.add_argument("--bundle", default=str(DEFAULT_BUNDLE),
|
| 84 |
-
help=f"joblib bundle saved by train_gpp_models.py (default: {DEFAULT_BUNDLE.name})")
|
| 85 |
-
p.add_argument("--root", default=str(PROJECT_ROOT),
|
| 86 |
-
help=f"Project root that contains per-state folders (default: {PROJECT_ROOT})")
|
| 87 |
-
p.add_argument("--states", nargs="+", default=DEFAULT_STATES,
|
| 88 |
-
help="Subset of state folder names to process.")
|
| 89 |
-
p.add_argument("--ref-years", nargs="+", type=int, default=DEFAULT_REF_YEARS,
|
| 90 |
-
help="Reference years (folder labels): default 2050 2070 2090.")
|
| 91 |
-
p.add_argument("--rcps", nargs="+", default=DEFAULT_RCPS,
|
| 92 |
-
help="Scenario tags (default: RCP26 RCP85).")
|
| 93 |
-
return p.parse_args()
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def main() -> int:
|
| 97 |
-
args = parse_args()
|
| 98 |
-
bundle_path = Path(args.bundle)
|
| 99 |
-
if not bundle_path.exists():
|
| 100 |
-
raise SystemExit(
|
| 101 |
-
f"Model bundle {bundle_path} not found. Run train_gpp_models.py first."
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
bundle = joblib.load(bundle_path)
|
| 105 |
-
model = bundle["model"]
|
| 106 |
-
feature_names = bundle["feature_names"]
|
| 107 |
-
metrics = bundle.get("metrics", {})
|
| 108 |
-
print(f"[load] {bundle_path}")
|
| 109 |
-
print(f"[load] model='{metrics.get('model', type(model).__name__)}' "
|
| 110 |
-
f"test_R2={metrics.get('test_R2', float('nan')):.4f} "
|
| 111 |
-
f"features={feature_names}")
|
| 112 |
-
|
| 113 |
-
root = Path(args.root)
|
| 114 |
-
n_done = n_skipped = 0
|
| 115 |
-
for state in args.states:
|
| 116 |
-
for ref_year in args.ref_years:
|
| 117 |
-
for rcp in args.rcps:
|
| 118 |
-
in_dir = root / state / f"data_LAI_geo_wx_CC{ref_year}_{rcp}"
|
| 119 |
-
out_dir = root / state / f"data_GPP_CC{ref_year}_{rcp}_ML"
|
| 120 |
-
if not in_dir.is_dir():
|
| 121 |
-
print(f"[skip] {state} CC{ref_year} {rcp}: no folder {in_dir}")
|
| 122 |
-
n_skipped += 1
|
| 123 |
-
continue
|
| 124 |
-
arr_paths = sorted(in_dir.glob(f"LAI_wx_geo_{state}_120d_*.npy"))
|
| 125 |
-
if not arr_paths:
|
| 126 |
-
print(f"[skip] {state} CC{ref_year} {rcp}: no .npy files in {in_dir}")
|
| 127 |
-
n_skipped += 1
|
| 128 |
-
continue
|
| 129 |
-
for arr_path in arr_paths:
|
| 130 |
-
file_year = arr_path.stem.split("_")[-1]
|
| 131 |
-
out_path = process_one(arr_path, out_dir, model, feature_names)
|
| 132 |
-
if out_path is None:
|
| 133 |
-
print(f"[skip] {state:14s} CC{ref_year} {rcp} "
|
| 134 |
-
f"yr={file_year} empty/corrupt input ({arr_path.name})")
|
| 135 |
-
n_skipped += 1
|
| 136 |
-
continue
|
| 137 |
-
in_mb = arr_path.stat().st_size / 1e6
|
| 138 |
-
out_mb = out_path.stat().st_size / 1e6
|
| 139 |
-
print(f"[ok ] {state:14s} CC{ref_year} {rcp} "
|
| 140 |
-
f"yr={file_year} in={in_mb:6.1f}MB out={out_mb:5.1f}MB -> {out_path}")
|
| 141 |
-
n_done += 1
|
| 142 |
-
|
| 143 |
-
print(f"\n[done] {n_done} files written, {n_skipped} skipped")
|
| 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
|
|
|
Scripts_ML_GPP/gpp_model_comparison.csv
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
model,train_R2,test_R2,test_RMSE,test_MAE,short
|
| 2 |
-
ExT,0.9999957154007364,0.7362586543064307,2.7146117209808143,2.04557304587156,et
|
| 3 |
-
RF,0.9649085840575606,0.724795323367248,2.7729785866539265,2.1082658587811256,rf
|
| 4 |
-
XGB,0.9834621347498868,0.7140691320624206,2.8265009276259936,2.103869253974442,xgb
|
| 5 |
-
GB,0.8717985317627104,0.7127967590072579,2.8327828160243502,2.1704373565995185,gb
|
| 6 |
-
HGB,0.9534688493650066,0.7078201243981701,2.8572205231836296,2.1661548654525165,hgb
|
| 7 |
-
SVR,0.7097001689945401,0.7044915973771844,2.8734492304788954,2.1869617198118716,svr
|
| 8 |
-
LightGBM,0.9942791618090159,0.6894203391848521,2.945812608689964,2.222975569060012,lgbm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_ML_GPP/main.py
DELETED
|
@@ -1,6 +0,0 @@
|
|
| 1 |
-
def main():
|
| 2 |
-
print("Hello from sim-gpp-wh-uv!")
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
if __name__ == "__main__":
|
| 6 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scripts_ML_GPP/train_gpp_models.py
DELETED
|
@@ -1,249 +0,0 @@
|
|
| 1 |
-
"""Train ML regressors to simulate GPP from DOY, LAI, Tmax, Tmin, SRad.
|
| 2 |
-
|
| 3 |
-
Inputs: combined_wheat_RSCM_out_v2.csv (columns include DOY, SLAI, Tmax, Tmin, SRad, GPP)
|
| 4 |
-
Models: SVR, RandomForest, ExtraTrees, HistGradientBoosting, GradientBoosting, XGBoost, LightGBM
|
| 5 |
-
Output: gpp_best_model.joblib (chosen model bundled with its StandardScaler and feature names)
|
| 6 |
-
gpp_model_comparison.csv
|
| 7 |
-
gpp_parity_<model>.png (one parity plot per model on the test split)
|
| 8 |
-
|
| 9 |
-
Usage:
|
| 10 |
-
uv run python train_gpp_models.py # interactive: pick the model after table is shown
|
| 11 |
-
uv run python train_gpp_models.py --auto # auto-pick the model with the best test R^2
|
| 12 |
-
uv run python train_gpp_models.py --pick xgb # pick a specific model by short name
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
from __future__ import annotations
|
| 16 |
-
|
| 17 |
-
import argparse
|
| 18 |
-
import sys
|
| 19 |
-
from pathlib import Path
|
| 20 |
-
|
| 21 |
-
import joblib
|
| 22 |
-
import matplotlib.pyplot as plt
|
| 23 |
-
import numpy as np
|
| 24 |
-
import pandas as pd
|
| 25 |
-
from sklearn.ensemble import (
|
| 26 |
-
ExtraTreesRegressor,
|
| 27 |
-
GradientBoostingRegressor,
|
| 28 |
-
HistGradientBoostingRegressor,
|
| 29 |
-
RandomForestRegressor,
|
| 30 |
-
)
|
| 31 |
-
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
|
| 32 |
-
from sklearn.model_selection import train_test_split
|
| 33 |
-
from sklearn.pipeline import Pipeline
|
| 34 |
-
from sklearn.preprocessing import StandardScaler
|
| 35 |
-
from sklearn.svm import SVR
|
| 36 |
-
|
| 37 |
-
import lightgbm as lgb
|
| 38 |
-
import xgboost as xgb
|
| 39 |
-
|
| 40 |
-
HERE = Path(__file__).resolve().parent
|
| 41 |
-
CSV_PATH = HERE / "combined_wheat_RSCM_out_v2.csv"
|
| 42 |
-
OUT_BUNDLE = HERE / "gpp_best_model.joblib"
|
| 43 |
-
OUT_TABLE = HERE / "gpp_model_comparison.csv"
|
| 44 |
-
|
| 45 |
-
FEATURE_COLS = ["DOY", "SLAI", "Tmax", "Tmin", "SRad"]
|
| 46 |
-
TARGET_COL = "GPP"
|
| 47 |
-
RANDOM_STATE = 42
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def build_models() -> dict[str, tuple[str, Pipeline]]:
|
| 51 |
-
"""Return short_name -> (display_name, sklearn Pipeline)."""
|
| 52 |
-
|
| 53 |
-
return {
|
| 54 |
-
"svr": (
|
| 55 |
-
"Support Vector Regression",
|
| 56 |
-
Pipeline([
|
| 57 |
-
("scaler", StandardScaler()),
|
| 58 |
-
("model", SVR(kernel="rbf", C=10.0, gamma="scale", epsilon=0.1)),
|
| 59 |
-
]),
|
| 60 |
-
),
|
| 61 |
-
"rf": (
|
| 62 |
-
"Random Forest",
|
| 63 |
-
Pipeline([
|
| 64 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 65 |
-
("model", RandomForestRegressor(
|
| 66 |
-
n_estimators=400, max_depth=None, n_jobs=-1, random_state=RANDOM_STATE,
|
| 67 |
-
)),
|
| 68 |
-
]),
|
| 69 |
-
),
|
| 70 |
-
"et": (
|
| 71 |
-
"Extra Trees",
|
| 72 |
-
Pipeline([
|
| 73 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 74 |
-
("model", ExtraTreesRegressor(
|
| 75 |
-
n_estimators=500, max_depth=None, n_jobs=-1, random_state=RANDOM_STATE,
|
| 76 |
-
)),
|
| 77 |
-
]),
|
| 78 |
-
),
|
| 79 |
-
"hgb": (
|
| 80 |
-
"Histogram Gradient Boosting",
|
| 81 |
-
Pipeline([
|
| 82 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 83 |
-
("model", HistGradientBoostingRegressor(
|
| 84 |
-
max_iter=500, learning_rate=0.05, max_depth=None,
|
| 85 |
-
random_state=RANDOM_STATE,
|
| 86 |
-
)),
|
| 87 |
-
]),
|
| 88 |
-
),
|
| 89 |
-
"gb": (
|
| 90 |
-
"Gradient Boosting",
|
| 91 |
-
Pipeline([
|
| 92 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 93 |
-
("model", GradientBoostingRegressor(
|
| 94 |
-
n_estimators=400, learning_rate=0.05, max_depth=4,
|
| 95 |
-
random_state=RANDOM_STATE,
|
| 96 |
-
)),
|
| 97 |
-
]),
|
| 98 |
-
),
|
| 99 |
-
"xgb": (
|
| 100 |
-
"XGBoost",
|
| 101 |
-
Pipeline([
|
| 102 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 103 |
-
("model", xgb.XGBRegressor(
|
| 104 |
-
n_estimators=600, learning_rate=0.05, max_depth=6,
|
| 105 |
-
subsample=0.9, colsample_bytree=0.9,
|
| 106 |
-
objective="reg:squarederror", tree_method="hist",
|
| 107 |
-
n_jobs=-1, random_state=RANDOM_STATE, verbosity=0,
|
| 108 |
-
)),
|
| 109 |
-
]),
|
| 110 |
-
),
|
| 111 |
-
"lgbm": (
|
| 112 |
-
"LightGBM",
|
| 113 |
-
Pipeline([
|
| 114 |
-
("scaler", StandardScaler(with_mean=False, with_std=False)),
|
| 115 |
-
("model", lgb.LGBMRegressor(
|
| 116 |
-
n_estimators=800, learning_rate=0.05, num_leaves=63,
|
| 117 |
-
subsample=0.9, colsample_bytree=0.9, min_child_samples=20,
|
| 118 |
-
n_jobs=-1, random_state=RANDOM_STATE, verbosity=-1,
|
| 119 |
-
)),
|
| 120 |
-
]),
|
| 121 |
-
),
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def load_dataset(csv_path: Path) -> tuple[np.ndarray, np.ndarray, pd.DataFrame]:
|
| 126 |
-
df = pd.read_csv(csv_path)
|
| 127 |
-
needed = FEATURE_COLS + [TARGET_COL]
|
| 128 |
-
missing = [c for c in needed if c not in df.columns]
|
| 129 |
-
if missing:
|
| 130 |
-
raise SystemExit(f"CSV {csv_path} is missing required columns: {missing}")
|
| 131 |
-
|
| 132 |
-
df = df.dropna(subset=needed).copy()
|
| 133 |
-
X = df[FEATURE_COLS].to_numpy(dtype=np.float64)
|
| 134 |
-
y = df[TARGET_COL].to_numpy(dtype=np.float64)
|
| 135 |
-
return X, y, df
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
def evaluate(name: str, model: Pipeline, X_train, X_test, y_train, y_test) -> dict:
|
| 139 |
-
model.fit(X_train, y_train)
|
| 140 |
-
yhat_train = model.predict(X_train)
|
| 141 |
-
yhat_test = model.predict(X_test)
|
| 142 |
-
return {
|
| 143 |
-
"model": name,
|
| 144 |
-
"train_R2": r2_score(y_train, yhat_train),
|
| 145 |
-
"test_R2": r2_score(y_test, yhat_test),
|
| 146 |
-
"test_RMSE": float(np.sqrt(mean_squared_error(y_test, yhat_test))),
|
| 147 |
-
"test_MAE": mean_absolute_error(y_test, yhat_test),
|
| 148 |
-
"_yhat_test": yhat_test,
|
| 149 |
-
"_pipeline": model,
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
def parity_plot(y_true, y_pred, title: str, out_png: Path) -> None:
|
| 154 |
-
fig, ax = plt.subplots(figsize=(5.0, 5.0))
|
| 155 |
-
ax.scatter(y_true, y_pred, s=8, alpha=0.4, edgecolor="none")
|
| 156 |
-
lo = float(min(y_true.min(), y_pred.min()))
|
| 157 |
-
hi = float(max(y_true.max(), y_pred.max()))
|
| 158 |
-
ax.plot([lo, hi], [lo, hi], "k--", lw=1.0)
|
| 159 |
-
r2 = r2_score(y_true, y_pred)
|
| 160 |
-
rmse = float(np.sqrt(mean_squared_error(y_true, y_pred)))
|
| 161 |
-
ax.set_xlabel(f"Observed {TARGET_COL}")
|
| 162 |
-
ax.set_ylabel(f"Predicted {TARGET_COL}")
|
| 163 |
-
ax.set_title(f"{title}\nR^2 = {r2:.3f} | RMSE = {rmse:.3f}")
|
| 164 |
-
ax.grid(True, alpha=0.3)
|
| 165 |
-
fig.tight_layout()
|
| 166 |
-
fig.savefig(out_png, dpi=140)
|
| 167 |
-
plt.close(fig)
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
def parse_args() -> argparse.Namespace:
|
| 171 |
-
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
|
| 172 |
-
p.add_argument("--csv", default=str(CSV_PATH), help=f"Path to CSV (default: {CSV_PATH.name})")
|
| 173 |
-
p.add_argument("--test-size", type=float, default=0.2)
|
| 174 |
-
p.add_argument("--seed", type=int, default=RANDOM_STATE)
|
| 175 |
-
p.add_argument("--auto", action="store_true",
|
| 176 |
-
help="Skip the prompt and pick the model with the best test R^2.")
|
| 177 |
-
p.add_argument("--pick", default=None,
|
| 178 |
-
help="Pick a specific model by short name (svr, rf, et, hgb, gb, xgb, lgbm).")
|
| 179 |
-
return p.parse_args()
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
def main() -> int:
|
| 183 |
-
args = parse_args()
|
| 184 |
-
|
| 185 |
-
print(f"[load] {args.csv}")
|
| 186 |
-
X, y, df = load_dataset(Path(args.csv))
|
| 187 |
-
print(f"[load] features={FEATURE_COLS} target={TARGET_COL} rows={len(df):,}")
|
| 188 |
-
|
| 189 |
-
X_train, X_test, y_train, y_test = train_test_split(
|
| 190 |
-
X, y, test_size=args.test_size, random_state=args.seed,
|
| 191 |
-
)
|
| 192 |
-
print(f"[split] train={len(X_train):,} test={len(X_test):,}")
|
| 193 |
-
|
| 194 |
-
models = build_models()
|
| 195 |
-
results: list[dict] = []
|
| 196 |
-
for short, (display, pipe) in models.items():
|
| 197 |
-
print(f"[fit ] {display:32s} ...", end=" ", flush=True)
|
| 198 |
-
res = evaluate(display, pipe, X_train, X_test, y_train, y_test)
|
| 199 |
-
res["short"] = short
|
| 200 |
-
results.append(res)
|
| 201 |
-
print(f"R2={res['test_R2']:.3f} RMSE={res['test_RMSE']:.3f} MAE={res['test_MAE']:.3f}")
|
| 202 |
-
parity_plot(y_test, res["_yhat_test"], display,
|
| 203 |
-
HERE / f"gpp_parity_{short}.png")
|
| 204 |
-
|
| 205 |
-
table = pd.DataFrame([
|
| 206 |
-
{k: v for k, v in r.items() if not k.startswith("_") and k != "short"}
|
| 207 |
-
| {"short": r["short"]}
|
| 208 |
-
for r in results
|
| 209 |
-
]).sort_values("test_R2", ascending=False).reset_index(drop=True)
|
| 210 |
-
print("\n=== Model comparison (sorted by test R^2) ===")
|
| 211 |
-
print(table.to_string(index=False, float_format=lambda v: f"{v:.4f}"))
|
| 212 |
-
table.to_csv(OUT_TABLE, index=False)
|
| 213 |
-
print(f"[save] {OUT_TABLE}")
|
| 214 |
-
|
| 215 |
-
by_short = {r["short"]: r for r in results}
|
| 216 |
-
if args.pick is not None:
|
| 217 |
-
if args.pick not in by_short:
|
| 218 |
-
raise SystemExit(f"--pick {args.pick!r} unknown. choose one of {list(by_short)}")
|
| 219 |
-
chosen = by_short[args.pick]
|
| 220 |
-
elif args.auto or not sys.stdin.isatty():
|
| 221 |
-
chosen = by_short[table.iloc[0]["short"]]
|
| 222 |
-
print(f"[auto] picking {chosen['model']} (best test R^2)")
|
| 223 |
-
else:
|
| 224 |
-
prompt = (
|
| 225 |
-
"\nEnter the short name of the model to keep "
|
| 226 |
-
f"({'/'.join(by_short)}), or press Enter for the best test R^2: "
|
| 227 |
-
)
|
| 228 |
-
ans = input(prompt).strip().lower()
|
| 229 |
-
if not ans:
|
| 230 |
-
chosen = by_short[table.iloc[0]["short"]]
|
| 231 |
-
elif ans in by_short:
|
| 232 |
-
chosen = by_short[ans]
|
| 233 |
-
else:
|
| 234 |
-
raise SystemExit(f"Unknown choice {ans!r}; expected one of {list(by_short)}")
|
| 235 |
-
|
| 236 |
-
bundle = {
|
| 237 |
-
"model": chosen["_pipeline"],
|
| 238 |
-
"feature_names": FEATURE_COLS,
|
| 239 |
-
"target_name": TARGET_COL,
|
| 240 |
-
"metrics": {k: chosen[k] for k in ("model", "train_R2", "test_R2", "test_RMSE", "test_MAE")},
|
| 241 |
-
}
|
| 242 |
-
joblib.dump(bundle, OUT_BUNDLE)
|
| 243 |
-
print(f"\n[save] {OUT_BUNDLE}")
|
| 244 |
-
print(f"[done] kept: {chosen['model']} test_R2={chosen['test_R2']:.4f}")
|
| 245 |
-
return 0
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
if __name__ == "__main__":
|
| 249 |
-
raise SystemExit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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