Konuktor92 commited on
Commit
a5899e5
·
verified ·
1 Parent(s): 70cca31

backup _backup/scripts 17:44:23

Browse files
_backup/scripts/05_aoi_ca.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Central Asia area of interest: KAZ, KGZ, TJK, TKM, UZB (geoBoundaries gbOpen ADM0 + ADM1).
2
+
3
+ Writes to --out: ca_adm0.geojson (country polygons, iso3), ca_adm1.geojson (region polygons, iso3, shapeName),
4
+ aoi_request.geojson (simplified union, used for downloads), aoi_summary.json.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ from pathlib import Path
11
+
12
+ import geopandas as gpd
13
+ import pandas as pd
14
+ import requests
15
+
16
+ API = "https://www.geoboundaries.org/api/current/gbOpen/{iso}/{level}/"
17
+ ISO3 = ["KAZ", "KGZ", "TJK", "TKM", "UZB"]
18
+ SINU = "+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +R=6371007.181 +units=m +no_defs"
19
+
20
+
21
+ def fetch(iso: str, level: str, cache: Path) -> gpd.GeoDataFrame:
22
+ path = cache / f"geoBoundaries-{iso}-{level}.geojson"
23
+ if not path.exists():
24
+ meta = requests.get(API.format(iso=iso, level=level), timeout=60).json()
25
+ r = requests.get(meta["gjDownloadURL"], timeout=600)
26
+ r.raise_for_status()
27
+ path.write_bytes(r.content)
28
+ g = gpd.read_file(path).to_crs(4326)
29
+ g["iso3"] = iso
30
+ return g
31
+
32
+
33
+ def main() -> None:
34
+ ap = argparse.ArgumentParser()
35
+ ap.add_argument("--out", type=Path, default=Path("/root/trendex-ca/data/aoi"))
36
+ a = ap.parse_args()
37
+ a.out.mkdir(parents=True, exist_ok=True)
38
+ adm0 = gpd.GeoDataFrame(pd.concat([fetch(i, "ADM0", a.out) for i in ISO3], ignore_index=True), crs=4326)
39
+ adm1 = gpd.GeoDataFrame(pd.concat([fetch(i, "ADM1", a.out) for i in ISO3], ignore_index=True), crs=4326)
40
+ adm0[["iso3", "shapeName", "geometry"]].to_file(a.out / "ca_adm0.geojson", driver="GeoJSON")
41
+ adm1[["iso3", "shapeName", "geometry"]].to_file(a.out / "ca_adm1.geojson", driver="GeoJSON")
42
+ union = adm0.union_all().simplify(0.01)
43
+ gpd.GeoDataFrame({"name": ["Central Asia (KAZ, KGZ, TJK, TKM, UZB)"]}, geometry=[union], crs=4326) \
44
+ .to_file(a.out / "aoi_request.geojson", driver="GeoJSON")
45
+ area = adm0.to_crs(SINU).area / 1e6
46
+ summary = {"countries": dict(zip(adm0["iso3"], area.round().astype(int))),
47
+ "total_km2": int(area.sum()), "expected_1km_cells": int(area.sum() / 0.8586),
48
+ "adm1_regions": int(len(adm1)), "bbox_lon_lat": [round(v, 3) for v in adm0.total_bounds]}
49
+ (a.out / "aoi_summary.json").write_text(json.dumps(summary, indent=2))
50
+ print(json.dumps(summary, indent=2))
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
_backup/scripts/10_download_ca.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Central Asia downloads (earthaccess, straight from NASA archives; re-runnable, skips existing files).
2
+
3
+ python ca/10_download_ca.py lpdaac --products MOD13A3 MCD12Q1 NASADEM
4
+ python ca/10_download_ca.py gesdisc
5
+
6
+ MOD13A3: Apr-Oct only (what the formula and the model use). NASADEM: only 1-degree tiles touching the AOI.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import re
13
+ from pathlib import Path
14
+
15
+ import geopandas as gpd
16
+ from shapely.geometry import box
17
+
18
+ ROOT = Path("/root/trendex-ca/data")
19
+ RAW = ROOT / "raw"
20
+ AOI = ROOT / "aoi" / "aoi_request.geojson"
21
+ LAST_YEAR = 2025
22
+ NDVI_MONTHS = set(range(4, 11))
23
+
24
+ LPDAAC = {"MOD13A3": ("MOD13A3", "061", "2000-02-01", f"{LAST_YEAR}-12-31"),
25
+ "MCD12Q1": ("MCD12Q1", "061", "2020-01-01", "2020-12-31"),
26
+ "NASADEM": ("NASADEM_HGT", "001", "2000-02-11", "2000-02-21")}
27
+ GESDISC = {"GPM_3IMERGM": ("07", "2000-06-01"), "GLDAS_NOAH025_M": ("2.1", "2000-01-01")}
28
+
29
+
30
+ def aoi():
31
+ g = gpd.read_file(AOI).to_crs(4326)
32
+ return g.union_all(), tuple(g.total_bounds)
33
+
34
+
35
+ def granule_name(gr) -> str:
36
+ return gr["umm"].get("GranuleUR", "")
37
+
38
+
39
+ def keep(name: str, product: str, shape) -> bool:
40
+ if product == "MOD13A3":
41
+ m = re.search(r"\.A(\d{4})(\d{3})\.", name)
42
+ if not m:
43
+ return True
44
+ import datetime as dt
45
+ month = (dt.date(int(m[1]), 1, 1) + dt.timedelta(days=int(m[2]) - 1)).month
46
+ return month in NDVI_MONTHS
47
+ if product == "NASADEM":
48
+ m = re.search(r"([ns])(\d{2})([ew])(\d{3})", name.lower())
49
+ if not m:
50
+ return True
51
+ lat = int(m[2]) * (1 if m[1] == "n" else -1)
52
+ lon = int(m[4]) * (1 if m[3] == "e" else -1)
53
+ return shape.intersects(box(lon, lat, lon + 1, lat + 1))
54
+ return True
55
+
56
+
57
+ def lpdaac(products: list[str]) -> None:
58
+ import earthaccess
59
+ earthaccess.login(strategy="netrc")
60
+ shape, bbox = aoi()
61
+ for name in products:
62
+ short, ver, first, last = LPDAAC[name]
63
+ found = earthaccess.search_data(short_name=short, version=ver, temporal=(first, last), bounding_box=bbox)
64
+ sel = [g for g in found if keep(granule_name(g), name, shape)]
65
+ dest = RAW / "earthaccess" / name
66
+ dest.mkdir(parents=True, exist_ok=True)
67
+ print(f"[lpdaac] {name}: {len(found)} granules in bbox, {len(sel)} kept", flush=True)
68
+ earthaccess.download(sel, local_path=str(dest), threads=24)
69
+ print(f"[lpdaac] {name}: {len(list(dest.iterdir()))} files on disk", flush=True)
70
+ print("LPDAAC_COMPLETE", products, flush=True)
71
+
72
+
73
+ def gesdisc() -> None:
74
+ import earthaccess
75
+ earthaccess.login(strategy="netrc")
76
+ _, bbox = aoi()
77
+ for short, (ver, first) in GESDISC.items():
78
+ found = earthaccess.search_data(short_name=short, version=ver, temporal=(first, f"{LAST_YEAR}-12-31"),
79
+ bounding_box=bbox)
80
+ dest = RAW / "gesdisc" / short
81
+ dest.mkdir(parents=True, exist_ok=True)
82
+ print(f"[gesdisc] {short}: {len(found)} granules", flush=True)
83
+ earthaccess.download(found, local_path=str(dest), threads=16)
84
+ print(f"[gesdisc] {short}: {len(list(dest.iterdir()))} files on disk", flush=True)
85
+ print("GESDISC_COMPLETE", flush=True)
86
+
87
+
88
+ def main() -> None:
89
+ ap = argparse.ArgumentParser()
90
+ ap.add_argument("step", choices=["lpdaac", "gesdisc"])
91
+ ap.add_argument("--products", nargs="*", default=["MOD13A3", "MCD12Q1", "NASADEM"])
92
+ a = ap.parse_args()
93
+ lpdaac(a.products) if a.step == "lpdaac" else gesdisc()
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()
_backup/scripts/20_build_cube_ca.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Central Asia cube (same schema family as naryn-cube), built for ~4.6M cells.
2
+
3
+ python ca/20_build_cube_ca.py --stage ndvi # cells.parquet + monthly NDVI (Apr-Oct), manifest partial=true
4
+ python ca/20_build_cube_ca.py --stage weather # adds IMERG + GLDAS columns to monthly, partial=false
5
+
6
+ Grid: global MODIS sinusoidal 1 km grid cut to the 5-country bbox; cell kept if its centre is in a country.
7
+ Membership by rasterizing geoBoundaries ADM0/ADM1 (cell-centre rule). NDVI never resampled.
8
+ Monthly rows: Apr-Oct only. Columns: cell_id, month, ndvi, ndvi_rel, ndvi_ok
9
+ (+ precip [mm/month], precip_winter [Oct(prev)-Mar sum, mm], tair [deg C, GLDAS], soil_moist, swe [kg m-2]).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import calendar
15
+ import json
16
+ import re
17
+ import time
18
+ from concurrent.futures import ProcessPoolExecutor
19
+ from pathlib import Path
20
+
21
+ import geopandas as gpd
22
+ import numpy as np
23
+ import pandas as pd
24
+ import pyarrow as pa
25
+ import pyarrow.parquet as pq
26
+ import rasterio
27
+ import xarray as xr
28
+ from pyproj import Transformer
29
+ from rasterio.features import rasterize
30
+ from rasterio.warp import Resampling, reproject, transform_bounds
31
+ from rasterio.windows import from_bounds
32
+ from scipy.ndimage import uniform_filter
33
+
34
+ ROOT = Path("/root/trendex-ca/data")
35
+ RAW, AOI_DIR, OUT, CACHE = ROOT / "raw", ROOT / "aoi", ROOT / "cube", ROOT / "cache"
36
+ MONTHS = list(range(4, 11))
37
+ BLOCK, STEEP_DEG, TPI_WINDOW, WORKERS = 11, 35.0, 5, 40
38
+ SINU = "+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +R=6371007.181 +units=m +no_defs"
39
+ SINU_CRS = rasterio.crs.CRS.from_proj4(SINU)
40
+ TILE = 1111950.5196666666
41
+ X0, Y0 = -20015109.355798, 10007554.677899
42
+ PIX1K = TILE / 1200
43
+ GRID: dict = {}
44
+ KEEP: tuple = () # (rows, cols) of kept cells; set before forking workers
45
+ LONLAT: tuple = ()
46
+
47
+
48
+ def log(m):
49
+ print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
50
+
51
+
52
+ # ----------------------------------------------------------------------------- grid + io
53
+ def build_grid() -> dict:
54
+ minx, miny, maxx, maxy = gpd.read_file(AOI_DIR / "aoi_request.geojson").to_crs(SINU).total_bounds
55
+ c0, c1 = int(np.floor((minx - X0) / PIX1K)), int(np.ceil((maxx - X0) / PIX1K))
56
+ r0, r1 = int(np.floor((Y0 - maxy) / PIX1K)), int(np.ceil((Y0 - miny) / PIX1K))
57
+ left, top = X0 + c0 * PIX1K, Y0 - r0 * PIX1K
58
+ return {"transform": rasterio.transform.from_origin(left, top, PIX1K, PIX1K), "shape": (r1 - r0, c1 - c0),
59
+ "left": left, "top": top, "r0": r0, "c0": c0}
60
+
61
+
62
+ def _open(src):
63
+ if isinstance(src, str):
64
+ with rasterio.open(src) as s:
65
+ return s.read(1), s.nodata, s.transform, s.crs
66
+ _, path, sds, npix = src
67
+ from pyhdf.SD import SD, SDC
68
+ m = re.search(r"\.h(\d{2})v(\d{2})\.", Path(path).name)
69
+ h, v = int(m[1]), int(m[2])
70
+ f = SD(path, SDC.READ)
71
+ try:
72
+ ds = f.select(sds)
73
+ raw, attrs = ds.get(), ds.attributes()
74
+ finally:
75
+ f.end()
76
+ pix = TILE / npix
77
+ return raw, attrs.get("_FillValue"), rasterio.transform.from_origin(X0 + h * TILE, Y0 - v * TILE, pix, pix), SINU_CRS
78
+
79
+
80
+ def to_master(srcs, resampling, fn=None) -> np.ndarray:
81
+ out = np.full(GRID["shape"], np.nan, dtype="float32")
82
+ for src in srcs:
83
+ raw, nodata, tr, crs = _open(src)
84
+ if fn:
85
+ a = fn(raw, nodata)
86
+ else:
87
+ a = raw.astype("float32")
88
+ if nodata is not None:
89
+ a[raw == nodata] = np.nan
90
+ tmp = np.full(GRID["shape"], np.nan, dtype="float32")
91
+ reproject(a.astype("float32"), tmp, src_transform=tr, src_crs=crs, dst_transform=GRID["transform"],
92
+ dst_crs=SINU_CRS, resampling=resampling, src_nodata=np.nan, dst_nodata=np.nan)
93
+ out = np.where(np.isnan(out), tmp, out)
94
+ return out
95
+
96
+
97
+ def hdf_by_date(product: str, sds: str, npix: int, months=None) -> dict:
98
+ by: dict = {}
99
+ for p in sorted((RAW / "earthaccess" / product).glob("*.hdf")):
100
+ m = re.search(r"\.A(\d{4})(\d{3})\.", p.name)
101
+ d = pd.Timestamp(year=int(m[1]), month=1, day=1) + pd.Timedelta(days=int(m[2]) - 1)
102
+ if months is None or d.month in months:
103
+ by.setdefault(d, []).append(("hdf", str(p), sds, npix))
104
+ return dict(sorted(by.items()))
105
+
106
+
107
+ # ----------------------------------------------------------------------------- workers (forked; use globals)
108
+ def ndvi_job(args):
109
+ d, nd_src, rel_src = args
110
+ a = to_master(nd_src, Resampling.nearest)
111
+ if np.nanmax(a) > 1.5:
112
+ a = a * 1e-4
113
+ rel = to_master(rel_src, Resampling.nearest)
114
+ r, c = KEEP
115
+ relv = rel[r, c]
116
+ return d, a[r, c].astype("float32"), np.where(np.isfinite(relv), relv, -1).astype("int8")
117
+
118
+
119
+ def dem_job(src):
120
+ """One NASADEM 1-degree tile -> its window of the master grid (avoids shipping full-size arrays)."""
121
+ raw, nodata, tr, crs = _open(src)
122
+ z = raw.astype("float32")
123
+ z[raw == (nodata if nodata is not None else -32768)] = np.nan
124
+ lat = tr.f + tr.e * (np.arange(z.shape[0]) + 0.5)
125
+ dy = abs(tr.e) * 111_320.0
126
+ dx = tr.a * 111_320.0 * np.cos(np.deg2rad(lat))[:, None]
127
+ gy_rows, gx_cols = np.gradient(z)
128
+ gx, gy = gx_cols / dx, -gy_rows / dy
129
+ slope = np.degrees(np.arctan(np.hypot(gx, gy))).astype("float32")
130
+ aspect = np.arctan2(-gx, -gy)
131
+ layers = {"z": z, "z2": z * z, "slope": slope,
132
+ "steep": np.where(np.isnan(slope), np.nan, slope > STEEP_DEG).astype("float32"),
133
+ "asin": np.sin(aspect).astype("float32"), "acos": np.cos(aspect).astype("float32")}
134
+ h, w = z.shape
135
+ b = transform_bounds(crs, SINU_CRS, tr.c, tr.f + tr.e * h, tr.c + tr.a * w, tr.f, densify_pts=21)
136
+ minx, miny, maxx, maxy = b
137
+ r0 = max(int(np.floor((GRID["top"] - maxy) / PIX1K)) - 1, 0)
138
+ c0 = max(int(np.floor((minx - GRID["left"]) / PIX1K)) - 1, 0)
139
+ r1 = min(int(np.ceil((GRID["top"] - miny) / PIX1K)) + 1, GRID["shape"][0])
140
+ c1 = min(int(np.ceil((maxx - GRID["left"]) / PIX1K)) + 1, GRID["shape"][1])
141
+ if r1 <= r0 or c1 <= c0:
142
+ return None
143
+ wtr = rasterio.windows.transform(rasterio.windows.Window(c0, r0, c1 - c0, r1 - r0), GRID["transform"])
144
+ out = {}
145
+ for k, arr in layers.items():
146
+ tmp = np.full((r1 - r0, c1 - c0), np.nan, "float32")
147
+ reproject(arr, tmp, src_transform=tr, src_crs=crs, dst_transform=wtr, dst_crs=SINU_CRS,
148
+ resampling=Resampling.average, src_nodata=np.nan, dst_nodata=np.nan)
149
+ out[k] = tmp
150
+ return r0, c0, out
151
+
152
+
153
+ def weather_job(path: str):
154
+ lon, lat = LONLAT
155
+ p = Path(path)
156
+ if "IMERG" in p.name:
157
+ ym = re.search(r"\.(\d{8})-S", p.name).group(1)
158
+ y, m = int(ym[:4]), int(ym[4:6])
159
+ with xr.open_dataset(p, group="Grid", engine="h5netcdf") as ds:
160
+ da = ds["precipitation"].squeeze(drop=True).sel(lon=slice(float(lon.min()) - 1, float(lon.max()) + 1),
161
+ lat=slice(float(lat.min()) - 1, float(lat.max()) + 1)).load()
162
+ v = da.interp(lon=xr.DataArray(lon, dims="c"), lat=xr.DataArray(lat, dims="c")).values
163
+ return "precip", y, m, (v * 24 * calendar.monthrange(y, m)[1]).astype("float32")
164
+ ym = re.search(r"\.A(\d{6})\.", p.name).group(1)
165
+ y, m = int(ym[:4]), int(ym[4:])
166
+ with xr.open_dataset(p) as ds:
167
+ sub = ds[["SoilMoi0_10cm_inst", "SWE_inst", "Tair_f_inst"]].squeeze(drop=True).sel(
168
+ lon=slice(float(lon.min()) - 1, float(lon.max()) + 1), lat=slice(float(lat.min()) - 1, float(lat.max()) + 1)).load()
169
+ pts = sub.interp(lon=xr.DataArray(lon, dims="c"), lat=xr.DataArray(lat, dims="c"))
170
+ return "gldas", y, m, (pts["SoilMoi0_10cm_inst"].values.astype("float32"), pts["SWE_inst"].values.astype("float32"),
171
+ (pts["Tair_f_inst"].values - 273.15).astype("float32"))
172
+
173
+
174
+ # ----------------------------------------------------------------------------- stages
175
+ def stage_ndvi(manifest: dict) -> None:
176
+ global KEEP
177
+ t0 = time.time()
178
+ adm0 = gpd.read_file(AOI_DIR / "ca_adm0.geojson").to_crs(SINU)
179
+ adm1 = gpd.read_file(AOI_DIR / "ca_adm1.geojson").to_crs(SINU)
180
+ iso = list(adm0["iso3"])
181
+ cmap = rasterize(((g, i + 1) for i, g in enumerate(adm0.geometry)), out_shape=GRID["shape"],
182
+ transform=GRID["transform"], fill=0, dtype="int16")
183
+ rmap = rasterize(((g, i + 1) for i, g in enumerate(adm1.geometry)), out_shape=GRID["shape"],
184
+ transform=GRID["transform"], fill=0, dtype="int32")
185
+ r, c = np.nonzero(cmap > 0)
186
+ KEEP = (r, c)
187
+ x = GRID["left"] + (c + 0.5) * PIX1K
188
+ y = GRID["top"] - (r + 0.5) * PIX1K
189
+ lon, lat = Transformer.from_crs(SINU_CRS, 4326, always_xy=True).transform(x, y)
190
+ reg = rmap[r, c]
191
+ cells = pd.DataFrame({
192
+ "cell_id": ((r + GRID["r0"]) * 43200 + (c + GRID["c0"])).astype("int64"), "row": r, "col": c,
193
+ "x": x, "y": y, "lon": lon.astype("float32"), "lat": lat.astype("float32"),
194
+ "country": np.array(iso)[cmap[r, c] - 1],
195
+ "region": np.where(reg > 0, adm1["shapeName"].values[np.maximum(reg - 1, 0)], None),
196
+ "block_row": (r // BLOCK).astype("int16"), "block_col": (c // BLOCK).astype("int16")})
197
+ cells["block_id"] = cells["block_row"].astype(str) + "-" + cells["block_col"].astype(str)
198
+ log(f"grid {GRID['shape']}, cells {len(cells)}")
199
+
200
+ lc = hdf_by_date("MCD12Q1", "LC_Type1", 2400)
201
+ lc_src = [s for v in lc.values() for s in v]
202
+ lw_src = [("hdf", s[1], "LW", 2400) for s in lc_src]
203
+ clean = lambda raw, nd: np.where(raw == 255, np.nan, raw).astype("float32") # noqa: E731
204
+ cells["lc_type1"] = to_master(lc_src, Resampling.mode, fn=clean)[r, c]
205
+ for name, cls in {"grass_frac": [10], "barren_frac": [16], "crop_frac": [12, 14], "forest_frac": [1, 2, 3, 4, 5],
206
+ "ice_frac": [15], "urban_frac": [13]}.items():
207
+ cells[name] = to_master(lc_src, Resampling.average,
208
+ fn=lambda raw, nd, k=cls: np.where(raw == 255, np.nan, np.isin(raw, k)).astype("float32"))[r, c]
209
+ cells["water_frac"] = to_master(lw_src, Resampling.average,
210
+ fn=lambda raw, nd: np.where(raw == 255, np.nan, raw == 1).astype("float32"))[r, c]
211
+ log(f"land cover done {time.time() - t0:.0f}s")
212
+
213
+ dem = sorted((RAW / "earthaccess" / "NASADEM").glob("*.zip"))
214
+ srcs = [f"/vsizip/{z}/{z.stem.split('_')[-1]}.hgt" for z in dem]
215
+ acc = {k: np.full(GRID["shape"], np.nan, "float32") for k in ("z", "z2", "slope", "steep", "asin", "acos")}
216
+ with ProcessPoolExecutor(WORKERS) as pool:
217
+ for res in pool.map(dem_job, srcs, chunksize=2):
218
+ if res is None:
219
+ continue
220
+ r0, c0, out = res
221
+ for k, a in out.items():
222
+ view = acc[k][r0:r0 + a.shape[0], c0:c0 + a.shape[1]]
223
+ np.copyto(view, a, where=np.isnan(view) & np.isfinite(a))
224
+ elev = acc["z"]
225
+ cells["elev_mean"] = elev[r, c]
226
+ cells["elev_std"] = np.sqrt(np.clip(acc["z2"] - elev ** 2, 0, None))[r, c]
227
+ cells["slope_mean"], cells["steep_share"] = acc["slope"][r, c], acc["steep"][r, c]
228
+ cells["aspect_sin"], cells["aspect_cos"] = acc["asin"][r, c], acc["acos"][r, c]
229
+ valid = np.isfinite(elev)
230
+ num = uniform_filter(np.where(valid, elev, 0), TPI_WINDOW)
231
+ den = uniform_filter(valid.astype("float32"), TPI_WINDOW)
232
+ cells["tpi"] = (elev - num / np.maximum(den, 1e-6))[r, c]
233
+ del acc
234
+ rules = [("water", (cells["water_frac"] > 0.5) | (cells["lc_type1"] == 17)), ("ice", cells["lc_type1"] == 15),
235
+ ("urban", cells["lc_type1"] == 13), ("too_steep", cells["slope_mean"] > STEEP_DEG),
236
+ ("barren", cells["lc_type1"] == 16), ("cropland", cells["lc_type1"].isin([12, 14])),
237
+ ("forest", cells["lc_type1"].isin([1, 2, 3, 4, 5]))]
238
+ reason = pd.Series(pd.NA, index=cells.index, dtype="string")
239
+ for name, cond in rules:
240
+ reason = reason.mask(reason.isna() & cond.fillna(False), name)
241
+ cells["mask_reason"] = reason
242
+ OUT.mkdir(parents=True, exist_ok=True)
243
+ cells.to_parquet(OUT / "cells.parquet", index=False)
244
+ manifest["cells"] = {"n": len(cells), "by_country": cells["country"].value_counts().astype(int).to_dict(),
245
+ "mask_reason": {str(k): int(v) for k, v in cells["mask_reason"].value_counts(dropna=False).items()},
246
+ "dem_tiles": len(srcs)}
247
+ log(f"cells.parquet written ({len(srcs)} DEM tiles) {time.time() - t0:.0f}s")
248
+
249
+ nd = hdf_by_date("MOD13A3", "1 km monthly NDVI", 1200, set(MONTHS))
250
+ nr = hdf_by_date("MOD13A3", "1 km monthly pixel reliability", 1200, set(MONTHS))
251
+ CACHE.mkdir(parents=True, exist_ok=True)
252
+ dates = list(nd)
253
+ ndvi = np.lib.format.open_memmap(CACHE / "ndvi.npy", mode="w+", dtype="float32", shape=(len(dates), len(cells)))
254
+ rel = np.lib.format.open_memmap(CACHE / "rel.npy", mode="w+", dtype="int8", shape=(len(dates), len(cells)))
255
+ with ProcessPoolExecutor(WORKERS) as pool:
256
+ for d, a, b in pool.map(ndvi_job, [(d, nd[d], nr.get(d, [])) for d in dates]):
257
+ i = dates.index(d)
258
+ ndvi[i], rel[i] = a, b
259
+ ndvi.flush(); rel.flush()
260
+ pd.Series([str(d.date()) for d in dates]).to_csv(CACHE / "dates.csv", index=False)
261
+ log(f"ndvi {len(dates)} months {time.time() - t0:.0f}s")
262
+ write_monthly(cells["cell_id"].values, dates, ndvi, rel, None)
263
+ manifest["partial"] = True
264
+ manifest["monthly"] = {"months": MONTHS, "n_dates": len(dates), "columns": ["cell_id", "month", "ndvi", "ndvi_rel", "ndvi_ok"],
265
+ "note": "PARTIAL: NDVI only; weather columns follow"}
266
+
267
+
268
+ def write_monthly(ids, dates, ndvi, rel, wx, root: Path | None = None) -> None:
269
+ root = root or OUT / "monthly"
270
+ years = sorted({d.year for d in dates})
271
+ for yr in years:
272
+ parts = []
273
+ for i, d in enumerate(dates):
274
+ if d.year != yr:
275
+ continue
276
+ cols = {"cell_id": ids, "month": np.full(len(ids), d.month, "int8"), "ndvi": ndvi[i],
277
+ "ndvi_rel": rel[i], "ndvi_ok": np.isin(rel[i], (0, 1))}
278
+ if wx is not None:
279
+ for k in ("precip", "precip_winter", "tair", "soil_moist", "swe"):
280
+ cols[k] = wx[k].get((yr, d.month), np.full(len(ids), np.nan, "float32"))
281
+ parts.append(pa.table(cols))
282
+ dest = root / f"year={yr}"
283
+ dest.mkdir(parents=True, exist_ok=True)
284
+ pq.write_table(pa.concat_tables(parts), dest / "part.parquet", row_group_size=2_000_000)
285
+ log(f"monthly {yr} written")
286
+
287
+
288
+ def stage_weather(manifest: dict) -> None:
289
+ global LONLAT
290
+ t0 = time.time()
291
+ cells = pd.read_parquet(OUT / "cells.parquet", columns=["cell_id", "lon", "lat"])
292
+ LONLAT = (cells["lon"].values.astype("float64"), cells["lat"].values.astype("float64"))
293
+ files = sorted(str(p) for p in (RAW / "gesdisc" / "GPM_3IMERGM").glob("*.HDF5")) + \
294
+ sorted(str(p) for p in (RAW / "gesdisc" / "GLDAS_NOAH025_M").glob("*.nc4"))
295
+ precip, soil, swe, tair = {}, {}, {}, {}
296
+ with ProcessPoolExecutor(24) as pool:
297
+ for kind, y, m, v in pool.map(weather_job, files, chunksize=2):
298
+ if kind == "precip":
299
+ precip[(y, m)] = v
300
+ else:
301
+ soil[(y, m)], swe[(y, m)], tair[(y, m)] = v
302
+ log(f"weather interpolated: {len(precip)} IMERG, {len(soil)} GLDAS months {time.time() - t0:.0f}s")
303
+ winter = {}
304
+ for yr in range(2001, 2026):
305
+ keys = [(yr - 1, 10), (yr - 1, 11), (yr - 1, 12), (yr, 1), (yr, 2), (yr, 3)]
306
+ if all(k in precip for k in keys):
307
+ w = sum(precip[k] for k in keys)
308
+ for mo in MONTHS:
309
+ winter[(yr, mo)] = w
310
+ wx = {"precip": precip, "precip_winter": winter, "tair": tair, "soil_moist": soil, "swe": swe}
311
+ dates = [pd.Timestamp(s) for s in pd.read_csv(CACHE / "dates.csv").iloc[:, 0]]
312
+ ndvi = np.load(CACHE / "ndvi.npy", mmap_mode="r")
313
+ rel = np.load(CACHE / "rel.npy", mmap_mode="r")
314
+ # write the full table next to the NDVI-only one, then swap (readers of the old files are not disturbed)
315
+ write_monthly(cells["cell_id"].values, dates, ndvi, rel, wx, OUT / "monthly_full")
316
+ old = OUT / "monthly_ndvi_only"
317
+ if old.exists():
318
+ import shutil
319
+ shutil.rmtree(old)
320
+ (OUT / "monthly").rename(old)
321
+ (OUT / "monthly_full").rename(OUT / "monthly")
322
+ manifest["partial"] = False
323
+ manifest["monthly"] = {"months": MONTHS, "n_dates": len(dates),
324
+ "columns": ["cell_id", "month", "ndvi", "ndvi_rel", "ndvi_ok", "precip", "precip_winter",
325
+ "tair", "soil_moist", "swe"]}
326
+ log(f"weather stage done {time.time() - t0:.0f}s")
327
+
328
+
329
+ def main() -> None:
330
+ global GRID
331
+ ap = argparse.ArgumentParser()
332
+ ap.add_argument("--stage", choices=["ndvi", "weather"], required=True)
333
+ a = ap.parse_args()
334
+ GRID = build_grid()
335
+ mpath = OUT / "manifest.json"
336
+ manifest = json.loads(mpath.read_text()) if mpath.exists() else {}
337
+ manifest.update({
338
+ "name": "TrendeX Central Asia cube", "synthetic": False,
339
+ "updated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
340
+ "grid": {"crs": SINU, "shape": GRID["shape"], "res_m": PIX1K, "origin_left_top": [GRID["left"], GRID["top"]],
341
+ "cell_id": "global_row * 43200 + global_col on the MODIS 1 km grid", "block_cells": BLOCK},
342
+ "aoi": "geoBoundaries gbOpen ADM0 of KAZ, KGZ, TJK, TKM, UZB; region = ADM1 shapeName; cell-centre rule",
343
+ "units": {"ndvi": "NDVI (scaled)", "ndvi_rel": "MOD13A3 pixel reliability (-1 missing, 0 good, 1 marginal, 2 snow, 3 cloud)",
344
+ "ndvi_ok": "reliability 0-1", "precip": "mm per month (IMERG Final V07)",
345
+ "precip_winter": "mm, Oct (previous year) .. Mar sum (IMERG)", "tair": "deg C, GLDAS-2.1 air temperature",
346
+ "soil_moist": "kg m-2, GLDAS-2.1 0-10 cm", "swe": "kg m-2, GLDAS-2.1",
347
+ "elev_mean": "m (NASADEM 30 m averaged)", "slope_mean": "deg, computed at 30 m then averaged to 1 km",
348
+ "lc_type1": "IGBP MCD12Q1 2020 mode over 500 m pixels"},
349
+ "datasets": {"MOD13A3": "061, doi:10.5067/MODIS/MOD13A3.061", "MCD12Q1": "061, doi:10.5067/MODIS/MCD12Q1.061",
350
+ "NASADEM_HGT": "001, doi:10.5067/MEaSUREs/NASADEM/NASADEM_HGT.001",
351
+ "GPM_3IMERGM": "07, doi:10.5067/GPM/IMERG/3B-MONTH/07", "GLDAS_NOAH025_M": "2.1, doi:10.5067/SXAVCZFAQLNO"},
352
+ "notes": ["Months Apr-Oct only. No Aqua NDVI, no MODIS LST/snow in the CA cube (GLDAS tair/swe instead).",
353
+ "mask_reason adds barren / cropland / forest to the Naryn rules; first matching rule wins."]})
354
+ stage_ndvi(manifest) if a.stage == "ndvi" else stage_weather(manifest)
355
+ mpath.write_text(json.dumps(manifest, indent=2, default=str))
356
+ log(f"STAGE_{a.stage.upper()}_DONE")
357
+
358
+
359
+ if __name__ == "__main__":
360
+ main()
_backup/scripts/30_train_ca.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train/evaluate expected greenness v2-ca exactly as locked in configs/model_v2_ca.yaml.
2
+
3
+ python ca/30_train_ca.py --git-commit <hash>
4
+
5
+ Training/evaluation on a 150k-cell sample; out-of-fold predictions for every eligible cell.
6
+ Writes runs/v2_ca/: metrics.json, model_ca.ubj, feature_schema.json, conformal.json, climatology / weather
7
+ climatology parquet, summer_residual.npy (cells x years, residual vs all-years climatology), expected_block.parquet.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import time
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+ import pyarrow.parquet as pq
19
+ import xgboost as xgb
20
+ from sklearn.linear_model import Ridge
21
+ from sklearn.model_selection import GroupKFold
22
+
23
+ CUBE = Path("/root/trendex-ca/data/cube")
24
+ RUN = Path("/root/trendex-ca/runs/v2_ca")
25
+ YEARS = np.arange(2001, 2026)
26
+ MONTHS = np.arange(5, 10)
27
+ CUBE_MONTHS = list(range(4, 11))
28
+ STATIC = ["elev_mean", "elev_std", "slope_mean", "steep_share", "aspect_sin", "aspect_cos", "tpi",
29
+ "grass_frac", "barren_frac", "crop_frac", "lc_type1", "lat"]
30
+ WEATHER = ["precip_m", "precip_2m", "precip_winter", "tair_m", "tair_prev", "soil_m", "swe_apr"]
31
+ FEATURES = STATIC + ["month", "clim_ndvi"] + WEATHER
32
+ FIXED = {"tree_method": "hist", "device": "cuda", "objective": "reg:squarederror"}
33
+ SEEDS = [0, 1, 2]
34
+ N_SAMPLE = 150_000
35
+
36
+
37
+ def log(m):
38
+ print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
39
+
40
+
41
+ def load_arrays(cells_all: pd.DataFrame, elig: np.ndarray) -> dict:
42
+ """(n_elig, 25 years, 7 months Apr-Oct) arrays straight from the yearly files (rows = month blocks x all cells)."""
43
+ n_all, idx = len(cells_all), np.nonzero(elig)[0]
44
+ shape = (len(idx), len(YEARS), len(CUBE_MONTHS))
45
+ arr = {k: np.full(shape, np.nan, "float32") for k in ["ndvi", "precip", "precip_winter", "tair", "soil_moist", "swe"]}
46
+ for j, yr in enumerate(YEARS):
47
+ t = pq.read_table(CUBE / "monthly" / f"year={yr}" / "part.parquet",
48
+ columns=["month", "ndvi", "ndvi_ok", "precip", "precip_winter", "tair", "soil_moist", "swe"])
49
+ months = t.column("month").to_numpy()
50
+ assert len(months) % n_all == 0, "monthly file is not month-blocks x all cells"
51
+ ok = t.column("ndvi_ok").to_numpy(zero_copy_only=False)
52
+ cols = {k: t.column(k).to_numpy(zero_copy_only=False).astype("float32") for k in arr}
53
+ cols["ndvi"] = np.where(ok, cols["ndvi"], np.nan)
54
+ for b in range(len(months) // n_all):
55
+ mo = int(months[b * n_all])
56
+ mi = CUBE_MONTHS.index(mo)
57
+ for k in arr:
58
+ arr[k][:, j, mi] = cols[k][b * n_all:(b + 1) * n_all][idx]
59
+ log(f"loaded {yr}")
60
+ return arr
61
+
62
+
63
+ def build_features(cells: pd.DataFrame, arr: dict, run: Path) -> dict:
64
+ mi = [CUBE_MONTHS.index(m) for m in MONTHS]
65
+ prev = [CUBE_MONTHS.index(m - 1) for m in MONTHS]
66
+ take = lambda a, ix: a[:, :, ix] # noqa: E731
67
+ anom = lambda x: x - np.nanmean(x, axis=1, keepdims=True) # noqa: E731
68
+ with np.errstate(all="ignore"):
69
+ raw_m = {"precip_m": take(arr["precip"], mi), "precip_2m": take(arr["precip"], mi) + take(arr["precip"], prev),
70
+ "tair_m": take(arr["tair"], mi), "tair_prev": take(arr["tair"], prev), "soil_m": take(arr["soil_moist"], mi)}
71
+ raw_y = {"precip_winter": arr["precip_winter"][:, :, CUBE_MONTHS.index(5)],
72
+ "swe_apr": arr["swe"][:, :, CUBE_MONTHS.index(4)]}
73
+ f = {k: anom(v) for k, v in raw_m.items()}
74
+ f |= {k: np.repeat(anom(v)[:, :, None], len(MONTHS), axis=2) for k, v in raw_y.items()}
75
+ wc = pd.concat([pd.DataFrame({"cell_id": cells["cell_id"].values, "month": int(mo)} |
76
+ {f"{k}_mean": np.nanmean(v[:, :, j], axis=1).astype("float32") for k, v in raw_m.items()} |
77
+ {f"{k}_mean": np.nanmean(v, axis=1).astype("float32") for k, v in raw_y.items()})
78
+ for j, mo in enumerate(MONTHS)], ignore_index=True)
79
+ wc.to_parquet(run / "weather_climatology.parquet", index=False)
80
+ f["ndvi"] = take(arr["ndvi"], mi)
81
+ return f
82
+
83
+
84
+ def clim_fold(ndvi, train_years):
85
+ tm = np.isin(YEARS, train_years)[None, :, None]
86
+ fin = np.isfinite(ndvi)
87
+ s = np.nansum(np.where(tm, ndvi, np.nan), axis=1, keepdims=True)
88
+ n = np.sum(fin & tm, axis=1, keepdims=True).astype("float32")
89
+ own = np.where(fin & tm, ndvi, 0.0)
90
+ with np.errstate(all="ignore"):
91
+ return ((s - own) / (n - (fin & tm))).astype("float32")
92
+
93
+
94
+ def matrix(f: dict, cells: pd.DataFrame, rows: np.ndarray, years: np.ndarray, clim: np.ndarray):
95
+ """Feature matrix for cell positions `rows`, the given years and May-Sep. Returns X, y, meta."""
96
+ yi = np.nonzero(np.isin(YEARS, years))[0]
97
+ sub = lambda a: a[rows][:, yi].reshape(-1) # noqa: E731
98
+ nm = len(MONTHS)
99
+ shape = (len(rows), len(yi), nm)
100
+ cols = {}
101
+ for k in STATIC:
102
+ cols[k] = np.broadcast_to(cells[k].values.astype("float32")[rows][:, None, None], shape).reshape(-1)
103
+ cols["month"] = np.broadcast_to(MONTHS.astype("float32")[None, None, :], shape).reshape(-1)
104
+ cols["clim_ndvi"] = sub(clim)
105
+ for k in WEATHER:
106
+ cols[k] = sub(f[k])
107
+ X = np.column_stack([cols[k] for k in FEATURES]).astype("float32")
108
+ ndvi = sub(f["ndvi"])
109
+ y = ndvi - cols["clim_ndvi"]
110
+ meta = {"row": np.broadcast_to(rows[:, None, None], shape).reshape(-1),
111
+ "year": np.broadcast_to(YEARS[yi][None, :, None], shape).reshape(-1),
112
+ "month": cols["month"].astype("int8"), "ndvi": ndvi}
113
+ return X, y.astype("float32"), meta
114
+
115
+
116
+ class RidgeModel:
117
+ def __init__(self, alpha):
118
+ self.alpha = alpha
119
+
120
+ def fit(self, X, y):
121
+ self.med = np.nanmedian(X, axis=0)
122
+ Z = np.where(np.isnan(X), self.med, X)
123
+ self.mu, self.sd = Z.mean(0), Z.std(0)
124
+ self.sd[self.sd == 0] = 1
125
+ self.r = Ridge(alpha=self.alpha).fit((Z - self.mu) / self.sd, y)
126
+ return self
127
+
128
+ def predict(self, X):
129
+ Z = np.where(np.isnan(X), self.med, X)
130
+ return self.r.predict((Z - self.mu) / self.sd)
131
+
132
+
133
+ def fit_xgb(X, y, params, n_est, seed, Xv=None, yv=None):
134
+ m = xgb.XGBRegressor(**FIXED, **params, n_estimators=n_est, random_state=seed,
135
+ early_stopping_rounds=50 if Xv is not None else None)
136
+ m.fit(X, y, eval_set=[(Xv, yv)] if Xv is not None else None, verbose=False)
137
+ return m
138
+
139
+
140
+ def boot(sse_a, sse_b, rng, n=2000):
141
+ idx = rng.integers(0, len(sse_a), size=(n, len(sse_a)))
142
+ dist = 1 - sse_a[idx].sum(1) / sse_b[idx].sum(1)
143
+ return {"point": float(1 - sse_a.sum() / sse_b.sum()), "ci_lo": float(np.quantile(dist, 0.025)),
144
+ "ci_hi": float(np.quantile(dist, 0.975)), "units": int(len(sse_a))}
145
+
146
+
147
+ def score(y, preds, units, cuts, rng):
148
+ out = {"n_rows": int(len(y))}
149
+ sse = {}
150
+ for k, p in preds.items():
151
+ e = y - p
152
+ t, q = np.digitize(y, cuts), np.digitize(p, cuts)
153
+ out[k] = {"rmse": float(np.sqrt(np.mean(e ** 2))), "mae": float(np.mean(np.abs(e))),
154
+ "anomaly_corr": float(np.corrcoef(y, p)[0, 1]) if np.std(p) > 0 else None,
155
+ "tercile_bacc": float(np.mean([np.mean(q[t == c] == c) for c in range(3) if np.any(t == c)]))}
156
+ sse[k] = pd.Series(e ** 2).groupby(units).sum().values
157
+ out["skill_xgb_vs_ridge"] = boot(sse["xgb"], sse["ridge"], rng)
158
+ out["skill_xgb_vs_clim"] = boot(sse["xgb"], sse["clim"], rng)
159
+ out["skill_ridge_vs_clim"] = boot(sse["ridge"], sse["clim"], rng)
160
+ return out
161
+
162
+
163
+ def finite(X, y, *extra):
164
+ ok = np.isfinite(y)
165
+ return (X[ok], y[ok]) + tuple(e[ok] for e in extra)
166
+
167
+
168
+ def main():
169
+ ap = argparse.ArgumentParser()
170
+ ap.add_argument("--git-commit", required=True)
171
+ a = ap.parse_args()
172
+ RUN.mkdir(parents=True, exist_ok=True)
173
+ rng = np.random.default_rng(0)
174
+ metrics = {"protocol": "configs/model_v2_ca.yaml", "git_commit": a.git_commit, "features": FEATURES}
175
+
176
+ cells_all = pd.read_parquet(CUBE / "cells.parquet")
177
+ elig = cells_all["mask_reason"].isna().values
178
+ cells = cells_all[elig].reset_index(drop=True)
179
+ arr = load_arrays(cells_all, elig)
180
+ f = build_features(cells, arr, RUN)
181
+ del arr
182
+ n = len(cells)
183
+ sample = np.sort(np.random.default_rng(0).choice(n, size=min(N_SAMPLE, n), replace=False))
184
+ sb = ((cells["block_row"].values // 3).astype(np.int64) * 100000 + cells["block_col"].values // 3)
185
+ metrics["data"] = {"eligible_cells": int(n), "sample_cells": int(len(sample)),
186
+ "by_country_eligible": cells["country"].value_counts().astype(int).to_dict()}
187
+ log(f"eligible cells {n}, sample {len(sample)}")
188
+
189
+ # --- tuning on the inner split (sample only)
190
+ c_in = clim_fold(f["ndvi"], np.arange(2001, 2016))
191
+ Xi, yi_ = finite(*matrix(f, cells, sample, np.arange(2001, 2016), c_in)[:2])
192
+ Xv, yv, mv = matrix(f, cells, sample, np.arange(2016, 2020), c_in)
193
+ Xv, yv, mv_month = finite(Xv, yv, mv["month"])
194
+ ridge_rmse = {al: float(np.sqrt(np.mean((yv - RidgeModel(al).fit(Xi, yi_).predict(Xv)) ** 2)))
195
+ for al in [1, 10, 100, 1000, 10000]}
196
+ alpha = min(ridge_rmse, key=ridge_rmse.get)
197
+ import optuna
198
+ optuna.logging.set_verbosity(optuna.logging.WARNING)
199
+
200
+ def objective(tr):
201
+ p = {"max_depth": tr.suggest_int("max_depth", 4, 10),
202
+ "learning_rate": tr.suggest_float("learning_rate", 0.03, 0.2, log=True),
203
+ "min_child_weight": tr.suggest_float("min_child_weight", 1, 200, log=True),
204
+ "subsample": tr.suggest_float("subsample", 0.5, 1.0),
205
+ "colsample_bytree": tr.suggest_float("colsample_bytree", 0.5, 1.0),
206
+ "reg_lambda": tr.suggest_float("reg_lambda", 1e-3, 30, log=True)}
207
+ m = fit_xgb(Xi, yi_, p, 2000, 0, Xv, yv)
208
+ tr.set_user_attr("n_est", int(m.best_iteration) + 1)
209
+ return float(np.sqrt(np.mean((yv - m.predict(Xv)) ** 2)))
210
+
211
+ st = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=0))
212
+ st.optimize(objective, n_trials=20, timeout=600)
213
+ best, n_est = st.best_params, st.best_trial.user_attrs["n_est"]
214
+ metrics["tuning"] = {"trials": len(st.trials), "best_params": best, "n_estimators": n_est,
215
+ "inner_rmse_xgb": st.best_value, "ridge_alpha": alpha, "inner_rmse_ridge": ridge_rmse}
216
+ log(f"tuning {len(st.trials)} trials, xgb {st.best_value:.4f} vs ridge {ridge_rmse[alpha]:.4f}, n_est {n_est}")
217
+ cuts = np.quantile(yi_, [1 / 3, 2 / 3])
218
+ res_in = yv - fit_xgb(Xi, yi_, best, n_est, 0).predict(Xv)
219
+ conf = {int(mo): [float(np.quantile(res_in[mv_month == mo], q)) for q in (0.1, 0.9)] for mo in MONTHS}
220
+ del Xi, yi_, Xv, yv
221
+
222
+ # --- temporal test
223
+ c_t = clim_fold(f["ndvi"], np.arange(2001, 2020))
224
+ Xtr, ytr = finite(*matrix(f, cells, sample, np.arange(2001, 2020), c_t)[:2])
225
+ Xte, yte, mte = matrix(f, cells, sample, np.arange(2020, 2026), c_t)
226
+ Xte, yte, te_year, te_month = finite(Xte, yte, mte["year"], mte["month"])
227
+ ridge = RidgeModel(alpha).fit(Xtr, ytr)
228
+ p_r = ridge.predict(Xte)
229
+ ps, seed_skill = [], []
230
+ for s in SEEDS:
231
+ p = fit_xgb(Xtr, ytr, best, n_est, s).predict(Xte)
232
+ ps.append(p)
233
+ seed_skill.append(float(1 - np.mean((yte - p) ** 2) / np.mean((yte - p_r) ** 2)))
234
+ p_x = np.mean(ps, axis=0)
235
+ temporal = score(yte, {"xgb": p_x, "ridge": p_r, "clim": np.zeros_like(yte)}, te_year, cuts, rng)
236
+ temporal["seed_skill_vs_ridge"] = {"values": seed_skill, "mean": float(np.mean(seed_skill)), "sd": float(np.std(seed_skill))}
237
+ lo = np.array([conf[int(m)][0] for m in te_month]); hi = np.array([conf[int(m)][1] for m in te_month])
238
+ temporal["conformal_coverage_p10_p90"] = float(np.mean(((yte - p_x) >= lo) & ((yte - p_x) <= hi)))
239
+ metrics["temporal_test"] = temporal
240
+ log(f"temporal skill vs ridge {temporal['skill_xgb_vs_ridge']}")
241
+ del Xtr, ytr, Xte, yte
242
+
243
+ # --- spatial test (sample, all years, superblock groups)
244
+ c_all = clim_fold(f["ndvi"], YEARS)
245
+ Xa, ya, ma = matrix(f, cells, sample, YEARS, c_all)
246
+ Xa, ya, rows_a = finite(Xa, ya, ma["row"])
247
+ groups = sb[rows_a]
248
+ preds = {"xgb": np.zeros_like(ya), "ridge": np.zeros_like(ya)}
249
+ for itr, ite in GroupKFold(5).split(Xa, groups=groups):
250
+ preds["xgb"][ite] = fit_xgb(Xa[itr], ya[itr], best, n_est, 0).predict(Xa[ite])
251
+ preds["ridge"][ite] = RidgeModel(alpha).fit(Xa[itr], ya[itr]).predict(Xa[ite])
252
+ preds["clim"] = np.zeros_like(ya)
253
+ spatial = score(ya, preds, groups, cuts, rng)
254
+ metrics["spatial_test"] = spatial
255
+ log(f"spatial skill vs ridge {spatial['skill_xgb_vs_ridge']}")
256
+
257
+ passed = temporal["skill_xgb_vs_ridge"]["ci_lo"] > 0 and spatial["skill_xgb_vs_ridge"]["ci_lo"] > 0
258
+ chosen = "xgb" if passed else "ridge"
259
+ metrics["gate"] = {"rule": "CI lower bound of skill_xgb_vs_ridge > 0 on temporal AND spatial tests",
260
+ "passed": bool(passed), "shipped_model": chosen}
261
+ log(f"GATE passed={passed} -> {chosen}")
262
+
263
+ # --- production model (sample, all years) + importance
264
+ prod = fit_xgb(Xa, ya, best, n_est, 0) if chosen == "xgb" else RidgeModel(alpha).fit(Xa, ya)
265
+ if chosen == "xgb":
266
+ booster = prod.get_booster()
267
+ booster.feature_names = FEATURES
268
+ booster.save_model(RUN / "model_ca.ubj")
269
+ sel = np.random.default_rng(1).choice(len(Xa), size=min(200_000, len(Xa)), replace=False)
270
+ contrib = booster.predict(xgb.DMatrix(Xa[sel], feature_names=FEATURES), pred_contribs=True)
271
+ metrics["feature_importance_mean_abs"] = dict(sorted(zip(FEATURES, np.abs(contrib[:, :-1]).mean(0).round(6).tolist()),
272
+ key=lambda kv: -kv[1]))
273
+ del Xa, ya
274
+
275
+ # --- out-of-fold for ALL eligible cells (5 year blocks), residual vs all-years climatology
276
+ clim_all = np.nanmean(f["ndvi"], axis=1, keepdims=True) # (n, 1, 5)
277
+ summer_res = np.full((n, len(YEARS)), np.nan, "float32")
278
+ bcode, buniq = pd.factorize(cells["block_id"])
279
+ nb = len(buniq)
280
+ acc = {k: np.zeros((nb, len(YEARS), len(MONTHS))) for k in ("observed", "expected", "residual", "n")}
281
+ all_rows = np.arange(n)
282
+ summer_idx = [list(MONTHS).index(m) for m in (6, 7, 8)]
283
+ for blk in [np.arange(s, s + 5) for s in (2001, 2006, 2011, 2016, 2021)]:
284
+ trn = np.setdiff1d(YEARS, blk)
285
+ cf = clim_fold(f["ndvi"], trn)
286
+ Xs, ys = finite(*matrix(f, cells, sample, trn, cf)[:2])
287
+ model = fit_xgb(Xs, ys, best, n_est, 0) if chosen == "xgb" else RidgeModel(alpha).fit(Xs, ys)
288
+ del Xs, ys
289
+ for chunk in np.array_split(all_rows, 10):
290
+ X, _, meta = matrix(f, cells, chunk, blk, cf)
291
+ pa_ = model.predict(X).astype("float32").reshape(len(chunk), len(blk), len(MONTHS))
292
+ yi = np.nonzero(np.isin(YEARS, blk))[0]
293
+ expected = clim_all[chunk] + pa_
294
+ obs = f["ndvi"][chunk][:, yi]
295
+ res = obs - expected
296
+ with np.errstate(all="ignore"):
297
+ summer_res[chunk[:, None], yi[None, :]] = np.nanmean(res[:, :, summer_idx], axis=2)
298
+ bc = bcode[chunk]
299
+ for j, yy in enumerate(yi):
300
+ for k in range(len(MONTHS)):
301
+ v = np.isfinite(res[:, j, k])
302
+ acc["n"][:, yy, k] += np.bincount(bc[v], minlength=nb)
303
+ for name, val in (("observed", obs), ("expected", expected), ("residual", res)):
304
+ acc[name][:, yy, k] += np.bincount(bc[v], weights=val[v, j, k], minlength=nb)
305
+ log(f"oof block {blk[0]}-{blk[-1]} done")
306
+ np.save(RUN / "summer_residual.npy", summer_res)
307
+ cells[["cell_id", "block_id", "region", "country"]].to_parquet(RUN / "eligible_cells.parquet", index=False)
308
+ B, Y, M = np.meshgrid(np.arange(nb), YEARS, MONTHS, indexing="ij")
309
+ with np.errstate(all="ignore"):
310
+ eb = pd.DataFrame({"block_id": np.asarray(buniq)[B.ravel()], "year": Y.ravel(), "month": M.ravel(),
311
+ "observed": (acc["observed"] / acc["n"]).ravel(), "expected": (acc["expected"] / acc["n"]).ravel(),
312
+ "residual": (acc["residual"] / acc["n"]).ravel(), "n_cells": acc["n"].ravel().astype(int)})
313
+ eb = eb[eb["n_cells"] > 0].reset_index(drop=True)
314
+ eb["p10"] = eb["expected"] + eb["month"].map(lambda m: conf[int(m)][0])
315
+ eb["p90"] = eb["expected"] + eb["month"].map(lambda m: conf[int(m)][1])
316
+ eb.to_parquet(RUN / "expected_block.parquet", index=False)
317
+
318
+ pd.concat([pd.DataFrame({"cell_id": cells["cell_id"].values, "month": int(mo),
319
+ "clim_ndvi": clim_all[:, 0, j]}) for j, mo in enumerate(MONTHS)]) \
320
+ .to_parquet(RUN / "climatology.parquet", index=False)
321
+ (RUN / "feature_schema.json").write_text(json.dumps({"features": FEATURES, "static": STATIC, "weather": WEATHER,
322
+ "months": MONTHS.tolist(), "shipped_model": chosen,
323
+ "target": "ndvi_anomaly = ndvi - clim_ndvi"}, indent=2))
324
+ (RUN / "conformal.json").write_text(json.dumps(conf, indent=2))
325
+ (RUN / "metrics.json").write_text(json.dumps(metrics, indent=2, default=float))
326
+ log("TRAIN_CA_DONE")
327
+
328
+
329
+ if __name__ == "__main__":
330
+ main()
_backup/scripts/40_products_ca.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CA products from runs/v2_ca (summer residuals of every eligible cell) -> runs/v2_ca/products.
2
+
3
+ residual_trend.parquet (cell), residual_trend_{block,region,country}.parquet, season_vs_expected_block.parquet,
4
+ expected_block.parquet (copied), products_summary.json. Placebo on a 200k-cell subsample.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import shutil
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+
17
+ sys.path.insert(0, "/root/trendex-ca/src")
18
+ from trendex_ml.stats.trend import bh_fdr, classify, mk_vectorized, trend_many # noqa: E402
19
+
20
+ RUN = Path("/root/trendex-ca/runs/v2_ca")
21
+ OUT = RUN / "products"
22
+ YEARS = np.arange(2001, 2026)
23
+ ALPHA, MIN_YEARS = 0.05, 18
24
+
25
+
26
+ def log(m):
27
+ print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
28
+
29
+
30
+ def trend_table(W: np.ndarray, keys, name: str) -> pd.DataFrame:
31
+ r = trend_many(W, YEARS.astype(float), method="hamed_rao", min_n=MIN_YEARS, n_jobs=40, chunk=5000)
32
+ df = pd.DataFrame(r)
33
+ df.insert(0, name, keys)
34
+ df["q"] = bh_fdr(df["p"].values)
35
+ df["class"] = classify(df["slope"].values, df["q"].values, df["n"].values, ALPHA, MIN_YEARS)
36
+ df["slope_per_decade"] = df["slope"] * 10
37
+ return df
38
+
39
+
40
+ def group_mean(W: np.ndarray, labels: pd.Series):
41
+ codes, uniq = pd.factorize(labels)
42
+ ok = codes >= 0
43
+ sums = np.zeros((len(uniq), W.shape[1]))
44
+ cnt = np.zeros((len(uniq), W.shape[1]))
45
+ for j in range(W.shape[1]):
46
+ v = ok & np.isfinite(W[:, j])
47
+ sums[:, j] = np.bincount(codes[v], weights=W[v, j], minlength=len(uniq))
48
+ cnt[:, j] = np.bincount(codes[v], minlength=len(uniq))
49
+ with np.errstate(all="ignore"):
50
+ return np.asarray(uniq), (sums / cnt).astype("float32")
51
+
52
+
53
+ def main():
54
+ OUT.mkdir(parents=True, exist_ok=True)
55
+ W = np.load(RUN / "summer_residual.npy")
56
+ cells = pd.read_parquet(RUN / "eligible_cells.parquet")
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}")
63
+ agg = {}
64
+ for col in ("block_id", "region", "country"):
65
+ keys, Wg = group_mean(W, cells[col])
66
+ t = trend_table(Wg, keys, col)
67
+ t.to_parquet(OUT / f"residual_trend_{col.replace('_id', '')}.parquet", index=False)
68
+ agg[col] = t
69
+ by_country = rt.merge(cells[["cell_id", "country"]], on="cell_id").groupby("country")["class"] \
70
+ .value_counts(normalize=True).round(4).unstack(fill_value=0).to_dict(orient="index")
71
+
72
+ rng = np.random.default_rng(0)
73
+ sub = W[rng.choice(len(W), size=min(200_000, len(W)), replace=False)]
74
+ raw, fdr = [], []
75
+ for _ in range(200):
76
+ perm = np.argsort(rng.random(sub.shape), axis=1)
77
+ _, _, _, p = mk_vectorized(np.take_along_axis(sub, perm, axis=1))
78
+ raw.append(float(np.nanmean(p < ALPHA)))
79
+ fdr.append(float(np.nanmean(bh_fdr(p) < ALPHA)))
80
+ _, _, _, p_obs = mk_vectorized(sub)
81
+ placebo = {"cells": int(len(sub)), "permutations": 200, "test": "original MK on the same subsample",
82
+ "observed_share_p<0.05": float(np.nanmean(p_obs < ALPHA)), "observed_share_q<0.05": float(np.nanmean(bh_fdr(p_obs) < ALPHA)),
83
+ "placebo_share_p<0.05_mean": float(np.mean(raw)), "placebo_share_q<0.05_mean": float(np.mean(fdr)),
84
+ "placebo_share_q<0.05_p95": float(np.quantile(fdr, 0.95))}
85
+ log(f"placebo {placebo}")
86
+
87
+ keys, Wb = group_mean(W, cells["block_id"])
88
+ sb = pd.DataFrame({"block_id": np.repeat(keys, len(YEARS)), "year": np.tile(YEARS, len(keys)),
89
+ "summer_residual": Wb.ravel()}).dropna()
90
+ q10, q90 = sb["summer_residual"].quantile([0.1, 0.9])
91
+ sb["season_class"] = np.select([sb["summer_residual"] < q10, sb["summer_residual"] > q90], ["below", "above"], "within")
92
+ sb.to_parquet(OUT / "season_vs_expected_block.parquet", index=False)
93
+ shutil.copy(RUN / "expected_block.parquet", OUT / "expected_block.parquet")
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"),
100
+ "season_band_block_summer_residual_q10_q90": [float(q10), float(q90)], "placebo": placebo,
101
+ "wording": "change not explained by precipitation, air temperature, snow and soil moisture (not a cause)"}
102
+ (OUT / "products_summary.json").write_text(json.dumps(summary, indent=2, default=float))
103
+ log("PRODUCTS_CA_DONE")
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
_backup/scripts/45_package_ca.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Package v2-ca for HF (runs/v2_ca/hf_model) + what-if grid by region and country (runs/v2_ca/products/scenarios).
2
+
3
+ Golden test: 100 rows rebuilt with the training code; predict_ca.py must reproduce the training model exactly.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import importlib.util
8
+ import json
9
+ import shutil
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+ import xgboost as xgb
16
+
17
+ ROOT = Path("/root/trendex-ca")
18
+ RUN = ROOT / "runs" / "v2_ca"
19
+ HF = RUN / "hf_model"
20
+ MONTHS, PRECIP, TEMP = [5, 6, 7, 8, 9], [-30, -20, -10, 0, 10, 20, 30], [-2, -1, 0, 1, 2]
21
+
22
+
23
+ def load_module(path, name):
24
+ spec = importlib.util.spec_from_file_location(name, path)
25
+ mod = importlib.util.module_from_spec(spec)
26
+ sys.modules[name] = mod
27
+ spec.loader.exec_module(mod)
28
+ return mod
29
+
30
+
31
+ def main():
32
+ HF.mkdir(parents=True, exist_ok=True)
33
+ for f in ["model_ca.ubj", "feature_schema.json", "climatology.parquet", "weather_climatology.parquet",
34
+ "conformal.json", "metrics.json"]:
35
+ shutil.copy(RUN / f, HF / f)
36
+ shutil.copy(ROOT / "scripts" / "predict_ca.py", HF / "predict_ca.py")
37
+ shutil.copy(ROOT / "configs" / "model_v2_ca.yaml", HF / "model_v2_ca.yaml")
38
+
39
+ tr = load_module(ROOT / "scripts" / "30_train_ca.py", "train_ca")
40
+ cells = pd.read_parquet(tr.CUBE / "cells.parquet")
41
+ cells_e = cells[cells["mask_reason"].isna()].reset_index(drop=True)
42
+ pm = load_module(HF / "predict_ca.py", "predict_ca")
43
+ model = pm.load(HF)
44
+
45
+ # golden: features for 100 random eligible cells in 2024 July via what_if inputs at zero deltas is too
46
+ # synthetic, so rebuild real rows from the cube for 300 cells and keep 100 finite ones
47
+ rng = np.random.default_rng(0)
48
+ pick = np.sort(rng.choice(len(cells_e), size=300, replace=False))
49
+ elig = cells["mask_reason"].isna().values
50
+ sub_mask = np.zeros(len(cells), bool)
51
+ sub_mask[np.nonzero(elig)[0][pick]] = True
52
+ arr = tr.load_arrays(cells, sub_mask)
53
+ tmp = RUN / "_golden_tmp"
54
+ tmp.mkdir(exist_ok=True)
55
+ f = tr.build_features(cells_e.iloc[pick].reset_index(drop=True), arr, tmp)
56
+ clim = tr.clim_fold(f["ndvi"], tr.YEARS)
57
+ X, y, meta = tr.matrix(f, cells_e.iloc[pick].reset_index(drop=True), np.arange(len(pick)), np.array([2024]), clim)
58
+ ok = np.isfinite(y)
59
+ gin = pd.DataFrame(X[ok][:100], columns=tr.FEATURES)
60
+ (HF / "golden").mkdir(exist_ok=True)
61
+ gin.to_parquet(HF / "golden" / "inputs.parquet", index=False)
62
+ out = model.predict(gin)
63
+ out.to_parquet(HF / "golden" / "expected.parquet", index=False)
64
+ ref = xgb.XGBRegressor()
65
+ ref.load_model(RUN / "model_ca.ubj")
66
+ diff = float(np.max(np.abs(ref.predict(gin[tr.FEATURES].to_numpy("float32")) - out["pred_anom"].to_numpy())))
67
+ print(f"golden max diff {diff:.2e}")
68
+ assert diff < 1e-5
69
+ shutil.rmtree(tmp)
70
+
71
+ # what-if grid: up to 2,000 random eligible cells per region, aggregated to region and country
72
+ samp = cells_e.groupby("region", dropna=False, group_keys=False).apply(
73
+ lambda g: g.sample(min(len(g), 2000), random_state=0))
74
+ rows = []
75
+ for mo in MONTHS:
76
+ for p in PRECIP:
77
+ for t in TEMP:
78
+ r = model.what_if(cells, samp["cell_id"].to_numpy(), month=mo, precip_pct=p, temp_c=t)
79
+ rows.append(pd.DataFrame({"region": samp["region"].to_numpy(), "country": samp["country"].to_numpy(),
80
+ "month": mo, "p": p, "t": t, "typical": r["expected_typical_weather"].to_numpy(),
81
+ "change": r["change_vs_typical"].to_numpy()}))
82
+ W = pd.concat(rows, ignore_index=True)
83
+
84
+ def nested(df):
85
+ g = df.groupby(["month", "p", "t"])["change"].mean()
86
+ typ = df[(df["p"] == 0) & (df["t"] == 0)].groupby("month")["typical"].mean()
87
+ return {"n_cells_sampled": int(len(df) // (len(MONTHS) * len(PRECIP) * len(TEMP))),
88
+ "typical": [round(float(typ[m]), 4) for m in MONTHS],
89
+ "change": [[[round(float(g[(m, p, t)]), 4) for t in TEMP] for p in PRECIP] for m in MONTHS]}
90
+
91
+ js = {"model": "TrendeX90/expected-greenness-ca@v2-ca", "units": "NDVI", "months": MONTHS, "precip_pct": PRECIP,
92
+ "temp_c": TEMP, "layout": "change[month][precip][temp]; expected = typical[month] + change",
93
+ "meaning": "Expected greenness change vs typical weather if precipitation and GLDAS air temperature differ by "
94
+ "the given amounts. Model sensitivity, not a causal effect; averages over up to 2,000 sampled "
95
+ "pasture cells per region.",
96
+ "all": nested(W), "countries": {c: nested(g) for c, g in W.groupby("country")},
97
+ "regions": {r: nested(g) for r, g in W.groupby("region")}}
98
+ sc = RUN / "products" / "scenarios"
99
+ sc.mkdir(parents=True, exist_ok=True)
100
+ (sc / "what_if.json").write_text(json.dumps(js, separators=(",", ":")))
101
+ print(f"what_if.json {(sc / 'what_if.json').stat().st_size / 1e3:.0f} kB; July all: typical {js['all']['typical'][2]}, "
102
+ f"-30% {js['all']['change'][2][0][2]}, +2C {js['all']['change'][2][3][4]}")
103
+
104
+ m = json.loads((RUN / "metrics.json").read_text())
105
+ t, s = m["temporal_test"], m["spatial_test"]
106
+ fmt = lambda d: f"{d['point']:.3f} (95% CI {d['ci_lo']:.3f} to {d['ci_hi']:.3f}, {d['units']} units)" # noqa: E731
107
+ (HF / "README.md").write_text(f"""---
108
+ license: other
109
+ library_name: xgboost
110
+ tags: [nasa, modis, ndvi, imerg, gldas, pastures, central-asia, tabular-regression]
111
+ datasets: [TrendeX90/ca-cube]
112
+ ---
113
+ # TrendeX expected greenness, Central Asia (v2-ca)
114
+
115
+ Summer (May-Sep) NDVI anomaly of 1 km pasture cells in Kazakhstan, Kyrgyzstan, Tajikistan, Turkmenistan and
116
+ Uzbekistan, predicted from weather (IMERG precipitation; GLDAS air temperature, soil moisture, snow) and terrain
117
+ only. The gap to observed NDVI is change **not explained by weather**: not a cause, not forage quality.
118
+ Protocol locked in git before fitting (`model_v2_ca.yaml`, commit {m['git_commit']}). Naryn pilot model: TrendeX90/expected-greenness (v1).
119
+
120
+ | Test | RMSE xgb | RMSE ridge | RMSE climatology | anomaly corr xgb |
121
+ |---|---|---|---|---|
122
+ | Temporal (2020-2025) | {t['xgb']['rmse']:.4f} | {t['ridge']['rmse']:.4f} | {t['clim']['rmse']:.4f} | {t['xgb']['anomaly_corr']:.3f} |
123
+ | Spatial (unseen super-blocks) | {s['xgb']['rmse']:.4f} | {s['ridge']['rmse']:.4f} | {s['clim']['rmse']:.4f} | {s['xgb']['anomaly_corr']:.3f} |
124
+
125
+ - Skill vs ridge: temporal {fmt(t['skill_xgb_vs_ridge'])}; spatial {fmt(s['skill_xgb_vs_ridge'])}.
126
+ - Skill vs climatology: temporal {fmt(t['skill_xgb_vs_clim'])}.
127
+ - Seeds ({len(t['seed_skill_vs_ridge']['values'])}): {t['seed_skill_vs_ridge']['mean']:.3f} +/- {t['seed_skill_vs_ridge']['sd']:.3f}.
128
+ - **Gate (pre-registered, CI lower bound > 0 on both tests): passed = {m['gate']['passed']}; shipped = {m['gate']['shipped_model']}.**
129
+ - P10-P90 coverage on 2020-2025: {t['conformal_coverage_p10_p90']:.0%} (nominal 80%).
130
+
131
+ Limits: trained on {m['data']['sample_cells']:,} sampled cells (of {m['data']['eligible_cells']:,} eligible) because of budget; GLDAS
132
+ (0.25 deg) is coarse; MCD12Q1 2020 mask; NDVI is greenness, not forage; no field validation; budget-limited tuning
133
+ (20 trials) and 3 seeds. Spatial test shares years with training and is easier than the temporal test.
134
+
135
+ ```python
136
+ from predict_ca import load # numpy, pandas, xgboost; CPU
137
+ m = load(".")
138
+ m.predict(features_df) # columns as in feature_schema.json
139
+ ```
140
+ Data: MOD13A3.061, MCD12Q1.061, NASADEM_HGT.001 (LP DAAC), GPM_3IMERGM.07, GLDAS_NOAH025_M.2.1 (GES DISC).
141
+ AI use: implementation assisted by Claude (Anthropic).
142
+ """)
143
+ print("PACKAGE_CA_DONE", sorted(p.name for p in HF.iterdir()))
144
+
145
+
146
+ if __name__ == "__main__":
147
+ main()
_backup/scripts/50_push_ca.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Push Central Asia outputs to HF.
2
+
3
+ python scripts/50_push_ca.py cube # cells.parquet, monthly/, manifest.json, aoi -> TrendeX90/ca-cube
4
+ python scripts/50_push_ca.py formula # backend outputs -> TrendeX90/ca-cube/formula/
5
+ python scripts/50_push_ca.py products # runs/v2_ca/products -> TrendeX90/ca-cube/products/
6
+ python scripts/50_push_ca.py model # runs/v2_ca/hf_model -> TrendeX90/expected-greenness-ca (tag v2-ca)
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ from pathlib import Path
13
+
14
+ from huggingface_hub import HfApi
15
+
16
+ ROOT = Path("/root/trendex-ca")
17
+ CUBE, RUN, BACKEND = ROOT / "data" / "cube", ROOT / "runs" / "v2_ca", Path("/root/trendex/backend")
18
+ CUBE_REPO, MODEL_REPO = "TrendeX90/ca-cube", "TrendeX90/expected-greenness-ca"
19
+
20
+
21
+ def card(manifest: dict) -> str:
22
+ status = "PARTIAL - NDVI only" if manifest.get("partial") else "full"
23
+ units = "\n".join(f"- `{k}`: {v}" for k, v in manifest.get("units", {}).items())
24
+ data = "\n".join(f"- {k} v{v}" for k, v in manifest.get("datasets", {}).items())
25
+ notes = "\n".join(f"- {n}" for n in manifest.get("notes", []))
26
+ cells = manifest.get("cells", {})
27
+ return f"""---
28
+ license: other
29
+ pretty_name: TrendeX Central Asia cube
30
+ tags: [nasa, modis, ndvi, imerg, gldas, central-asia, pastures]
31
+ ---
32
+ # TrendeX Central Asia cube ({status})
33
+
34
+ Kazakhstan, Kyrgyzstan, Tajikistan, Turkmenistan, Uzbekistan on the global MODIS sinusoidal 1 km grid
35
+ ({cells.get('n', '?'):,} cells). Same layout as TrendeX90/naryn-cube; **synthetic = false**.
36
+
37
+ - `cells.parquet`: cell_id, row, col, x, y, lon, lat, country (ISO3), region (ADM1 shapeName), block_id / block_row / block_col,
38
+ terrain (NASADEM 30 m -> 1 km), land cover (MCD12Q1 2020) and fractions, mask_reason.
39
+ - `monthly/year=YYYY/part.parquet`: Apr-Oct rows, `pd.read_parquet("monthly/")`.
40
+ - `products/`, `formula/`: model and formula outputs (when present).
41
+
42
+ ## Units
43
+ {units}
44
+
45
+ ## Data
46
+ {data}
47
+
48
+ ## Notes
49
+ {notes}
50
+ """
51
+
52
+
53
+ def main():
54
+ ap = argparse.ArgumentParser()
55
+ ap.add_argument("what", choices=["cube", "formula", "products", "model"])
56
+ a = ap.parse_args()
57
+ api = HfApi()
58
+ if a.what == "cube":
59
+ m = json.loads((CUBE / "manifest.json").read_text())
60
+ (CUBE / "README.md").write_text(card(m))
61
+ api.upload_folder(repo_id=CUBE_REPO, repo_type="dataset", folder_path=str(CUBE),
62
+ allow_patterns=["cells.parquet", "manifest.json", "README.md", "monthly/**"],
63
+ commit_message=f"Central Asia cube ({'partial' if m.get('partial') else 'full'})")
64
+ api.upload_folder(repo_id=CUBE_REPO, repo_type="dataset", folder_path=str(ROOT / "data" / "aoi"),
65
+ path_in_repo="aoi", allow_patterns=["aoi_request.geojson", "aoi_summary.json"],
66
+ commit_message="area of interest")
67
+ elif a.what == "formula":
68
+ for local, remote in ((BACKEND / "export" / "ca" / "v1" / "fe", "formula/export/ca/v1/fe"),
69
+ (BACKEND / "export_ca" / "v1", "formula/export_ca/v1"),
70
+ (BACKEND / "artifacts_ca", "formula/artifacts_ca")):
71
+ if local.exists():
72
+ api.upload_folder(repo_id=CUBE_REPO, repo_type="dataset", folder_path=str(local), path_in_repo=remote,
73
+ ignore_patterns=["*.npy", "*.npz"], commit_message=f"formula outputs: {remote}")
74
+ print("pushed", remote, flush=True)
75
+ else:
76
+ print("missing", local, flush=True)
77
+ elif a.what == "products":
78
+ api.upload_folder(repo_id=CUBE_REPO, repo_type="dataset", folder_path=str(RUN / "products"),
79
+ path_in_repo="products", commit_message="model v2-ca products")
80
+ else:
81
+ if not api.repo_exists(MODEL_REPO):
82
+ api.create_repo(MODEL_REPO, private=False)
83
+ api.upload_folder(repo_id=MODEL_REPO, folder_path=str(RUN / "hf_model"),
84
+ ignore_patterns=["__pycache__/*", "*.pyc", ".pytest_cache/*"], commit_message="expected greenness v2-ca")
85
+ if "v2-ca" not in [t.name for t in api.list_repo_refs(MODEL_REPO).tags]:
86
+ api.create_tag(MODEL_REPO, tag="v2-ca", tag_message="protocol model_v2_ca")
87
+ print(f"PUSHED_{a.what.upper()}", flush=True)
88
+
89
+
90
+ if __name__ == "__main__":
91
+ main()
_backup/scripts/backup_loop.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Every 10 minutes, mirror logs, code, protocol and finished run outputs to HF (TrendeX90/ca-cube/_backup/),
2
+ so nothing is lost if the Vast machine stops. Unchanged files are skipped by the hub (no empty commits).
3
+
4
+ setsid nohup python scripts/backup_loop.py > logs/backup.log 2>&1 &
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ import traceback
10
+ from pathlib import Path
11
+
12
+ from huggingface_hub import HfApi
13
+
14
+ ROOT = Path("/root/trendex-ca")
15
+ REPO = "TrendeX90/ca-cube"
16
+ ITEMS = [
17
+ (ROOT / "logs", "_backup/logs", ["*.log"]),
18
+ (ROOT / "scripts", "_backup/scripts", ["*.py", "*.sh"]),
19
+ (ROOT / "configs", "_backup/configs", ["*.yaml"]),
20
+ (ROOT / "runs" / "v2_ca", "_backup/runs_v2_ca", ["*.json", "*.ubj", "*.parquet", "*.npy", "products/**", "hf_model/**"]),
21
+ (ROOT / "data" / "aoi", "_backup/aoi", ["*.json", "aoi_request.geojson"]),
22
+ ]
23
+
24
+
25
+ def main() -> None:
26
+ api = HfApi()
27
+ while True:
28
+ for folder, dest, patterns in ITEMS:
29
+ if not folder.exists():
30
+ continue
31
+ try:
32
+ api.upload_folder(repo_id=REPO, repo_type="dataset", folder_path=str(folder), path_in_repo=dest,
33
+ allow_patterns=patterns, ignore_patterns=["__pycache__/*", "*.pyc", "_golden_tmp/*"],
34
+ commit_message=f"backup {dest} {time.strftime('%H:%M:%S')}")
35
+ print(time.strftime("%H:%M:%S"), "synced", dest, flush=True)
36
+ except Exception:
37
+ print(time.strftime("%H:%M:%S"), "sync failed", dest, traceback.format_exc(limit=1), flush=True)
38
+ time.sleep(600)
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()
_backup/scripts/predict_ca.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TrendeX expected greenness, Central Asia (v2-ca): CPU inference. Imports only numpy, pandas, xgboost.
2
+
3
+ Files next to this module: model_ca.ubj, feature_schema.json, climatology.parquet (cell_id, month, clim_ndvi),
4
+ weather_climatology.parquet (cell_id, month, <feature>_mean), conformal.json.
5
+
6
+ from predict_ca import load
7
+ m = load("path/to/repo")
8
+ m.predict(df) # df has feature_schema.json columns
9
+ m.what_if(cells, cell_ids, month=7, precip_pct=-30, temp_c=1) # cells = ca-cube cells.parquet rows
10
+
11
+ Expected greenness from weather and terrain alone; the gap to observed NDVI is change NOT explained by
12
+ precipitation, air temperature, snow and soil moisture. Not a cause, not forage quality.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ import xgboost as xgb
22
+
23
+
24
+ class ExpectedGreennessCA:
25
+ def __init__(self, root):
26
+ root = Path(root)
27
+ s = json.loads((root / "feature_schema.json").read_text())
28
+ self.features, self.static, self.weather = s["features"], s["static"], s["weather"]
29
+ self.booster = xgb.Booster()
30
+ self.booster.load_model(str(root / "model_ca.ubj"))
31
+ self.booster.set_param({"device": "cpu"})
32
+ self.clim = pd.read_parquet(root / "climatology.parquet").set_index(["cell_id", "month"])
33
+ self.wclim = pd.read_parquet(root / "weather_climatology.parquet").set_index(["cell_id", "month"])
34
+ self.conf = {int(k): v for k, v in json.loads((root / "conformal.json").read_text()).items()}
35
+
36
+ def predict(self, df: pd.DataFrame) -> pd.DataFrame:
37
+ missing = [c for c in self.features if c not in df.columns]
38
+ if missing:
39
+ raise ValueError(f"missing features: {missing}")
40
+ X = df[self.features].to_numpy(dtype="float32")
41
+ pred = self.booster.predict(xgb.DMatrix(X, feature_names=self.features))
42
+ months = df["month"].astype(int).to_numpy()
43
+ lo = np.array([self.conf[m][0] for m in months])
44
+ hi = np.array([self.conf[m][1] for m in months])
45
+ exp = df["clim_ndvi"].to_numpy() + pred
46
+ return pd.DataFrame({"pred_anom": pred, "expected": exp, "p10": exp + lo, "p90": exp + hi}, index=df.index)
47
+
48
+ def what_if(self, cells: pd.DataFrame, cell_ids, month: int, precip_pct: float = 0.0, temp_c: float = 0.0,
49
+ soil_pct: float = 0.0) -> pd.DataFrame:
50
+ ids = np.asarray(cell_ids)
51
+ key = pd.MultiIndex.from_arrays([ids, np.full(len(ids), int(month))])
52
+ w = self.wclim.reindex(key)
53
+ st = cells.set_index("cell_id").reindex(ids)
54
+
55
+ def frame(pp, tc, sp):
56
+ f = pd.DataFrame({k: st[k].to_numpy() for k in self.static})
57
+ f["month"] = float(month)
58
+ f["clim_ndvi"] = self.clim["clim_ndvi"].reindex(key).to_numpy()
59
+ for k in ("precip_m", "precip_2m", "precip_winter"):
60
+ f[k] = w[f"{k}_mean"].to_numpy() * pp / 100.0
61
+ f["tair_m"] = f["tair_prev"] = tc
62
+ f["soil_m"] = w["soil_m_mean"].to_numpy() * sp / 100.0
63
+ f["swe_apr"] = 0.0
64
+ return f
65
+
66
+ res = self.predict(frame(precip_pct, temp_c, soil_pct))
67
+ base = self.predict(frame(0.0, 0.0, 0.0))
68
+ res.insert(0, "cell_id", ids)
69
+ res["expected_typical_weather"] = base["expected"].to_numpy()
70
+ res["change_vs_typical"] = res["expected"].to_numpy() - base["expected"].to_numpy()
71
+ return res
72
+
73
+
74
+ def load(root=Path(__file__).parent) -> ExpectedGreennessCA:
75
+ return ExpectedGreennessCA(root)
_backup/scripts/restart_formula.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Stop a running formula job (runner + python pipeline), then start it again on the latest backend commit.
3
+ me=$$
4
+ for pid in $(pgrep -f "scripts/run_formula.sh") $(pgrep -f "pipeline.build"); do
5
+ [ "$pid" = "$me" ] && continue
6
+ kill "$pid" 2>/dev/null && echo "killed $pid"
7
+ done
8
+ sleep 3
9
+ pgrep -fa "pipeline.build" | grep -v restart_formula || echo "formula stopped"
10
+ cd /root/trendex-ca
11
+ [ -f logs/formula.log ] && mv logs/formula.log "logs/formula_$(date +%H%M%S).log"
12
+ setsid nohup bash scripts/run_formula.sh < /dev/null > logs/formula.log 2>&1 &
13
+ sleep 15
14
+ head -3 logs/formula.log
_backup/scripts/run_formula.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run the backend formula (github.com/Konuktor/trendex, core_ca.yaml) on a frozen hard-link snapshot of the CA cube,
3
+ # so the weather stage can swap monthly/ underneath without disturbing it. Then push formula outputs to HF.
4
+ set -euo pipefail
5
+ SNAP=/root/trendex-ca/data/cube_formula
6
+ rm -rf "$SNAP" && mkdir -p "$SNAP"
7
+ cp -al /root/trendex-ca/data/cube/monthly "$SNAP/monthly"
8
+ cp /root/trendex-ca/data/cube/cells.parquet /root/trendex-ca/data/cube/manifest.json "$SNAP/"
9
+ cd /root/trendex && git pull -q && git log --oneline -1
10
+ cd backend
11
+ export TRENDEX_CONFIG=core_ca.yaml
12
+ echo "FORMULA_BUILD_START $(date -u +%T)"
13
+ .venv/bin/python -m pipeline.build --cube "$SNAP" --out artifacts_ca --clean --jobs 20
14
+ echo "FORMULA_EXPORT_START $(date -u +%T)"
15
+ TRENDEX_ARTIFACTS=artifacts_ca TRENDEX_EXPORT=export_ca/v1 .venv/bin/python scripts/30_export_static.py
16
+ TRENDEX_ARTIFACTS=artifacts_ca .venv/bin/python scripts/35_export_frontend.py
17
+ du -sh artifacts_ca export_ca/v1 export/ca/v1/fe || true
18
+ python /root/trendex-ca/scripts/50_push_ca.py formula
19
+ echo "FORMULA_DONE $(date -u +%T)"
_backup/scripts/setup_box.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # One-time environment setup on the Vast box (CUDA 12 PyTorch image, /opt/conda Python 3.11).
3
+ set -euo pipefail
4
+ echo "SETUP_START $(date -u +%FT%TZ)"
5
+ python -m pip install -q --upgrade pip
6
+ python -m pip install -q \
7
+ rasterio rioxarray xarray h5netcdf netCDF4 h5py \
8
+ geopandas shapely pyproj pyarrow polars pandas requests tqdm \
9
+ earthaccess xgboost lightgbm scikit-learn optuna shap \
10
+ pymannkendall statsmodels huggingface_hub pytest
11
+ python -m pip freeze > /root/requirements.lock
12
+ python - <<'PY'
13
+ import numpy as np, rasterio, xarray, geopandas, earthaccess, xgboost, lightgbm, sklearn
14
+ import optuna, shap, pymannkendall, statsmodels, huggingface_hub, h5py, netCDF4, polars
15
+ print("rasterio", rasterio.__version__, "| GDAL", rasterio.__gdal_version__)
16
+ print("xgboost", xgboost.__version__, "| lightgbm", lightgbm.__version__, "| earthaccess", earthaccess.__version__)
17
+ from xgboost import XGBRegressor
18
+ X = np.random.rand(2000, 5); y = X.sum(1)
19
+ XGBRegressor(n_estimators=20, tree_method="hist", device="cuda").fit(X, y)
20
+ print("XGBOOST_CUDA_OK")
21
+ PY
22
+ echo "SETUP_DONE $(date -u +%FT%TZ)"