Download 04_exp2_memory_decouple/exp2b_structural.py from eduzrh/EcoMemory-Extreme-Events: direct link, hf CLI and curl.
- Browser
- Download file 9.44 kB
-
https://huggingface.co/datasets/eduzrh/EcoMemory-Extreme-Events/resolve/main/04_exp2_memory_decouple/exp2b_structural.py
- Command line
-
hf download hf://datasets/eduzrh/EcoMemory-Extreme-Events/04_exp2_memory_decouple/exp2b_structural.py
-
curl -L -o exp2b_structural.py https://huggingface.co/datasets/eduzrh/EcoMemory-Extreme-Events/resolve/main/04_exp2_memory_decouple/exp2b_structural.py
9.44 kB
| """ | |
| Experiment 2b — retrain with the structure of section 3.6 and see whether the | |
| water channel becomes identifiable. | |
| Identity problem in experiment 2 | |
| With five meteorological inputs the network can rebuild the soil-water state | |
| from antecedent precipitation, so replacing soil water removes no information | |
| (the naive cut moves the prediction by 0.0007). The 2x2 design only | |
| redistributes the same antecedent weather between two arms. | |
| This script builds the alternative structure | |
| * the only antecedent channel is the bucket state u_t, a deterministic | |
| function of precipitation and evaporative demand (no free parameters of the | |
| network feed into it, no meteorological input at lags > 0) | |
| * current-month weather enters as a per-window attribute, not as a sequence | |
| Under this structure "remove the antecedent water" is a well-defined operation: | |
| the network cannot reconstruct u from anything else, because nothing else is | |
| given. The test is then how much of the black-box (met-only) memory the water | |
| channel can reproduce. | |
| Delta_met = | f_met(full antecedent) - f_met(climatological antecedent) | | |
| Delta_struct = | f_str(full u) - f_str(climatological u) | | |
| R = mean|Delta_struct| / mean|Delta_met| | |
| R is the fraction of antecedent dependence that a physically constrained water | |
| pathway can carry; 1 - R bounds the non-water part (tissue damage, canopy | |
| carry-over, and any lagged meteorological pathway that is not mediated by | |
| water). | |
| Outputs: exp2b_stats.json, exp2b_deltas.npz | |
| """ | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| ROOT = Path(__file__).resolve().parents[2] | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from ecomodel import GPPModel, build_windows, standardise, train_model # noqa: E402 | |
| from exp2_analysis import bucket_series # noqa: E402 | |
| OUT = Path(__file__).resolve().parent | |
| PROC = ROOT / "data" / "processed" | |
| SEQ = 60 | |
| DYN5 = ["precip", "tair", "vpd", "swrad", "wind"] | |
| KEEP_CUR = 4 # months treated as "current", not antecedent | |
| def main(): | |
| z = np.load(PROC / "cells_monthly.npz", allow_pickle=True) | |
| feats = [str(x) for x in z["feats"]] | |
| i5 = [feats.index(f) for f in DYN5] | |
| dyn5 = z["dyn"][:, :, i5].astype(np.float32) | |
| et0 = z["dyn"][:, :, feats.index("et0")].astype(np.float32) | |
| sm_obs = z["dyn"][:, :, feats.index("sm_root")].astype(np.float32) | |
| gpp = z["gpp"].astype(np.float32) | |
| static = z["static"].astype(np.float32) | |
| months = z["months"] | |
| n_cell, nt = gpp.shape | |
| good = ((np.isfinite(gpp).mean(axis=1) > 0.9) | |
| & np.isfinite(static).all(axis=1) | |
| & np.isfinite(dyn5).all(axis=(1, 2))) | |
| y = np.clip(gpp / np.nanmean(gpp, axis=1, keepdims=True), 0, 4).astype(np.float32) | |
| pars = json.load(open(OUT / "bucket_fit.json")) | |
| wet = bucket_series(dyn5[:, :, 0], et0, sm_obs, pars) # (n_cell, nt) in [0,1] | |
| print("bucket wetness range %.3f-%.3f" % (wet.min(), wet.max()), flush=True) | |
| mon = months % 100 | |
| # standardisation built from training years only, on cell level | |
| mu_u = np.nanmean(wet[good][:, :243], axis=1, keepdims=True) # 1981-2001 approx; refit below | |
| # use the same split as the models: windows ending <= 2005 | |
| tr_months = months <= 200512 | |
| mu_u = np.nanmean(wet[:, tr_months], axis=1, keepdims=True) | |
| sd_u = np.nanstd(wet[:, tr_months], axis=1, keepdims=True) | |
| sd_u[sd_u == 0] = 1 | |
| u = ((wet - mu_u) / sd_u).astype(np.float32) | |
| dyn_s, stat_s, mu_d, sd_d = standardise(dyn5, static, y, good) | |
| x, ys, ci, ti = build_windows(u[:, :, None], y, months, SEQ) | |
| keep = good[ci] | |
| x, ys, ci, ti = x[keep], ys[keep], ci[keep], ti[keep] | |
| cur = dyn_s[ci, ti] # current-month met | |
| s = np.concatenate([stat_s[ci], cur], axis=1).astype(np.float32) | |
| yr = months[ti] // 100 | |
| tr, va, te = yr <= 2005, (yr >= 2006) & (yr <= 2010), yr >= 2011 | |
| print("windows", tr.sum(), va.sum(), te.sum(), "n_stat", s.shape[1], flush=True) | |
| ckpt = OUT / "model_struct.pt" | |
| if ckpt.exists(): | |
| blob = torch.load(ckpt, map_location="cpu") | |
| model = GPPModel(blob["n_dyn"], blob["n_stat"], blob["hidden"]) | |
| model.load_state_dict(blob["state"]) | |
| print("loaded cached structural model, epoch", blob["epoch"], flush=True) | |
| else: | |
| model, _ = train_model(x[tr], s[tr], ys[tr], x[va], s[va], ys[va], | |
| n_stat=s.shape[1], hidden=48, epochs=60, | |
| batch=1024, lr=1e-3, patience=8, ckpt_path=ckpt) | |
| model.eval() | |
| with torch.no_grad(): | |
| pred = model(torch.from_numpy(x[te]), torch.from_numpy(s[te])).numpy() | |
| nse = 1 - ((pred - ys[te]) ** 2).sum() / ((ys[te] - ys[te].mean()) ** 2).sum() | |
| r = float(np.corrcoef(pred, ys[te])[0, 1]) | |
| print("structural test NSE %.3f r %.3f" % (nse, r), flush=True) | |
| # ---- sample the same way as experiments 1 and 2 | |
| rng = np.random.default_rng(7) | |
| sel = [] | |
| for c in np.unique(ci[te]): | |
| ii = np.where(te & (ci == c))[0] | |
| sel.extend(rng.choice(ii, size=min(20, len(ii)), replace=False)) | |
| sel = np.array(sel) | |
| xs, ss, cs, ts = x[sel], s[sel], ci[sel], ti[sel] | |
| # ---- climatological water history: run the bucket on a repeated | |
| # climatological year, then look up the calendar month of each lag | |
| clim_met = np.zeros((n_cell, 12, 5), dtype=np.float32) | |
| for m in range(1, 13): | |
| clim_met[:, m - 1] = np.nanmean(dyn5[:, mon == m], axis=1) | |
| spin = np.concatenate([clim_met, clim_met, clim_met], axis=1) # 36 months | |
| wet_clim = bucket_series(spin[:, :, 0], np.tile( | |
| np.nanmean(et0[:, mon == 1], axis=1)[:, None], (1, 36)).astype(np.float32), | |
| wet[:, :1].repeat(36, axis=1), pars) | |
| # month order of the spin-up is Jan..Dec repeated; take the last 12 months | |
| wet_tab = np.stack([wet_clim[:, 24 + m] for m in range(12)], axis=1) # (n_cell,12) | |
| u_tab = (wet_tab - mu_u) / sd_u | |
| mons = months[ts[:, None] - SEQ + 1 + np.arange(SEQ)[None, :]] % 100 | |
| u_clim_seq = np.stack([u_tab[cs[k], mons[k] - 1] for k in range(len(sel))]) | |
| x_cut = xs.copy() | |
| x_cut[:, :-KEEP_CUR, 0] = u_clim_seq[:, :-KEEP_CUR] | |
| with torch.no_grad(): | |
| fa = model(torch.from_numpy(xs), torch.from_numpy(ss)).numpy() | |
| fd = model(torch.from_numpy(x_cut), torch.from_numpy(ss)).numpy() | |
| d_struct = fa - fd | |
| # ---- black-box reference: the met-only model of experiment 1 | |
| blob = torch.load(Path(__file__).resolve().parents[1] / "03_exp1_unmask_human" / "model_base.pt", | |
| map_location="cpu") | |
| m_met_model = GPPModel(blob["n_dyn"], blob["n_stat"], blob["hidden"]) | |
| m_met_model.load_state_dict(blob["state"]) | |
| m_met_model.eval() | |
| clim5 = np.zeros((n_cell, 12, 5), dtype=np.float32) | |
| for m in range(1, 13): | |
| clim5[:, m - 1] = np.nanmean(dyn5[:, mon == m], axis=1) | |
| clim5_s = (clim5 - mu_d) / sd_d | |
| mons60 = months[ts[:, None] - SEQ + 1 + np.arange(SEQ)[None, :]] % 100 | |
| xmet = np.stack([dyn_s[cs[k], ts[k] - SEQ + 1:ts[k] + 1] for k in range(len(sel))]) | |
| xmet_cut = xmet.copy() | |
| for k in range(len(sel)): | |
| xmet_cut[k, :-KEEP_CUR] = clim5_s[cs[k], mons60[k][:-KEEP_CUR] - 1] | |
| with torch.no_grad(): | |
| ga = m_met_model(torch.from_numpy(xmet), torch.from_numpy(stat_s[cs])).numpy() | |
| gd = m_met_model(torch.from_numpy(xmet_cut), torch.from_numpy(stat_s[cs])).numpy() | |
| d_met = ga - gd | |
| crop, forest, arid = static[cs, 0], static[cs, 1], static[cs, 4] | |
| grp = np.full(len(cs), "other", dtype=object) | |
| grp[(crop < 0.1) & (forest > 0.5)] = "forest" | |
| grp[(crop < 0.1) & (forest <= 0.5)] = "other_natural" | |
| grp[crop > 0.5] = "cropland" | |
| def boot(v, n=2000): | |
| v = v[np.isfinite(v)] | |
| if len(v) < 5: | |
| return [np.nan, np.nan] | |
| bs = [np.nanmean(rng.choice(v, len(v))) for _ in range(n)] | |
| return [float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5))] | |
| stats = {"test_nse": float(nse), "test_r": r, "n_samples": int(len(sel)), | |
| "overall": { | |
| "mean_abs_delta_met": float(np.mean(np.abs(d_met))), | |
| "mean_abs_delta_struct": float(np.mean(np.abs(d_struct))), | |
| "ratio": float(np.mean(np.abs(d_struct)) / np.mean(np.abs(d_met))), | |
| "corr": float(np.corrcoef(d_met, d_struct)[0, 1])}, | |
| "groups": {}} | |
| for g in ["cropland", "forest", "other_natural"]: | |
| m = grp == g | |
| if m.sum() < 20: | |
| continue | |
| ratio = np.sum(np.abs(d_struct[m])) / np.sum(np.abs(d_met[m])) | |
| stats["groups"][g] = { | |
| "n": int(m.sum()), | |
| "delta_met": float(np.mean(np.abs(d_met[m]))), | |
| "delta_struct": float(np.mean(np.abs(d_struct[m]))), | |
| "ratio": float(ratio), | |
| "delta_struct_ci": boot(np.abs(d_struct[m])), | |
| "corr": float(np.corrcoef(d_met[m], d_struct[m])[0, 1])} | |
| np.savez_compressed(OUT / "exp2b_deltas.npz", d_met=d_met.astype(np.float32), | |
| d_struct=d_struct.astype(np.float32), cell=cs, time=ts, | |
| group=grp.astype("U16"), aridity=arid.astype(np.float32)) | |
| json.dump(stats, open(OUT / "exp2b_stats.json", "w"), indent=2) | |
| print(json.dumps(stats, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |