Download _backup/scripts/42_extend_mask.py from TrendeX90/ca-cube: direct link, hf CLI and curl.
- Browser
- Download file 3.42 kB
-
https://huggingface.co/datasets/TrendeX90/ca-cube/resolve/main/_backup/scripts/42_extend_mask.py
- Command line
-
hf download hf://datasets/TrendeX90/ca-cube/_backup/scripts/42_extend_mask.py
-
curl -L -o 42_extend_mask.py https://huggingface.co/datasets/TrendeX90/ca-cube/resolve/main/_backup/scripts/42_extend_mask.py
3.42 kB
| """Extend v2-ca outputs to cells the corrected formula mask re-includes (mountain barren -> pasture). | |
| The extra set = status == "pasture" in the backend's NEW artifacts_ca/cells.parquet, minus cells already covered. | |
| They were never in the model's training sample, so the shipped production model gives spatially out-of-sample | |
| predictions for them (not year-block cross-fitted). Marked source="production_model_unseen_cell" in products. | |
| Appends to runs/v2_ca/summer_residual.npy and eligible_cells.parquet; then re-run 40_products_ca.py. | |
| """ | |
| from __future__ import annotations | |
| import importlib.util | |
| import sys | |
| import time | |
| 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" | |
| FORMULA_CELLS = Path("/root/trendex/backend/artifacts_ca/cells.parquet") | |
| def log(m): | |
| print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True) | |
| 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(): | |
| tr = load_module(ROOT / "scripts" / "30_train_ca.py", "train_ca") | |
| fc = pd.read_parquet(FORMULA_CELLS) | |
| log(f"formula cells columns: {list(fc.columns)[:20]}") | |
| pasture = set(fc.loc[fc["status"] == "pasture", "cell_id"].astype("int64")) | |
| elig = pd.read_parquet(RUN / "eligible_cells.parquet") | |
| if "source" not in elig.columns: | |
| elig["source"] = "oof" | |
| have = set(elig["cell_id"].astype("int64")) | |
| cells_all = pd.read_parquet(tr.CUBE / "cells.parquet") | |
| extra_mask = cells_all["cell_id"].isin(pasture - have).values | |
| cells_x = cells_all[extra_mask].reset_index(drop=True) | |
| log(f"formula pasture {len(pasture)}, already covered {len(have & pasture)}, extra {len(cells_x)}; " | |
| f"by country {cells_x['country'].value_counts().to_dict()}; by old mask_reason {cells_x['mask_reason'].value_counts(dropna=False).to_dict()}") | |
| if len(cells_x) == 0: | |
| log("EXTEND_DONE (nothing to add)") | |
| return | |
| arr = tr.load_arrays(cells_all, extra_mask) | |
| tmp = RUN / "_extend_tmp" | |
| tmp.mkdir(exist_ok=True) | |
| f = tr.build_features(cells_x, arr, tmp) | |
| del arr | |
| clim_loyo = tr.clim_fold(f["ndvi"], tr.YEARS) # what the production model saw as clim_ndvi | |
| clim_all = np.nanmean(f["ndvi"], axis=1, keepdims=True) | |
| booster = xgb.Booster() | |
| booster.load_model(str(RUN / "model_ca.ubj")) | |
| rows = np.arange(len(cells_x)) | |
| X, _, _ = tr.matrix(f, cells_x, rows, tr.YEARS, clim_loyo) | |
| pred = booster.predict(xgb.DMatrix(X, feature_names=tr.FEATURES)).reshape(len(rows), len(tr.YEARS), len(tr.MONTHS)) | |
| res = f["ndvi"] - (clim_all + pred) | |
| summer_idx = [list(tr.MONTHS).index(m) for m in (6, 7, 8)] | |
| with np.errstate(all="ignore"): | |
| sres = np.nanmean(res[:, :, summer_idx], axis=2).astype("float32") | |
| W = np.load(RUN / "summer_residual.npy") | |
| np.save(RUN / "summer_residual.npy", np.vstack([W, sres])) | |
| add = cells_x[["cell_id", "block_id", "region", "country"]].assign(source="production_model_unseen_cell") | |
| pd.concat([elig, add], ignore_index=True).to_parquet(RUN / "eligible_cells.parquet", index=False) | |
| import shutil | |
| shutil.rmtree(tmp) | |
| log(f"EXTEND_DONE added {len(add)} cells (total {len(elig) + len(add)})") | |
| if __name__ == "__main__": | |
| main() | |