backup _backup/scripts 18:24:56
Browse files
_backup/scripts/40_products_ca.py
CHANGED
|
@@ -57,6 +57,7 @@ def main():
|
|
| 57 |
log(f"cells {len(cells)}")
|
| 58 |
|
| 59 |
rt = trend_table(W, cells["cell_id"].values, "cell_id")
|
|
|
|
| 60 |
rt.to_parquet(OUT / "residual_trend.parquet", index=False)
|
| 61 |
shares = rt["class"].value_counts(normalize=True).round(4).to_dict()
|
| 62 |
log(f"cell classes {shares}")
|
|
@@ -94,6 +95,7 @@ def main():
|
|
| 94 |
shutil.copy(RUN / "metrics.json", OUT / "metrics.json")
|
| 95 |
|
| 96 |
summary = {"model": "TrendeX90/expected-greenness-ca@v2-ca", "eligible_cells": int(len(cells)),
|
|
|
|
| 97 |
"residual_trend_cell_class_shares": shares, "residual_trend_cell_class_shares_by_country": by_country,
|
| 98 |
"residual_trend_country": agg["country"][["country", "slope_per_decade", "ci_lo", "ci_hi", "p", "q", "class"]]
|
| 99 |
.round(6).to_dict(orient="records"),
|
|
|
|
| 57 |
log(f"cells {len(cells)}")
|
| 58 |
|
| 59 |
rt = trend_table(W, cells["cell_id"].values, "cell_id")
|
| 60 |
+
rt["source"] = cells["source"].values if "source" in cells.columns else "oof"
|
| 61 |
rt.to_parquet(OUT / "residual_trend.parquet", index=False)
|
| 62 |
shares = rt["class"].value_counts(normalize=True).round(4).to_dict()
|
| 63 |
log(f"cell classes {shares}")
|
|
|
|
| 95 |
shutil.copy(RUN / "metrics.json", OUT / "metrics.json")
|
| 96 |
|
| 97 |
summary = {"model": "TrendeX90/expected-greenness-ca@v2-ca", "eligible_cells": int(len(cells)),
|
| 98 |
+
"cells_by_source": rt["source"].value_counts().astype(int).to_dict(),
|
| 99 |
"residual_trend_cell_class_shares": shares, "residual_trend_cell_class_shares_by_country": by_country,
|
| 100 |
"residual_trend_country": agg["country"][["country", "slope_per_decade", "ci_lo", "ci_hi", "p", "q", "class"]]
|
| 101 |
.round(6).to_dict(orient="records"),
|
_backup/scripts/42_extend_mask.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extend v2-ca outputs to cells the corrected formula mask re-includes (mountain barren -> pasture).
|
| 2 |
+
|
| 3 |
+
The extra set = status == "pasture" in the backend's NEW artifacts_ca/cells.parquet, minus cells already covered.
|
| 4 |
+
They were never in the model's training sample, so the shipped production model gives spatially out-of-sample
|
| 5 |
+
predictions for them (not year-block cross-fitted). Marked source="production_model_unseen_cell" in products.
|
| 6 |
+
Appends to runs/v2_ca/summer_residual.npy and eligible_cells.parquet; then re-run 40_products_ca.py.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import importlib.util
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import pandas as pd
|
| 17 |
+
import xgboost as xgb
|
| 18 |
+
|
| 19 |
+
ROOT = Path("/root/trendex-ca")
|
| 20 |
+
RUN = ROOT / "runs" / "v2_ca"
|
| 21 |
+
FORMULA_CELLS = Path("/root/trendex/backend/artifacts_ca/cells.parquet")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def log(m):
|
| 25 |
+
print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_module(path, name):
|
| 29 |
+
spec = importlib.util.spec_from_file_location(name, path)
|
| 30 |
+
mod = importlib.util.module_from_spec(spec)
|
| 31 |
+
sys.modules[name] = mod
|
| 32 |
+
spec.loader.exec_module(mod)
|
| 33 |
+
return mod
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
tr = load_module(ROOT / "scripts" / "30_train_ca.py", "train_ca")
|
| 38 |
+
fc = pd.read_parquet(FORMULA_CELLS)
|
| 39 |
+
log(f"formula cells columns: {list(fc.columns)[:20]}")
|
| 40 |
+
pasture = set(fc.loc[fc["status"] == "pasture", "cell_id"].astype("int64"))
|
| 41 |
+
elig = pd.read_parquet(RUN / "eligible_cells.parquet")
|
| 42 |
+
if "source" not in elig.columns:
|
| 43 |
+
elig["source"] = "oof"
|
| 44 |
+
have = set(elig["cell_id"].astype("int64"))
|
| 45 |
+
cells_all = pd.read_parquet(tr.CUBE / "cells.parquet")
|
| 46 |
+
extra_mask = cells_all["cell_id"].isin(pasture - have).values
|
| 47 |
+
cells_x = cells_all[extra_mask].reset_index(drop=True)
|
| 48 |
+
log(f"formula pasture {len(pasture)}, already covered {len(have & pasture)}, extra {len(cells_x)}; "
|
| 49 |
+
f"by country {cells_x['country'].value_counts().to_dict()}; by old mask_reason {cells_x['mask_reason'].value_counts(dropna=False).to_dict()}")
|
| 50 |
+
if len(cells_x) == 0:
|
| 51 |
+
log("EXTEND_DONE (nothing to add)")
|
| 52 |
+
return
|
| 53 |
+
|
| 54 |
+
arr = tr.load_arrays(cells_all, extra_mask)
|
| 55 |
+
tmp = RUN / "_extend_tmp"
|
| 56 |
+
tmp.mkdir(exist_ok=True)
|
| 57 |
+
f = tr.build_features(cells_x, arr, tmp)
|
| 58 |
+
del arr
|
| 59 |
+
clim_loyo = tr.clim_fold(f["ndvi"], tr.YEARS) # what the production model saw as clim_ndvi
|
| 60 |
+
clim_all = np.nanmean(f["ndvi"], axis=1, keepdims=True)
|
| 61 |
+
booster = xgb.Booster()
|
| 62 |
+
booster.load_model(str(RUN / "model_ca.ubj"))
|
| 63 |
+
rows = np.arange(len(cells_x))
|
| 64 |
+
X, _, _ = tr.matrix(f, cells_x, rows, tr.YEARS, clim_loyo)
|
| 65 |
+
pred = booster.predict(xgb.DMatrix(X, feature_names=tr.FEATURES)).reshape(len(rows), len(tr.YEARS), len(tr.MONTHS))
|
| 66 |
+
res = f["ndvi"] - (clim_all + pred)
|
| 67 |
+
summer_idx = [list(tr.MONTHS).index(m) for m in (6, 7, 8)]
|
| 68 |
+
with np.errstate(all="ignore"):
|
| 69 |
+
sres = np.nanmean(res[:, :, summer_idx], axis=2).astype("float32")
|
| 70 |
+
|
| 71 |
+
W = np.load(RUN / "summer_residual.npy")
|
| 72 |
+
np.save(RUN / "summer_residual.npy", np.vstack([W, sres]))
|
| 73 |
+
add = cells_x[["cell_id", "block_id", "region", "country"]].assign(source="production_model_unseen_cell")
|
| 74 |
+
pd.concat([elig, add], ignore_index=True).to_parquet(RUN / "eligible_cells.parquet", index=False)
|
| 75 |
+
import shutil
|
| 76 |
+
shutil.rmtree(tmp)
|
| 77 |
+
log(f"EXTEND_DONE added {len(add)} cells (total {len(elig) + len(add)})")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
main()
|
_backup/scripts/after_formula2.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# After the formula re-run has written the new cells.parquet and the first model push chain is done:
|
| 3 |
+
# extend model outputs to re-included cells, rebuild products, push products.
|
| 4 |
+
set -uo pipefail
|
| 5 |
+
cd /root/trendex-ca
|
| 6 |
+
until grep -qE "FORMULA2_EXPORT_START|Traceback" logs/formula2.log; do sleep 20; done
|
| 7 |
+
grep -q Traceback logs/formula2.log && { echo "FORMULA2 FAILED, not extending"; exit 1; }
|
| 8 |
+
until grep -qE "CHAIN_DONE|CHAIN_FAILED" logs/chain2.log; do sleep 20; done
|
| 9 |
+
echo "EXTEND_START $(date -u +%T)"
|
| 10 |
+
python -u scripts/42_extend_mask.py > logs/extend.log 2>&1 || { echo "EXTEND FAILED"; exit 1; }
|
| 11 |
+
python -u scripts/40_products_ca.py > logs/products_ca2.log 2>&1 || { echo "PRODUCTS2 FAILED"; exit 1; }
|
| 12 |
+
python -u scripts/50_push_ca.py products > logs/push_products_ca2.log 2>&1 || { echo "PUSH PRODUCTS2 FAILED"; exit 1; }
|
| 13 |
+
echo "EXTEND_CHAIN_DONE $(date -u +%T)"
|
_backup/scripts/run_formula2.sh
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Formula re-run with the corrected barren rule (backend main, core_ca.yaml) on the FULL cube (with weather),
|
| 3 |
+
# then upload in the order the site needs: fe/ -> layers/ -> cells.parquet + S.npy -> the rest.
|
| 4 |
+
set -euo pipefail
|
| 5 |
+
cd /root/trendex && git pull -q && git log --oneline -1
|
| 6 |
+
cd backend
|
| 7 |
+
export TRENDEX_CONFIG=core_ca.yaml
|
| 8 |
+
echo "FORMULA2_BUILD_START $(date -u +%T)"
|
| 9 |
+
.venv/bin/python -m pipeline.build --cube /root/trendex-ca/data/cube --out artifacts_ca --clean --jobs 20
|
| 10 |
+
echo "FORMULA2_EXPORT_START $(date -u +%T)"
|
| 11 |
+
TRENDEX_ARTIFACTS=artifacts_ca TRENDEX_EXPORT=export_ca/v1 .venv/bin/python scripts/30_export_static.py
|
| 12 |
+
TRENDEX_ARTIFACTS=artifacts_ca .venv/bin/python scripts/35_export_frontend.py
|
| 13 |
+
du -sh artifacts_ca artifacts_ca/layers export_ca/v1 export/ca/v1/fe || true
|
| 14 |
+
python - <<'PY'
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from huggingface_hub import HfApi
|
| 17 |
+
api, repo, b = HfApi(), "TrendeX90/ca-cube", Path("/root/trendex/backend")
|
| 18 |
+
def folder(local, remote, **kw):
|
| 19 |
+
api.upload_folder(repo_id=repo, repo_type="dataset", folder_path=str(local), path_in_repo=remote,
|
| 20 |
+
commit_message=f"formula v2 (barren rule): {remote}", **kw)
|
| 21 |
+
print("pushed", remote, flush=True)
|
| 22 |
+
folder(b / "export/ca/v1/fe", "formula/export/ca/v1/fe")
|
| 23 |
+
folder(b / "artifacts_ca/layers", "formula/artifacts_ca/layers")
|
| 24 |
+
for f in ("cells.parquet", "S.npy"):
|
| 25 |
+
api.upload_file(path_or_fileobj=str(b / "artifacts_ca" / f), path_in_repo=f"formula/artifacts_ca/{f}",
|
| 26 |
+
repo_id=repo, repo_type="dataset", commit_message=f"formula v2: artifacts_ca/{f}")
|
| 27 |
+
print("pushed", f, flush=True)
|
| 28 |
+
folder(b / "export_ca/v1", "formula/export_ca/v1")
|
| 29 |
+
folder(b / "artifacts_ca", "formula/artifacts_ca", ignore_patterns=["*.npy", "*.npz", "layers/**", "cells.parquet"])
|
| 30 |
+
PY
|
| 31 |
+
echo "FORMULA2_DONE $(date -u +%T)"
|