File size: 17,304 Bytes
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""Train/evaluate expected greenness v2-ca exactly as locked in configs/model_v2_ca.yaml.

    python ca/30_train_ca.py --git-commit <hash>

Training/evaluation on a 150k-cell sample; out-of-fold predictions for every eligible cell.
Writes runs/v2_ca/: metrics.json, model_ca.ubj, feature_schema.json, conformal.json, climatology / weather
climatology parquet, summer_residual.npy (cells x years, residual vs all-years climatology), expected_block.parquet.
"""
from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

import numpy as np
import pandas as pd
import pyarrow.parquet as pq
import xgboost as xgb
from sklearn.linear_model import Ridge
from sklearn.model_selection import GroupKFold

CUBE = Path("/root/trendex-ca/data/cube")
RUN = Path("/root/trendex-ca/runs/v2_ca")
YEARS = np.arange(2001, 2026)
MONTHS = np.arange(5, 10)
CUBE_MONTHS = list(range(4, 11))
STATIC = ["elev_mean", "elev_std", "slope_mean", "steep_share", "aspect_sin", "aspect_cos", "tpi",
          "grass_frac", "barren_frac", "crop_frac", "lc_type1", "lat"]
WEATHER = ["precip_m", "precip_2m", "precip_winter", "tair_m", "tair_prev", "soil_m", "swe_apr"]
FEATURES = STATIC + ["month", "clim_ndvi"] + WEATHER
FIXED = {"tree_method": "hist", "device": "cuda", "objective": "reg:squarederror"}
SEEDS = [0, 1, 2]
N_SAMPLE = 150_000


def log(m):
    print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)


def load_arrays(cells_all: pd.DataFrame, elig: np.ndarray) -> dict:
    """(n_elig, 25 years, 7 months Apr-Oct) arrays straight from the yearly files (rows = month blocks x all cells)."""
    n_all, idx = len(cells_all), np.nonzero(elig)[0]
    shape = (len(idx), len(YEARS), len(CUBE_MONTHS))
    arr = {k: np.full(shape, np.nan, "float32") for k in ["ndvi", "precip", "precip_winter", "tair", "soil_moist", "swe"]}
    for j, yr in enumerate(YEARS):
        t = pq.read_table(CUBE / "monthly" / f"year={yr}" / "part.parquet",
                          columns=["month", "ndvi", "ndvi_ok", "precip", "precip_winter", "tair", "soil_moist", "swe"])
        months = t.column("month").to_numpy()
        assert len(months) % n_all == 0, "monthly file is not month-blocks x all cells"
        ok = t.column("ndvi_ok").to_numpy(zero_copy_only=False)
        cols = {k: t.column(k).to_numpy(zero_copy_only=False).astype("float32") for k in arr}
        cols["ndvi"] = np.where(ok, cols["ndvi"], np.nan)
        for b in range(len(months) // n_all):
            mo = int(months[b * n_all])
            mi = CUBE_MONTHS.index(mo)
            for k in arr:
                arr[k][:, j, mi] = cols[k][b * n_all:(b + 1) * n_all][idx]
        log(f"loaded {yr}")
    return arr


def build_features(cells: pd.DataFrame, arr: dict, run: Path) -> dict:
    mi = [CUBE_MONTHS.index(m) for m in MONTHS]
    prev = [CUBE_MONTHS.index(m - 1) for m in MONTHS]
    take = lambda a, ix: a[:, :, ix]                                   # noqa: E731
    anom = lambda x: x - np.nanmean(x, axis=1, keepdims=True)          # noqa: E731
    with np.errstate(all="ignore"):
        raw_m = {"precip_m": take(arr["precip"], mi), "precip_2m": take(arr["precip"], mi) + take(arr["precip"], prev),
                 "tair_m": take(arr["tair"], mi), "tair_prev": take(arr["tair"], prev), "soil_m": take(arr["soil_moist"], mi)}
        raw_y = {"precip_winter": arr["precip_winter"][:, :, CUBE_MONTHS.index(5)],
                 "swe_apr": arr["swe"][:, :, CUBE_MONTHS.index(4)]}
        f = {k: anom(v) for k, v in raw_m.items()}
        f |= {k: np.repeat(anom(v)[:, :, None], len(MONTHS), axis=2) for k, v in raw_y.items()}
        wc = pd.concat([pd.DataFrame({"cell_id": cells["cell_id"].values, "month": int(mo)} |
                                     {f"{k}_mean": np.nanmean(v[:, :, j], axis=1).astype("float32") for k, v in raw_m.items()} |
                                     {f"{k}_mean": np.nanmean(v, axis=1).astype("float32") for k, v in raw_y.items()})
                        for j, mo in enumerate(MONTHS)], ignore_index=True)
    wc.to_parquet(run / "weather_climatology.parquet", index=False)
    f["ndvi"] = take(arr["ndvi"], mi)
    return f


def clim_fold(ndvi, train_years):
    tm = np.isin(YEARS, train_years)[None, :, None]
    fin = np.isfinite(ndvi)
    s = np.nansum(np.where(tm, ndvi, np.nan), axis=1, keepdims=True)
    n = np.sum(fin & tm, axis=1, keepdims=True).astype("float32")
    own = np.where(fin & tm, ndvi, 0.0)
    with np.errstate(all="ignore"):
        return ((s - own) / (n - (fin & tm))).astype("float32")


def matrix(f: dict, cells: pd.DataFrame, rows: np.ndarray, years: np.ndarray, clim: np.ndarray):
    """Feature matrix for cell positions `rows`, the given years and May-Sep. Returns X, y, meta."""
    yi = np.nonzero(np.isin(YEARS, years))[0]
    sub = lambda a: a[rows][:, yi].reshape(-1)                         # noqa: E731
    nm = len(MONTHS)
    shape = (len(rows), len(yi), nm)
    cols = {}
    for k in STATIC:
        cols[k] = np.broadcast_to(cells[k].values.astype("float32")[rows][:, None, None], shape).reshape(-1)
    cols["month"] = np.broadcast_to(MONTHS.astype("float32")[None, None, :], shape).reshape(-1)
    cols["clim_ndvi"] = sub(clim)
    for k in WEATHER:
        cols[k] = sub(f[k])
    X = np.column_stack([cols[k] for k in FEATURES]).astype("float32")
    ndvi = sub(f["ndvi"])
    y = ndvi - cols["clim_ndvi"]
    meta = {"row": np.broadcast_to(rows[:, None, None], shape).reshape(-1),
            "year": np.broadcast_to(YEARS[yi][None, :, None], shape).reshape(-1),
            "month": cols["month"].astype("int8"), "ndvi": ndvi}
    return X, y.astype("float32"), meta


class RidgeModel:
    def __init__(self, alpha):
        self.alpha = alpha

    def fit(self, X, y):
        self.med = np.nanmedian(X, axis=0)
        Z = np.where(np.isnan(X), self.med, X)
        self.mu, self.sd = Z.mean(0), Z.std(0)
        self.sd[self.sd == 0] = 1
        self.r = Ridge(alpha=self.alpha).fit((Z - self.mu) / self.sd, y)
        return self

    def predict(self, X):
        Z = np.where(np.isnan(X), self.med, X)
        return self.r.predict((Z - self.mu) / self.sd)


def fit_xgb(X, y, params, n_est, seed, Xv=None, yv=None):
    m = xgb.XGBRegressor(**FIXED, **params, n_estimators=n_est, random_state=seed,
                         early_stopping_rounds=50 if Xv is not None else None)
    m.fit(X, y, eval_set=[(Xv, yv)] if Xv is not None else None, verbose=False)
    return m


def boot(sse_a, sse_b, rng, n=2000):
    idx = rng.integers(0, len(sse_a), size=(n, len(sse_a)))
    dist = 1 - sse_a[idx].sum(1) / sse_b[idx].sum(1)
    return {"point": float(1 - sse_a.sum() / sse_b.sum()), "ci_lo": float(np.quantile(dist, 0.025)),
            "ci_hi": float(np.quantile(dist, 0.975)), "units": int(len(sse_a))}


def score(y, preds, units, cuts, rng):
    out = {"n_rows": int(len(y))}
    sse = {}
    for k, p in preds.items():
        e = y - p
        t, q = np.digitize(y, cuts), np.digitize(p, cuts)
        out[k] = {"rmse": float(np.sqrt(np.mean(e ** 2))), "mae": float(np.mean(np.abs(e))),
                  "anomaly_corr": float(np.corrcoef(y, p)[0, 1]) if np.std(p) > 0 else None,
                  "tercile_bacc": float(np.mean([np.mean(q[t == c] == c) for c in range(3) if np.any(t == c)]))}
        sse[k] = pd.Series(e ** 2).groupby(units).sum().values
    out["skill_xgb_vs_ridge"] = boot(sse["xgb"], sse["ridge"], rng)
    out["skill_xgb_vs_clim"] = boot(sse["xgb"], sse["clim"], rng)
    out["skill_ridge_vs_clim"] = boot(sse["ridge"], sse["clim"], rng)
    return out


def finite(X, y, *extra):
    ok = np.isfinite(y)
    return (X[ok], y[ok]) + tuple(e[ok] for e in extra)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--git-commit", required=True)
    a = ap.parse_args()
    RUN.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(0)
    metrics = {"protocol": "configs/model_v2_ca.yaml", "git_commit": a.git_commit, "features": FEATURES}

    cells_all = pd.read_parquet(CUBE / "cells.parquet")
    elig = cells_all["mask_reason"].isna().values
    cells = cells_all[elig].reset_index(drop=True)
    arr = load_arrays(cells_all, elig)
    f = build_features(cells, arr, RUN)
    del arr
    n = len(cells)
    sample = np.sort(np.random.default_rng(0).choice(n, size=min(N_SAMPLE, n), replace=False))
    sb = ((cells["block_row"].values // 3).astype(np.int64) * 100000 + cells["block_col"].values // 3)
    metrics["data"] = {"eligible_cells": int(n), "sample_cells": int(len(sample)),
                       "by_country_eligible": cells["country"].value_counts().astype(int).to_dict()}
    log(f"eligible cells {n}, sample {len(sample)}")

    # --- tuning on the inner split (sample only)
    c_in = clim_fold(f["ndvi"], np.arange(2001, 2016))
    Xi, yi_ = finite(*matrix(f, cells, sample, np.arange(2001, 2016), c_in)[:2])
    Xv, yv, mv = matrix(f, cells, sample, np.arange(2016, 2020), c_in)
    Xv, yv, mv_month = finite(Xv, yv, mv["month"])
    ridge_rmse = {al: float(np.sqrt(np.mean((yv - RidgeModel(al).fit(Xi, yi_).predict(Xv)) ** 2)))
                  for al in [1, 10, 100, 1000, 10000]}
    alpha = min(ridge_rmse, key=ridge_rmse.get)
    import optuna
    optuna.logging.set_verbosity(optuna.logging.WARNING)

    def objective(tr):
        p = {"max_depth": tr.suggest_int("max_depth", 4, 10),
             "learning_rate": tr.suggest_float("learning_rate", 0.03, 0.2, log=True),
             "min_child_weight": tr.suggest_float("min_child_weight", 1, 200, log=True),
             "subsample": tr.suggest_float("subsample", 0.5, 1.0),
             "colsample_bytree": tr.suggest_float("colsample_bytree", 0.5, 1.0),
             "reg_lambda": tr.suggest_float("reg_lambda", 1e-3, 30, log=True)}
        m = fit_xgb(Xi, yi_, p, 2000, 0, Xv, yv)
        tr.set_user_attr("n_est", int(m.best_iteration) + 1)
        return float(np.sqrt(np.mean((yv - m.predict(Xv)) ** 2)))

    st = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=0))
    st.optimize(objective, n_trials=20, timeout=600)
    best, n_est = st.best_params, st.best_trial.user_attrs["n_est"]
    metrics["tuning"] = {"trials": len(st.trials), "best_params": best, "n_estimators": n_est,
                         "inner_rmse_xgb": st.best_value, "ridge_alpha": alpha, "inner_rmse_ridge": ridge_rmse}
    log(f"tuning {len(st.trials)} trials, xgb {st.best_value:.4f} vs ridge {ridge_rmse[alpha]:.4f}, n_est {n_est}")
    cuts = np.quantile(yi_, [1 / 3, 2 / 3])
    res_in = yv - fit_xgb(Xi, yi_, best, n_est, 0).predict(Xv)
    conf = {int(mo): [float(np.quantile(res_in[mv_month == mo], q)) for q in (0.1, 0.9)] for mo in MONTHS}
    del Xi, yi_, Xv, yv

    # --- temporal test
    c_t = clim_fold(f["ndvi"], np.arange(2001, 2020))
    Xtr, ytr = finite(*matrix(f, cells, sample, np.arange(2001, 2020), c_t)[:2])
    Xte, yte, mte = matrix(f, cells, sample, np.arange(2020, 2026), c_t)
    Xte, yte, te_year, te_month = finite(Xte, yte, mte["year"], mte["month"])
    ridge = RidgeModel(alpha).fit(Xtr, ytr)
    p_r = ridge.predict(Xte)
    ps, seed_skill = [], []
    for s in SEEDS:
        p = fit_xgb(Xtr, ytr, best, n_est, s).predict(Xte)
        ps.append(p)
        seed_skill.append(float(1 - np.mean((yte - p) ** 2) / np.mean((yte - p_r) ** 2)))
    p_x = np.mean(ps, axis=0)
    temporal = score(yte, {"xgb": p_x, "ridge": p_r, "clim": np.zeros_like(yte)}, te_year, cuts, rng)
    temporal["seed_skill_vs_ridge"] = {"values": seed_skill, "mean": float(np.mean(seed_skill)), "sd": float(np.std(seed_skill))}
    lo = np.array([conf[int(m)][0] for m in te_month]); hi = np.array([conf[int(m)][1] for m in te_month])
    temporal["conformal_coverage_p10_p90"] = float(np.mean(((yte - p_x) >= lo) & ((yte - p_x) <= hi)))
    metrics["temporal_test"] = temporal
    log(f"temporal skill vs ridge {temporal['skill_xgb_vs_ridge']}")
    del Xtr, ytr, Xte, yte

    # --- spatial test (sample, all years, superblock groups)
    c_all = clim_fold(f["ndvi"], YEARS)
    Xa, ya, ma = matrix(f, cells, sample, YEARS, c_all)
    Xa, ya, rows_a = finite(Xa, ya, ma["row"])
    groups = sb[rows_a]
    preds = {"xgb": np.zeros_like(ya), "ridge": np.zeros_like(ya)}
    for itr, ite in GroupKFold(5).split(Xa, groups=groups):
        preds["xgb"][ite] = fit_xgb(Xa[itr], ya[itr], best, n_est, 0).predict(Xa[ite])
        preds["ridge"][ite] = RidgeModel(alpha).fit(Xa[itr], ya[itr]).predict(Xa[ite])
    preds["clim"] = np.zeros_like(ya)
    spatial = score(ya, preds, groups, cuts, rng)
    metrics["spatial_test"] = spatial
    log(f"spatial skill vs ridge {spatial['skill_xgb_vs_ridge']}")

    passed = temporal["skill_xgb_vs_ridge"]["ci_lo"] > 0 and spatial["skill_xgb_vs_ridge"]["ci_lo"] > 0
    chosen = "xgb" if passed else "ridge"
    metrics["gate"] = {"rule": "CI lower bound of skill_xgb_vs_ridge > 0 on temporal AND spatial tests",
                       "passed": bool(passed), "shipped_model": chosen}
    log(f"GATE passed={passed} -> {chosen}")

    # --- production model (sample, all years) + importance
    prod = fit_xgb(Xa, ya, best, n_est, 0) if chosen == "xgb" else RidgeModel(alpha).fit(Xa, ya)
    if chosen == "xgb":
        booster = prod.get_booster()
        booster.feature_names = FEATURES
        booster.save_model(RUN / "model_ca.ubj")
        sel = np.random.default_rng(1).choice(len(Xa), size=min(200_000, len(Xa)), replace=False)
        contrib = booster.predict(xgb.DMatrix(Xa[sel], feature_names=FEATURES), pred_contribs=True)
        metrics["feature_importance_mean_abs"] = dict(sorted(zip(FEATURES, np.abs(contrib[:, :-1]).mean(0).round(6).tolist()),
                                                             key=lambda kv: -kv[1]))
    del Xa, ya

    # --- out-of-fold for ALL eligible cells (5 year blocks), residual vs all-years climatology
    clim_all = np.nanmean(f["ndvi"], axis=1, keepdims=True)  # (n, 1, 5)
    summer_res = np.full((n, len(YEARS)), np.nan, "float32")
    bcode, buniq = pd.factorize(cells["block_id"])
    nb = len(buniq)
    acc = {k: np.zeros((nb, len(YEARS), len(MONTHS))) for k in ("observed", "expected", "residual", "n")}
    all_rows = np.arange(n)
    summer_idx = [list(MONTHS).index(m) for m in (6, 7, 8)]
    for blk in [np.arange(s, s + 5) for s in (2001, 2006, 2011, 2016, 2021)]:
        trn = np.setdiff1d(YEARS, blk)
        cf = clim_fold(f["ndvi"], trn)
        Xs, ys = finite(*matrix(f, cells, sample, trn, cf)[:2])
        model = fit_xgb(Xs, ys, best, n_est, 0) if chosen == "xgb" else RidgeModel(alpha).fit(Xs, ys)
        del Xs, ys
        for chunk in np.array_split(all_rows, 10):
            X, _, meta = matrix(f, cells, chunk, blk, cf)
            pa_ = model.predict(X).astype("float32").reshape(len(chunk), len(blk), len(MONTHS))
            yi = np.nonzero(np.isin(YEARS, blk))[0]
            expected = clim_all[chunk] + pa_
            obs = f["ndvi"][chunk][:, yi]
            res = obs - expected
            with np.errstate(all="ignore"):
                summer_res[chunk[:, None], yi[None, :]] = np.nanmean(res[:, :, summer_idx], axis=2)
            bc = bcode[chunk]
            for j, yy in enumerate(yi):
                for k in range(len(MONTHS)):
                    v = np.isfinite(res[:, j, k])
                    acc["n"][:, yy, k] += np.bincount(bc[v], minlength=nb)
                    for name, val in (("observed", obs), ("expected", expected), ("residual", res)):
                        acc[name][:, yy, k] += np.bincount(bc[v], weights=val[v, j, k], minlength=nb)
        log(f"oof block {blk[0]}-{blk[-1]} done")
    np.save(RUN / "summer_residual.npy", summer_res)
    cells[["cell_id", "block_id", "region", "country"]].to_parquet(RUN / "eligible_cells.parquet", index=False)
    B, Y, M = np.meshgrid(np.arange(nb), YEARS, MONTHS, indexing="ij")
    with np.errstate(all="ignore"):
        eb = pd.DataFrame({"block_id": np.asarray(buniq)[B.ravel()], "year": Y.ravel(), "month": M.ravel(),
                           "observed": (acc["observed"] / acc["n"]).ravel(), "expected": (acc["expected"] / acc["n"]).ravel(),
                           "residual": (acc["residual"] / acc["n"]).ravel(), "n_cells": acc["n"].ravel().astype(int)})
    eb = eb[eb["n_cells"] > 0].reset_index(drop=True)
    eb["p10"] = eb["expected"] + eb["month"].map(lambda m: conf[int(m)][0])
    eb["p90"] = eb["expected"] + eb["month"].map(lambda m: conf[int(m)][1])
    eb.to_parquet(RUN / "expected_block.parquet", index=False)

    pd.concat([pd.DataFrame({"cell_id": cells["cell_id"].values, "month": int(mo),
                             "clim_ndvi": clim_all[:, 0, j]}) for j, mo in enumerate(MONTHS)]) \
        .to_parquet(RUN / "climatology.parquet", index=False)
    (RUN / "feature_schema.json").write_text(json.dumps({"features": FEATURES, "static": STATIC, "weather": WEATHER,
                                                         "months": MONTHS.tolist(), "shipped_model": chosen,
                                                         "target": "ndvi_anomaly = ndvi - clim_ndvi"}, indent=2))
    (RUN / "conformal.json").write_text(json.dumps(conf, indent=2))
    (RUN / "metrics.json").write_text(json.dumps(metrics, indent=2, default=float))
    log("TRAIN_CA_DONE")


if __name__ == "__main__":
    main()