ca-cube / _backup /scripts /20_build_cube_ca.py
Konuktor92's picture
backup _backup/scripts 17:44:23
a5899e5 verified
Raw History Blame Contribute Delete
18.8 kB
"""Central Asia cube (same schema family as naryn-cube), built for ~4.6M cells.
python ca/20_build_cube_ca.py --stage ndvi # cells.parquet + monthly NDVI (Apr-Oct), manifest partial=true
python ca/20_build_cube_ca.py --stage weather # adds IMERG + GLDAS columns to monthly, partial=false
Grid: global MODIS sinusoidal 1 km grid cut to the 5-country bbox; cell kept if its centre is in a country.
Membership by rasterizing geoBoundaries ADM0/ADM1 (cell-centre rule). NDVI never resampled.
Monthly rows: Apr-Oct only. Columns: cell_id, month, ndvi, ndvi_rel, ndvi_ok
(+ precip [mm/month], precip_winter [Oct(prev)-Mar sum, mm], tair [deg C, GLDAS], soil_moist, swe [kg m-2]).
"""
from __future__ import annotations
import argparse
import calendar
import json
import re
import time
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import geopandas as gpd
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import rasterio
import xarray as xr
from pyproj import Transformer
from rasterio.features import rasterize
from rasterio.warp import Resampling, reproject, transform_bounds
from rasterio.windows import from_bounds
from scipy.ndimage import uniform_filter
ROOT = Path("/root/trendex-ca/data")
RAW, AOI_DIR, OUT, CACHE = ROOT / "raw", ROOT / "aoi", ROOT / "cube", ROOT / "cache"
MONTHS = list(range(4, 11))
BLOCK, STEEP_DEG, TPI_WINDOW, WORKERS = 11, 35.0, 5, 40
SINU = "+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +R=6371007.181 +units=m +no_defs"
SINU_CRS = rasterio.crs.CRS.from_proj4(SINU)
TILE = 1111950.5196666666
X0, Y0 = -20015109.355798, 10007554.677899
PIX1K = TILE / 1200
GRID: dict = {}
KEEP: tuple = () # (rows, cols) of kept cells; set before forking workers
LONLAT: tuple = ()
def log(m):
print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
# ----------------------------------------------------------------------------- grid + io
def build_grid() -> dict:
minx, miny, maxx, maxy = gpd.read_file(AOI_DIR / "aoi_request.geojson").to_crs(SINU).total_bounds
c0, c1 = int(np.floor((minx - X0) / PIX1K)), int(np.ceil((maxx - X0) / PIX1K))
r0, r1 = int(np.floor((Y0 - maxy) / PIX1K)), int(np.ceil((Y0 - miny) / PIX1K))
left, top = X0 + c0 * PIX1K, Y0 - r0 * PIX1K
return {"transform": rasterio.transform.from_origin(left, top, PIX1K, PIX1K), "shape": (r1 - r0, c1 - c0),
"left": left, "top": top, "r0": r0, "c0": c0}
def _open(src):
if isinstance(src, str):
with rasterio.open(src) as s:
return s.read(1), s.nodata, s.transform, s.crs
_, path, sds, npix = src
from pyhdf.SD import SD, SDC
m = re.search(r"\.h(\d{2})v(\d{2})\.", Path(path).name)
h, v = int(m[1]), int(m[2])
f = SD(path, SDC.READ)
try:
ds = f.select(sds)
raw, attrs = ds.get(), ds.attributes()
finally:
f.end()
pix = TILE / npix
return raw, attrs.get("_FillValue"), rasterio.transform.from_origin(X0 + h * TILE, Y0 - v * TILE, pix, pix), SINU_CRS
def to_master(srcs, resampling, fn=None) -> np.ndarray:
out = np.full(GRID["shape"], np.nan, dtype="float32")
for src in srcs:
raw, nodata, tr, crs = _open(src)
if fn:
a = fn(raw, nodata)
else:
a = raw.astype("float32")
if nodata is not None:
a[raw == nodata] = np.nan
tmp = np.full(GRID["shape"], np.nan, dtype="float32")
reproject(a.astype("float32"), tmp, src_transform=tr, src_crs=crs, dst_transform=GRID["transform"],
dst_crs=SINU_CRS, resampling=resampling, src_nodata=np.nan, dst_nodata=np.nan)
out = np.where(np.isnan(out), tmp, out)
return out
def hdf_by_date(product: str, sds: str, npix: int, months=None) -> dict:
by: dict = {}
for p in sorted((RAW / "earthaccess" / product).glob("*.hdf")):
m = re.search(r"\.A(\d{4})(\d{3})\.", p.name)
d = pd.Timestamp(year=int(m[1]), month=1, day=1) + pd.Timedelta(days=int(m[2]) - 1)
if months is None or d.month in months:
by.setdefault(d, []).append(("hdf", str(p), sds, npix))
return dict(sorted(by.items()))
# ----------------------------------------------------------------------------- workers (forked; use globals)
def ndvi_job(args):
d, nd_src, rel_src = args
a = to_master(nd_src, Resampling.nearest)
if np.nanmax(a) > 1.5:
a = a * 1e-4
rel = to_master(rel_src, Resampling.nearest)
r, c = KEEP
relv = rel[r, c]
return d, a[r, c].astype("float32"), np.where(np.isfinite(relv), relv, -1).astype("int8")
def dem_job(src):
"""One NASADEM 1-degree tile -> its window of the master grid (avoids shipping full-size arrays)."""
raw, nodata, tr, crs = _open(src)
z = raw.astype("float32")
z[raw == (nodata if nodata is not None else -32768)] = np.nan
lat = tr.f + tr.e * (np.arange(z.shape[0]) + 0.5)
dy = abs(tr.e) * 111_320.0
dx = tr.a * 111_320.0 * np.cos(np.deg2rad(lat))[:, None]
gy_rows, gx_cols = np.gradient(z)
gx, gy = gx_cols / dx, -gy_rows / dy
slope = np.degrees(np.arctan(np.hypot(gx, gy))).astype("float32")
aspect = np.arctan2(-gx, -gy)
layers = {"z": z, "z2": z * z, "slope": slope,
"steep": np.where(np.isnan(slope), np.nan, slope > STEEP_DEG).astype("float32"),
"asin": np.sin(aspect).astype("float32"), "acos": np.cos(aspect).astype("float32")}
h, w = z.shape
b = transform_bounds(crs, SINU_CRS, tr.c, tr.f + tr.e * h, tr.c + tr.a * w, tr.f, densify_pts=21)
minx, miny, maxx, maxy = b
r0 = max(int(np.floor((GRID["top"] - maxy) / PIX1K)) - 1, 0)
c0 = max(int(np.floor((minx - GRID["left"]) / PIX1K)) - 1, 0)
r1 = min(int(np.ceil((GRID["top"] - miny) / PIX1K)) + 1, GRID["shape"][0])
c1 = min(int(np.ceil((maxx - GRID["left"]) / PIX1K)) + 1, GRID["shape"][1])
if r1 <= r0 or c1 <= c0:
return None
wtr = rasterio.windows.transform(rasterio.windows.Window(c0, r0, c1 - c0, r1 - r0), GRID["transform"])
out = {}
for k, arr in layers.items():
tmp = np.full((r1 - r0, c1 - c0), np.nan, "float32")
reproject(arr, tmp, src_transform=tr, src_crs=crs, dst_transform=wtr, dst_crs=SINU_CRS,
resampling=Resampling.average, src_nodata=np.nan, dst_nodata=np.nan)
out[k] = tmp
return r0, c0, out
def weather_job(path: str):
lon, lat = LONLAT
p = Path(path)
if "IMERG" in p.name:
ym = re.search(r"\.(\d{8})-S", p.name).group(1)
y, m = int(ym[:4]), int(ym[4:6])
with xr.open_dataset(p, group="Grid", engine="h5netcdf") as ds:
da = ds["precipitation"].squeeze(drop=True).sel(lon=slice(float(lon.min()) - 1, float(lon.max()) + 1),
lat=slice(float(lat.min()) - 1, float(lat.max()) + 1)).load()
v = da.interp(lon=xr.DataArray(lon, dims="c"), lat=xr.DataArray(lat, dims="c")).values
return "precip", y, m, (v * 24 * calendar.monthrange(y, m)[1]).astype("float32")
ym = re.search(r"\.A(\d{6})\.", p.name).group(1)
y, m = int(ym[:4]), int(ym[4:])
with xr.open_dataset(p) as ds:
sub = ds[["SoilMoi0_10cm_inst", "SWE_inst", "Tair_f_inst"]].squeeze(drop=True).sel(
lon=slice(float(lon.min()) - 1, float(lon.max()) + 1), lat=slice(float(lat.min()) - 1, float(lat.max()) + 1)).load()
pts = sub.interp(lon=xr.DataArray(lon, dims="c"), lat=xr.DataArray(lat, dims="c"))
return "gldas", y, m, (pts["SoilMoi0_10cm_inst"].values.astype("float32"), pts["SWE_inst"].values.astype("float32"),
(pts["Tair_f_inst"].values - 273.15).astype("float32"))
# ----------------------------------------------------------------------------- stages
def stage_ndvi(manifest: dict) -> None:
global KEEP
t0 = time.time()
adm0 = gpd.read_file(AOI_DIR / "ca_adm0.geojson").to_crs(SINU)
adm1 = gpd.read_file(AOI_DIR / "ca_adm1.geojson").to_crs(SINU)
iso = list(adm0["iso3"])
cmap = rasterize(((g, i + 1) for i, g in enumerate(adm0.geometry)), out_shape=GRID["shape"],
transform=GRID["transform"], fill=0, dtype="int16")
rmap = rasterize(((g, i + 1) for i, g in enumerate(adm1.geometry)), out_shape=GRID["shape"],
transform=GRID["transform"], fill=0, dtype="int32")
r, c = np.nonzero(cmap > 0)
KEEP = (r, c)
x = GRID["left"] + (c + 0.5) * PIX1K
y = GRID["top"] - (r + 0.5) * PIX1K
lon, lat = Transformer.from_crs(SINU_CRS, 4326, always_xy=True).transform(x, y)
reg = rmap[r, c]
cells = pd.DataFrame({
"cell_id": ((r + GRID["r0"]) * 43200 + (c + GRID["c0"])).astype("int64"), "row": r, "col": c,
"x": x, "y": y, "lon": lon.astype("float32"), "lat": lat.astype("float32"),
"country": np.array(iso)[cmap[r, c] - 1],
"region": np.where(reg > 0, adm1["shapeName"].values[np.maximum(reg - 1, 0)], None),
"block_row": (r // BLOCK).astype("int16"), "block_col": (c // BLOCK).astype("int16")})
cells["block_id"] = cells["block_row"].astype(str) + "-" + cells["block_col"].astype(str)
log(f"grid {GRID['shape']}, cells {len(cells)}")
lc = hdf_by_date("MCD12Q1", "LC_Type1", 2400)
lc_src = [s for v in lc.values() for s in v]
lw_src = [("hdf", s[1], "LW", 2400) for s in lc_src]
clean = lambda raw, nd: np.where(raw == 255, np.nan, raw).astype("float32") # noqa: E731
cells["lc_type1"] = to_master(lc_src, Resampling.mode, fn=clean)[r, c]
for name, cls in {"grass_frac": [10], "barren_frac": [16], "crop_frac": [12, 14], "forest_frac": [1, 2, 3, 4, 5],
"ice_frac": [15], "urban_frac": [13]}.items():
cells[name] = to_master(lc_src, Resampling.average,
fn=lambda raw, nd, k=cls: np.where(raw == 255, np.nan, np.isin(raw, k)).astype("float32"))[r, c]
cells["water_frac"] = to_master(lw_src, Resampling.average,
fn=lambda raw, nd: np.where(raw == 255, np.nan, raw == 1).astype("float32"))[r, c]
log(f"land cover done {time.time() - t0:.0f}s")
dem = sorted((RAW / "earthaccess" / "NASADEM").glob("*.zip"))
srcs = [f"/vsizip/{z}/{z.stem.split('_')[-1]}.hgt" for z in dem]
acc = {k: np.full(GRID["shape"], np.nan, "float32") for k in ("z", "z2", "slope", "steep", "asin", "acos")}
with ProcessPoolExecutor(WORKERS) as pool:
for res in pool.map(dem_job, srcs, chunksize=2):
if res is None:
continue
r0, c0, out = res
for k, a in out.items():
view = acc[k][r0:r0 + a.shape[0], c0:c0 + a.shape[1]]
np.copyto(view, a, where=np.isnan(view) & np.isfinite(a))
elev = acc["z"]
cells["elev_mean"] = elev[r, c]
cells["elev_std"] = np.sqrt(np.clip(acc["z2"] - elev ** 2, 0, None))[r, c]
cells["slope_mean"], cells["steep_share"] = acc["slope"][r, c], acc["steep"][r, c]
cells["aspect_sin"], cells["aspect_cos"] = acc["asin"][r, c], acc["acos"][r, c]
valid = np.isfinite(elev)
num = uniform_filter(np.where(valid, elev, 0), TPI_WINDOW)
den = uniform_filter(valid.astype("float32"), TPI_WINDOW)
cells["tpi"] = (elev - num / np.maximum(den, 1e-6))[r, c]
del acc
rules = [("water", (cells["water_frac"] > 0.5) | (cells["lc_type1"] == 17)), ("ice", cells["lc_type1"] == 15),
("urban", cells["lc_type1"] == 13), ("too_steep", cells["slope_mean"] > STEEP_DEG),
("barren", cells["lc_type1"] == 16), ("cropland", cells["lc_type1"].isin([12, 14])),
("forest", cells["lc_type1"].isin([1, 2, 3, 4, 5]))]
reason = pd.Series(pd.NA, index=cells.index, dtype="string")
for name, cond in rules:
reason = reason.mask(reason.isna() & cond.fillna(False), name)
cells["mask_reason"] = reason
OUT.mkdir(parents=True, exist_ok=True)
cells.to_parquet(OUT / "cells.parquet", index=False)
manifest["cells"] = {"n": len(cells), "by_country": cells["country"].value_counts().astype(int).to_dict(),
"mask_reason": {str(k): int(v) for k, v in cells["mask_reason"].value_counts(dropna=False).items()},
"dem_tiles": len(srcs)}
log(f"cells.parquet written ({len(srcs)} DEM tiles) {time.time() - t0:.0f}s")
nd = hdf_by_date("MOD13A3", "1 km monthly NDVI", 1200, set(MONTHS))
nr = hdf_by_date("MOD13A3", "1 km monthly pixel reliability", 1200, set(MONTHS))
CACHE.mkdir(parents=True, exist_ok=True)
dates = list(nd)
ndvi = np.lib.format.open_memmap(CACHE / "ndvi.npy", mode="w+", dtype="float32", shape=(len(dates), len(cells)))
rel = np.lib.format.open_memmap(CACHE / "rel.npy", mode="w+", dtype="int8", shape=(len(dates), len(cells)))
with ProcessPoolExecutor(WORKERS) as pool:
for d, a, b in pool.map(ndvi_job, [(d, nd[d], nr.get(d, [])) for d in dates]):
i = dates.index(d)
ndvi[i], rel[i] = a, b
ndvi.flush(); rel.flush()
pd.Series([str(d.date()) for d in dates]).to_csv(CACHE / "dates.csv", index=False)
log(f"ndvi {len(dates)} months {time.time() - t0:.0f}s")
write_monthly(cells["cell_id"].values, dates, ndvi, rel, None)
manifest["partial"] = True
manifest["monthly"] = {"months": MONTHS, "n_dates": len(dates), "columns": ["cell_id", "month", "ndvi", "ndvi_rel", "ndvi_ok"],
"note": "PARTIAL: NDVI only; weather columns follow"}
def write_monthly(ids, dates, ndvi, rel, wx, root: Path | None = None) -> None:
root = root or OUT / "monthly"
years = sorted({d.year for d in dates})
for yr in years:
parts = []
for i, d in enumerate(dates):
if d.year != yr:
continue
cols = {"cell_id": ids, "month": np.full(len(ids), d.month, "int8"), "ndvi": ndvi[i],
"ndvi_rel": rel[i], "ndvi_ok": np.isin(rel[i], (0, 1))}
if wx is not None:
for k in ("precip", "precip_winter", "tair", "soil_moist", "swe"):
cols[k] = wx[k].get((yr, d.month), np.full(len(ids), np.nan, "float32"))
parts.append(pa.table(cols))
dest = root / f"year={yr}"
dest.mkdir(parents=True, exist_ok=True)
pq.write_table(pa.concat_tables(parts), dest / "part.parquet", row_group_size=2_000_000)
log(f"monthly {yr} written")
def stage_weather(manifest: dict) -> None:
global LONLAT
t0 = time.time()
cells = pd.read_parquet(OUT / "cells.parquet", columns=["cell_id", "lon", "lat"])
LONLAT = (cells["lon"].values.astype("float64"), cells["lat"].values.astype("float64"))
files = sorted(str(p) for p in (RAW / "gesdisc" / "GPM_3IMERGM").glob("*.HDF5")) + \
sorted(str(p) for p in (RAW / "gesdisc" / "GLDAS_NOAH025_M").glob("*.nc4"))
precip, soil, swe, tair = {}, {}, {}, {}
with ProcessPoolExecutor(24) as pool:
for kind, y, m, v in pool.map(weather_job, files, chunksize=2):
if kind == "precip":
precip[(y, m)] = v
else:
soil[(y, m)], swe[(y, m)], tair[(y, m)] = v
log(f"weather interpolated: {len(precip)} IMERG, {len(soil)} GLDAS months {time.time() - t0:.0f}s")
winter = {}
for yr in range(2001, 2026):
keys = [(yr - 1, 10), (yr - 1, 11), (yr - 1, 12), (yr, 1), (yr, 2), (yr, 3)]
if all(k in precip for k in keys):
w = sum(precip[k] for k in keys)
for mo in MONTHS:
winter[(yr, mo)] = w
wx = {"precip": precip, "precip_winter": winter, "tair": tair, "soil_moist": soil, "swe": swe}
dates = [pd.Timestamp(s) for s in pd.read_csv(CACHE / "dates.csv").iloc[:, 0]]
ndvi = np.load(CACHE / "ndvi.npy", mmap_mode="r")
rel = np.load(CACHE / "rel.npy", mmap_mode="r")
# write the full table next to the NDVI-only one, then swap (readers of the old files are not disturbed)
write_monthly(cells["cell_id"].values, dates, ndvi, rel, wx, OUT / "monthly_full")
old = OUT / "monthly_ndvi_only"
if old.exists():
import shutil
shutil.rmtree(old)
(OUT / "monthly").rename(old)
(OUT / "monthly_full").rename(OUT / "monthly")
manifest["partial"] = False
manifest["monthly"] = {"months": MONTHS, "n_dates": len(dates),
"columns": ["cell_id", "month", "ndvi", "ndvi_rel", "ndvi_ok", "precip", "precip_winter",
"tair", "soil_moist", "swe"]}
log(f"weather stage done {time.time() - t0:.0f}s")
def main() -> None:
global GRID
ap = argparse.ArgumentParser()
ap.add_argument("--stage", choices=["ndvi", "weather"], required=True)
a = ap.parse_args()
GRID = build_grid()
mpath = OUT / "manifest.json"
manifest = json.loads(mpath.read_text()) if mpath.exists() else {}
manifest.update({
"name": "TrendeX Central Asia cube", "synthetic": False,
"updated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"grid": {"crs": SINU, "shape": GRID["shape"], "res_m": PIX1K, "origin_left_top": [GRID["left"], GRID["top"]],
"cell_id": "global_row * 43200 + global_col on the MODIS 1 km grid", "block_cells": BLOCK},
"aoi": "geoBoundaries gbOpen ADM0 of KAZ, KGZ, TJK, TKM, UZB; region = ADM1 shapeName; cell-centre rule",
"units": {"ndvi": "NDVI (scaled)", "ndvi_rel": "MOD13A3 pixel reliability (-1 missing, 0 good, 1 marginal, 2 snow, 3 cloud)",
"ndvi_ok": "reliability 0-1", "precip": "mm per month (IMERG Final V07)",
"precip_winter": "mm, Oct (previous year) .. Mar sum (IMERG)", "tair": "deg C, GLDAS-2.1 air temperature",
"soil_moist": "kg m-2, GLDAS-2.1 0-10 cm", "swe": "kg m-2, GLDAS-2.1",
"elev_mean": "m (NASADEM 30 m averaged)", "slope_mean": "deg, computed at 30 m then averaged to 1 km",
"lc_type1": "IGBP MCD12Q1 2020 mode over 500 m pixels"},
"datasets": {"MOD13A3": "061, doi:10.5067/MODIS/MOD13A3.061", "MCD12Q1": "061, doi:10.5067/MODIS/MCD12Q1.061",
"NASADEM_HGT": "001, doi:10.5067/MEaSUREs/NASADEM/NASADEM_HGT.001",
"GPM_3IMERGM": "07, doi:10.5067/GPM/IMERG/3B-MONTH/07", "GLDAS_NOAH025_M": "2.1, doi:10.5067/SXAVCZFAQLNO"},
"notes": ["Months Apr-Oct only. No Aqua NDVI, no MODIS LST/snow in the CA cube (GLDAS tair/swe instead).",
"mask_reason adds barren / cropland / forest to the Naryn rules; first matching rule wins."]})
stage_ndvi(manifest) if a.stage == "ndvi" else stage_weather(manifest)
mpath.write_text(json.dumps(manifest, indent=2, default=str))
log(f"STAGE_{a.stage.upper()}_DONE")
if __name__ == "__main__":
main()