File size: 7,725 Bytes
a5899e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce7a57d
 
a5899e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""Package v2-ca for HF (runs/v2_ca/hf_model) + what-if grid by region and country (runs/v2_ca/products/scenarios).

Golden test: 100 rows rebuilt with the training code; predict_ca.py must reproduce the training model exactly.
"""
from __future__ import annotations

import importlib.util
import json
import shutil
import sys
from pathlib import Path

import numpy as np
import pandas as pd
import xgboost as xgb

ROOT = Path("/root/trendex-ca")
RUN = ROOT / "runs" / "v2_ca"
HF = RUN / "hf_model"
MONTHS, PRECIP, TEMP = [5, 6, 7, 8, 9], [-30, -20, -10, 0, 10, 20, 30], [-2, -1, 0, 1, 2]


def load_module(path, name):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules[name] = mod
    spec.loader.exec_module(mod)
    return mod


def main():
    HF.mkdir(parents=True, exist_ok=True)
    for f in ["model_ca.ubj", "feature_schema.json", "climatology.parquet", "weather_climatology.parquet",
              "conformal.json", "metrics.json"]:
        shutil.copy(RUN / f, HF / f)
    shutil.copy(ROOT / "scripts" / "predict_ca.py", HF / "predict_ca.py")
    shutil.copy(ROOT / "configs" / "model_v2_ca.yaml", HF / "model_v2_ca.yaml")

    tr = load_module(ROOT / "scripts" / "30_train_ca.py", "train_ca")
    cells = pd.read_parquet(tr.CUBE / "cells.parquet")
    cells_e = cells[cells["mask_reason"].isna()].reset_index(drop=True)
    pm = load_module(HF / "predict_ca.py", "predict_ca")
    model = pm.load(HF)

    # golden: features for 100 random eligible cells in 2024 July via what_if inputs at zero deltas is too
    # synthetic, so rebuild real rows from the cube for 300 cells and keep 100 finite ones
    rng = np.random.default_rng(0)
    pick = np.sort(rng.choice(len(cells_e), size=300, replace=False))
    elig = cells["mask_reason"].isna().values
    sub_mask = np.zeros(len(cells), bool)
    sub_mask[np.nonzero(elig)[0][pick]] = True
    arr = tr.load_arrays(cells, sub_mask)
    tmp = RUN / "_golden_tmp"
    tmp.mkdir(exist_ok=True)
    f = tr.build_features(cells_e.iloc[pick].reset_index(drop=True), arr, tmp)
    clim = tr.clim_fold(f["ndvi"], tr.YEARS)
    X, y, meta = tr.matrix(f, cells_e.iloc[pick].reset_index(drop=True), np.arange(len(pick)), np.array([2024]), clim)
    ok = np.isfinite(y)
    gin = pd.DataFrame(X[ok][:100], columns=tr.FEATURES)
    (HF / "golden").mkdir(exist_ok=True)
    gin.to_parquet(HF / "golden" / "inputs.parquet", index=False)
    out = model.predict(gin)
    out.to_parquet(HF / "golden" / "expected.parquet", index=False)
    ref = xgb.XGBRegressor()
    ref.load_model(RUN / "model_ca.ubj")
    diff = float(np.max(np.abs(ref.predict(gin[tr.FEATURES].to_numpy("float32")) - out["pred_anom"].to_numpy())))
    print(f"golden max diff {diff:.2e}")
    assert diff < 1e-5
    shutil.rmtree(tmp)

    # what-if grid: up to 2,000 random eligible cells per region, aggregated to region and country
    shuffled = cells_e.sample(frac=1.0, random_state=0)
    samp = shuffled[shuffled.groupby("region", dropna=False).cumcount() < 2000]
    rows = []
    for mo in MONTHS:
        for p in PRECIP:
            for t in TEMP:
                r = model.what_if(cells, samp["cell_id"].to_numpy(), month=mo, precip_pct=p, temp_c=t)
                rows.append(pd.DataFrame({"region": samp["region"].to_numpy(), "country": samp["country"].to_numpy(),
                                          "month": mo, "p": p, "t": t, "typical": r["expected_typical_weather"].to_numpy(),
                                          "change": r["change_vs_typical"].to_numpy()}))
    W = pd.concat(rows, ignore_index=True)

    def nested(df):
        g = df.groupby(["month", "p", "t"])["change"].mean()
        typ = df[(df["p"] == 0) & (df["t"] == 0)].groupby("month")["typical"].mean()
        return {"n_cells_sampled": int(len(df) // (len(MONTHS) * len(PRECIP) * len(TEMP))),
                "typical": [round(float(typ[m]), 4) for m in MONTHS],
                "change": [[[round(float(g[(m, p, t)]), 4) for t in TEMP] for p in PRECIP] for m in MONTHS]}

    js = {"model": "TrendeX90/expected-greenness-ca@v2-ca", "units": "NDVI", "months": MONTHS, "precip_pct": PRECIP,
          "temp_c": TEMP, "layout": "change[month][precip][temp]; expected = typical[month] + change",
          "meaning": "Expected greenness change vs typical weather if precipitation and GLDAS air temperature differ by "
                     "the given amounts. Model sensitivity, not a causal effect; averages over up to 2,000 sampled "
                     "pasture cells per region.",
          "all": nested(W), "countries": {c: nested(g) for c, g in W.groupby("country")},
          "regions": {r: nested(g) for r, g in W.groupby("region")}}
    sc = RUN / "products" / "scenarios"
    sc.mkdir(parents=True, exist_ok=True)
    (sc / "what_if.json").write_text(json.dumps(js, separators=(",", ":")))
    print(f"what_if.json {(sc / 'what_if.json').stat().st_size / 1e3:.0f} kB; July all: typical {js['all']['typical'][2]}, "
          f"-30% {js['all']['change'][2][0][2]}, +2C {js['all']['change'][2][3][4]}")

    m = json.loads((RUN / "metrics.json").read_text())
    t, s = m["temporal_test"], m["spatial_test"]
    fmt = lambda d: f"{d['point']:.3f} (95% CI {d['ci_lo']:.3f} to {d['ci_hi']:.3f}, {d['units']} units)"  # noqa: E731
    (HF / "README.md").write_text(f"""---
license: other
library_name: xgboost
tags: [nasa, modis, ndvi, imerg, gldas, pastures, central-asia, tabular-regression]
datasets: [TrendeX90/ca-cube]
---
# TrendeX expected greenness, Central Asia (v2-ca)

Summer (May-Sep) NDVI anomaly of 1 km pasture cells in Kazakhstan, Kyrgyzstan, Tajikistan, Turkmenistan and
Uzbekistan, predicted from weather (IMERG precipitation; GLDAS air temperature, soil moisture, snow) and terrain
only. The gap to observed NDVI is change **not explained by weather**: not a cause, not forage quality.
Protocol locked in git before fitting (`model_v2_ca.yaml`, commit {m['git_commit']}). Naryn pilot model: TrendeX90/expected-greenness (v1).

| Test | RMSE xgb | RMSE ridge | RMSE climatology | anomaly corr xgb |
|---|---|---|---|---|
| Temporal (2020-2025) | {t['xgb']['rmse']:.4f} | {t['ridge']['rmse']:.4f} | {t['clim']['rmse']:.4f} | {t['xgb']['anomaly_corr']:.3f} |
| Spatial (unseen super-blocks) | {s['xgb']['rmse']:.4f} | {s['ridge']['rmse']:.4f} | {s['clim']['rmse']:.4f} | {s['xgb']['anomaly_corr']:.3f} |

- Skill vs ridge: temporal {fmt(t['skill_xgb_vs_ridge'])}; spatial {fmt(s['skill_xgb_vs_ridge'])}.
- Skill vs climatology: temporal {fmt(t['skill_xgb_vs_clim'])}.
- Seeds ({len(t['seed_skill_vs_ridge']['values'])}): {t['seed_skill_vs_ridge']['mean']:.3f} +/- {t['seed_skill_vs_ridge']['sd']:.3f}.
- **Gate (pre-registered, CI lower bound > 0 on both tests): passed = {m['gate']['passed']}; shipped = {m['gate']['shipped_model']}.**
- P10-P90 coverage on 2020-2025: {t['conformal_coverage_p10_p90']:.0%} (nominal 80%).

Limits: trained on {m['data']['sample_cells']:,} sampled cells (of {m['data']['eligible_cells']:,} eligible) because of budget; GLDAS
(0.25 deg) is coarse; MCD12Q1 2020 mask; NDVI is greenness, not forage; no field validation; budget-limited tuning
(20 trials) and 3 seeds. Spatial test shares years with training and is easier than the temporal test.

```python
from predict_ca import load      # numpy, pandas, xgboost; CPU
m = load(".")
m.predict(features_df)           # columns as in feature_schema.json
```
Data: MOD13A3.061, MCD12Q1.061, NASADEM_HGT.001 (LP DAAC), GPM_3IMERGM.07, GLDAS_NOAH025_M.2.1 (GES DISC).
AI use: implementation assisted by Claude (Anthropic).
""")
    print("PACKAGE_CA_DONE", sorted(p.name for p in HF.iterdir()))


if __name__ == "__main__":
    main()