"""Build China annual SPI dataset from CRU TS v4.10 monthly precipitation (0.5 deg).  (锐多宝工具集, v2 2026-11-30)
用法：python make_data.py --raw raw/ --boundary china-boundary.geojson --out out/
  raw/       CRU TS v4.10 月降水 cru_ts4.10.YYYY.YYYY.pre.dat.nc（官方 .nc.gz 解压），至少覆盖 1975–2025：
             https://crudata.uea.ac.uk/cru/data/hrg/cru_ts_4.10/cruts.2604091129.v4.10/pre/
  boundary   锐多宝工具集公开的国界线 https://data.ruiduobao.cn/tools/core/china-boundary.geojson（kind=boundary 的线 polygonize 成面）
  依赖       python3, numpy, scipy, netCDF4, shapely
口径：
- 年总量 = 1–12 月合计（12 个月尺度 SPI，日历年）；任一月缺测 → 该年缺测。
- 「疑似退回气候态」判定（本站启发式，不是 CRU 官方逐格质量标记；CRU 另发布的测站数 stn 文件本脚本未采用）：
  CRU TS 方法中，格点附近无测站时距平取 0、数值即气候态，表现为同一日历月的值在多年间几乎重复。
  某年 ≥10 个月落在各自日历月众数（众数出现 ≥3 次）±max(0.15 mm, 3%) 以内 → 该格点该年按启发式记缺测。
- 每格点用 1975–2025 中「有效年」拟合两参数 Gamma（loc=0）；有效年 < 30，或有效年年总量变差系数 CV < 0.05（年际变化疑似被源数据压平，启发式）→ 该格点全部年份记缺测。
- 缺测在 bin 中记 int8 = -128；年降水 mm 仍原样保存（供核对）。
- 全国平均 = 非缺测格点按 cos(纬度) 加权。
Output: precip-spi.bin + precip-spi-meta.json
"""
import argparse, glob, json, os, numpy as np, netCDF4
from scipy import stats
from shapely.geometry import shape, Point
from shapely.ops import polygonize, unary_union
from shapely.prepared import prep

ap = argparse.ArgumentParser(description='CRU TS v4.10 pre -> precip-spi.bin + precip-spi-meta.json')
ap.add_argument('--raw', default='raw'); ap.add_argument('--boundary', default='china-boundary.geojson'); ap.add_argument('--out', default='out')
A = ap.parse_args(); os.makedirs(A.out, exist_ok=True)

Y0, Y1 = 1975, 2025; NY = Y1 - Y0 + 1; MINY = 30; MINCV = 0.05; MISS = -128
files = sorted(glob.glob(os.path.join(A.raw, 'cru_ts4.10.*.pre.dat.nc')))
assert files, 'no CRU TS v4.10 pre .nc files in --raw'
pre = []; tt = []
for f in files:
    d = netCDF4.Dataset(f); t = netCDF4.num2date(d['time'][:], d['time'].units, only_use_cftime_datetimes=False)
    sel = [k for k, x in enumerate(t) if Y0 <= x.year <= Y1]
    if not sel: continue
    lon = d['lon'][:].data; lat = d['lat'][:].data
    pre.append(d['pre'][sel].filled(np.nan)); tt += [t[k] for k in sel]
pre = np.concatenate(pre); assert len(tt) == NY * 12
bl = [shape(f['geometry']) for f in json.load(open(A.boundary, encoding='utf-8'))['features'] if f['properties'].get('kind') == 'boundary']
cn = prep(unary_union(list(polygonize(unary_union(bl)))).buffer(0))   # 国界线 → 面；取格心落在面内的格点

def relaxed_years(mon):
    s = np.round(mon.reshape(NY, 12), 1); neq = np.zeros(NY, int); tot = 0
    for c in range(12):
        v, cnt = np.unique(s[:, c], return_counts=True)
        if cnt.max() < 3: return np.zeros(NY, bool)
        md = v[cnt.argmax()]; tot += md; neq += np.abs(s[:, c] - md) <= max(0.15, 0.03 * md)
    return (neq >= 10) if tot > 0 else np.zeros(NY, bool)   # 启发式：≥10 个月落在气候众数 ±max(0.15mm,3%) 内 → 疑似退回气候态

cells, P, S, VY = [], [], [], []
stat = {'mask': 0, 'dropped_all_nan': [], 'cells_lt30': [], 'cellyears_relaxed': 0}
for j, la in enumerate(lat):
    if not (3 <= la <= 54): continue
    for i, lo in enumerate(lon):
        if not (73 <= lo <= 136) or not cn.contains(Point(lo, la)): continue
        stat['mask'] += 1
        mon = pre[:, j, i]; ann = mon.reshape(NY, 12).sum(1)
        if np.isnan(ann).all(): stat['dropped_all_nan'].append((float(lo), float(la))); continue
        rel = relaxed_years(mon); valid = ~np.isnan(ann) & ~rel
        stat['cellyears_relaxed'] += int(rel.sum())
        spi = np.full(NY, MISS, np.int16)
        pv0 = ann[valid]; cv = float(pv0.std() / pv0.mean()) if valid.sum() > 1 else 0.0
        if valid.sum() >= MINY and cv >= MINCV:
            pv = ann[valid]; q = (pv <= 0).mean()
            a, _, b = stats.gamma.fit(pv[pv > 0], floc=0)
            cdf = q + (1 - q) * np.where(ann > 0, stats.gamma.cdf(np.where(ann > 0, ann, 1), a, scale=b), 0)
            z = np.clip(stats.norm.ppf(np.clip(cdf, 1e-6, 1 - 1e-6)), -3, 3)
            spi[valid] = np.round(z[valid] * 40).astype(np.int16)
        else:
            stat['cells_lt30'].append((float(lo), float(la), int(valid.sum()), round(cv, 4)))
        cells.append((round(float(lo), 2), round(float(la), 2)))
        P.append(np.clip(np.round(np.nan_to_num(ann)), 0, 65535).astype(np.uint16))
        S.append(spi.astype(np.int8)); VY.append(int(valid.sum()) if (valid.sum() >= MINY and cv >= MINCV) else 0)
n = len(cells); P = np.array(P).T.copy(); S = np.array(S).T.copy()
w = np.cos(np.radians([c[1] for c in cells])); ok = S != MISS
nat = ((np.where(ok, S, 0) / 40.0) * w).sum(1) / (ok * w).sum(1)
natP = (P * w).sum(1) / w.sum()
with open(os.path.join(A.out, 'precip-spi.bin'), 'wb') as f:
    f.write(S.astype(np.int8).tobytes()); f.write(P.astype('<u2').tobytes())
meta = {
  "version": 2, "source": "CRU TS v4.10 pre (Harris et al. 2020, doi:10.1038/s41597-020-0453-3)",
  "license": "Open Database License (ODbL) v1.0 / Database Contents License v1.0; attribution + share-alike",
  "method": "calendar-year (Jan-Dec) totals = 12-month SPI; years in which >=10 of the 12 monthly values lie within max(0.15 mm, 3%) of the calendar-month mode (site heuristic for values that appear relaxed to climatology; not an official CRU per-cell quality flag; CRU station-count files not used) or contain a missing month are treated as missing; two-parameter gamma (loc=0) fitted per cell on valid years of 1975-2025 (>=30 valid years and CV>=0.05 required, else whole cell missing); SPI = Phi^-1(F), clipped to +-3; missing stored as -128; national mean = cos(lat)-weighted over non-missing cells",
  "years": [Y0, Y1], "res": 0.5, "n": n, "spiScale": 40, "missing": MISS, "minValidYears": MINY, "minCV": MINCV,
  "layout": "bin = int8 spi*40 [year][cell] (-128 = missing) then uint16LE annual mm [year][cell]",
  "lon": [c[0] for c in cells], "lat": [c[1] for c in cells],
  "validYears": VY,
  "nationalSpi": [round(float(x), 3) for x in nat],
  "nationalMm": [round(float(x), 1) for x in natP],
}
json.dump(meta, open(os.path.join(A.out, 'precip-spi-meta.json'), 'w'), separators=(',', ':'))
stat.update({'kept': n, 'missing_cellyears_total': int((~ok).sum()), 'n_cells_lt30': len(stat['cells_lt30']),
             'cells_some_missing': int(((~ok).sum(0) > 0).sum())})
json.dump(stat, open(os.path.join(A.out, 'make_data-stats.json'), 'w'), indent=1)
print(json.dumps({k: v for k, v in stat.items() if k != 'cells_lt30'}, indent=1)); print('lt30', stat['cells_lt30'])
print('bin', os.path.getsize(os.path.join(A.out, 'precip-spi.bin')), 'meta', os.path.getsize(os.path.join(A.out, 'precip-spi-meta.json')))
print({y: meta['nationalSpi'][y - Y0] for y in (1998, 2011, 2016, 2024, 2025)})
