Download code/compute_cdhe.py from eduzrh/helloworld: direct link, hf CLI and curl.
- Browser
- Download file 9.06 kB
-
https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/code/compute_cdhe.py
- Command line
-
hf download hf://datasets/eduzrh/helloworld/code/compute_cdhe.py
-
curl -L -o compute_cdhe.py https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/code/compute_cdhe.py
9.06 kB
| """ | |
| 全球复合干热事件(CDHE)状态序列评估 | |
| 数据:NOAA PSL 公开格点 | |
| - CMAP enhanced 降水(2.5°,mm/day,1979—) | |
| - NCEP/NCAR 再分析 2 m 气温(2.5°,degC,1948—) | |
| - Natural Earth 110m 陆地边界(用于陆地掩膜) | |
| 方法:按日历月构建经验分布,得到标准化降水指数 SPI 与标准化温度指数 STI, | |
| 以 SPI<=-1 且 STI>=1 判定复合干热月。 | |
| 输出:月度/年度全球指标、区域指标、最新月状态栅格。 | |
| """ | |
| import json | |
| import os | |
| import numpy as np | |
| import netCDF4 as nc | |
| from scipy.stats import norm | |
| from shapely.geometry import shape, Point | |
| from shapely.prepared import prep | |
| BASE = os.path.dirname(os.path.abspath(__file__)) | |
| DATA = os.path.join(BASE, "data") | |
| OUT = os.path.join(BASE, "results") | |
| os.makedirs(OUT, exist_ok=True) | |
| BASE_YEARS = (1991, 2020) | |
| SPI_THR = -1.0 | |
| STI_THR = 1.0 | |
| REGIONS = [ | |
| ("亚马逊", -15, 5, -75, -45), | |
| ("欧洲", 35, 70, -10, 40), | |
| ("东亚", 20, 50, 100, 145), | |
| ("北美", 25, 60, -125, -65), | |
| ("澳大利亚", -45, -10, 110, 155), | |
| ("非洲南部", -35, 5, 10, 50), | |
| ("干旱亚洲", 15, 45, 40, 80), | |
| ("南美南部", -40, -20, -75, -45), | |
| ] | |
| def load(path, var): | |
| d = nc.Dataset(path) | |
| lat = np.array(d.variables["lat"][:], dtype=float) | |
| lon = np.array(d.variables["lon"][:], dtype=float) | |
| t = d.variables["time"] | |
| times = nc.num2date(t[:], t.units, only_use_cftime_datetimes=False) | |
| v = np.array(d.variables[var][:], dtype=float) | |
| fill = getattr(d.variables[var], "_FillValue", None) | |
| d.close() | |
| if fill is not None: | |
| v[v == fill] = np.nan | |
| v[v > 1e20] = np.nan | |
| months = np.array([(x.year, x.month) for x in times]) | |
| return lat, lon, months, v | |
| def regrid(arr, src_lat, src_lon, dst_lat, dst_lon): | |
| """双线性插值到目标网格(纬度升序、经度环绕)。""" | |
| from scipy.interpolate import RegularGridInterpolator | |
| la = src_lat[::-1] | |
| lo = np.append(src_lon, 360.0) | |
| a = np.concatenate([arr[:, ::-1, :], arr[::-1, :, :1]], axis=2) | |
| out = np.empty((arr.shape[0], len(dst_lat), len(dst_lon)), dtype="float32") | |
| for k in range(arr.shape[0]): | |
| f = RegularGridInterpolator((la, lo), a[k], bounds_error=False) | |
| pts = np.array(np.meshgrid(dst_lat, dst_lon, indexing="ij")).reshape(2, -1).T | |
| out[k] = f(pts).reshape(len(dst_lat), len(dst_lon)) | |
| return out | |
| def land_mask(lat, lon): | |
| gj = json.load(open(os.path.join(DATA, "land110.geojson"))) | |
| geoms = [prep(shape(f["geometry"])) for f in gj["features"]] | |
| m = np.zeros((len(lat), len(lon)), dtype=bool) | |
| lon_s = ((lon + 180) % 360) - 180 | |
| for i, la in enumerate(lat): | |
| for j, lo in enumerate(lon_s): | |
| p = Point(lo, la) | |
| m[i, j] = any(g.contains(p) for g in geoms) | |
| return m | |
| def standardized(v, months, base_years): | |
| """按日历月做经验分布标准化,返回与 v 同形状的指数(Phi^{-1}(p))。""" | |
| out = np.full_like(v, np.nan) | |
| years = np.array([m[0] for m in months]) | |
| mon = np.array([m[1] for m in months]) | |
| inbase = (years >= base_years[0]) & (years <= base_years[1]) | |
| for cm in range(1, 13): | |
| idx_all = np.where(mon == cm)[0] | |
| idx_base = np.where((mon == cm) & inbase)[0] | |
| if len(idx_base) < 10: | |
| continue | |
| ref = v[idx_base] # (n, lat, lon) | |
| # 每个格点单独排序,得到经验累积概率(Gringorten) | |
| n = ref.shape[0] | |
| order = np.argsort(ref, axis=0) | |
| ranks = np.empty_like(order) | |
| np.put_along_axis(ranks, order, np.arange(n).reshape((n,) + (1,) * (ref.ndim - 1)), axis=0) | |
| ranks = ranks + 1 | |
| # 对每个目标月,用其在基准期分布中的位置 | |
| for k in idx_all: | |
| val = v[k] | |
| # 逐格点的插入位置(右插入) | |
| pos = (ref < val[None]).sum(axis=0) | |
| p = (pos + 0.44) / (n + 0.12) | |
| p = np.clip(p, 1e-4, 1 - 1e-4) | |
| out[k] = norm.ppf(p) | |
| return out | |
| def dump(obj, path): | |
| def conv(o): | |
| if hasattr(o, "item"): | |
| return o.item() | |
| raise TypeError(type(o)) | |
| json.dump(obj, open(path, "w"), ensure_ascii=False, default=conv) | |
| def main(): | |
| lat_p, lon_p, mon_p, pr = load(os.path.join(DATA, "precip.mon.mean.nc"), "precip") | |
| lat_t, lon_t, mon_t, ta = load(os.path.join(DATA, "air.mon.mean.nc"), "air") | |
| lat, lon = lat_p, lon_p | |
| if ta.shape[1:] != pr.shape[1:]: | |
| ta = regrid(ta, lat_t, lon_t, lat_p, lon_p) | |
| # 对齐共同月份 | |
| common = sorted(set(map(tuple, mon_p)) & set(map(tuple, mon_t))) | |
| common = [m for m in common if m >= (1979, 1)] | |
| ip = {tuple(m): i for i, m in enumerate(mon_p)} | |
| it = {tuple(m): i for i, m in enumerate(mon_t)} | |
| pr = np.stack([pr[ip[m]] for m in common]) | |
| ta = np.stack([ta[it[m]] for m in common]) | |
| months = common | |
| mask = land_mask(lat, lon) | |
| w = np.cos(np.deg2rad(lat))[:, None] | |
| wl = np.where(mask, w, 0.0) | |
| spi = standardized(pr, months, BASE_YEARS) | |
| sti = standardized(ta, months, BASE_YEARS) | |
| dry = spi <= SPI_THR | |
| hot = sti >= STI_THR | |
| cdhe = dry & hot & mask[None] | |
| # 月度全球指标 | |
| rows = [] | |
| for k, (y, m) in enumerate(months): | |
| a = wl > 0 | |
| frac = np.nansum(wl[cdhe[k]]) / np.nansum(wl) | |
| frac_dry = np.nansum(wl[dry[k] & mask]) / np.nansum(wl) | |
| frac_hot = np.nansum(wl[hot[k] & mask]) / np.nansum(wl) | |
| inten = np.nanmean(((-spi[k]) * (sti[k]))[cdhe[k]]) if cdhe[k].any() else 0.0 | |
| rows.append(dict(year=y, month=m, cdhe_frac=frac, dry_frac=frac_dry, | |
| hot_frac=frac_hot, cdhe_intensity=float(inten), | |
| cdhe_cells=int(cdhe[k].sum()), land_cells=int(mask.sum()))) | |
| # 年度汇总 | |
| years = sorted(set(r["year"] for r in rows)) | |
| annual = [] | |
| for y in years: | |
| yr = [r for r in rows if r["year"] == y] | |
| annual.append(dict( | |
| year=y, | |
| cdhe_frac_mean=float(np.mean([r["cdhe_frac"] for r in yr])), | |
| cdhe_frac_max=float(np.max([r["cdhe_frac"] for r in yr])), | |
| cdhe_months_cells=int(sum(r["cdhe_cells"] for r in yr)), | |
| cdhe_intensity_mean=float(np.mean([r["cdhe_intensity"] for r in yr])), | |
| )) | |
| # 区域指标 | |
| region_rows = [] | |
| for name, la0, la1, lo0, lo1 in REGIONS: | |
| lon_s = ((lon + 180) % 360) - 180 | |
| sel = ((lat[:, None] >= la0) & (lat[:, None] <= la1) | |
| & (lon_s[None, :] >= lo0) & (lon_s[None, :] <= lo1) & mask) | |
| if sel.sum() == 0: | |
| continue | |
| ww = np.where(sel, w, 0) | |
| for k, (y, m) in enumerate(months): | |
| f = np.nansum(ww[cdhe[k]]) / np.nansum(ww) | |
| region_rows.append(dict(region=name, year=y, month=m, cdhe_frac=float(f))) | |
| reg = {} | |
| for name, *_ in REGIONS: | |
| sub = [r for r in region_rows if r["region"] == name] | |
| if not sub: | |
| continue | |
| ys = sorted(set(r["year"] for r in sub)) | |
| series = [] | |
| for y in ys: | |
| vv = [r["cdhe_frac"] for r in sub if r["year"] == y] | |
| series.append(dict(year=y, cdhe_frac=float(np.mean(vv)))) | |
| reg[name] = series | |
| # 最新月状态 | |
| k = len(months) - 1 | |
| latest = dict( | |
| year=int(months[k][0]), month=int(months[k][1]), | |
| lat=[float(x) for x in lat], lon=[float(x) for x in lon], | |
| spi=np.round(np.where(mask, spi[k], np.nan), 2).tolist(), | |
| sti=np.round(np.where(mask, sti[k], np.nan), 2).tolist(), | |
| cdhe=np.where(mask, cdhe[k].astype(int), -1).tolist(), | |
| land=mask.astype(int).tolist(), | |
| ) | |
| summary = dict( | |
| period=[f"{months[0][0]}-{months[0][1]:02d}", f"{months[-1][0]}-{months[-1][1]:02d}"], | |
| n_months=len(months), baseline=list(BASE_YEARS), | |
| spi_threshold=SPI_THR, sti_threshold=STI_THR, | |
| land_cells=int(mask.sum()), | |
| latest=dict(year=int(months[k][0]), month=int(months[k][1]), | |
| cdhe_frac=rows[k]["cdhe_frac"], dry_frac=rows[k]["dry_frac"], | |
| hot_frac=rows[k]["hot_frac"]), | |
| peak=dict(year=max(annual, key=lambda a: a["cdhe_frac_mean"])["year"], | |
| cdhe_frac=max(a["cdhe_frac_mean"] for a in annual)), | |
| annual_mean=float(np.mean([a["cdhe_frac_mean"] for a in annual])), | |
| first_decade_mean=float(np.mean([a["cdhe_frac_mean"] for a in annual if a["year"] < 1999])), | |
| last_decade_mean=float(np.mean([a["cdhe_frac_mean"] for a in annual if a["year"] >= 2016])), | |
| ) | |
| dump(rows, os.path.join(OUT, "monthly_series.json")) | |
| dump(annual, os.path.join(OUT, "annual_series.json")) | |
| dump(reg, os.path.join(OUT, "region_series.json")) | |
| dump(latest, os.path.join(OUT, "latest_grid.json")) | |
| dump(summary, os.path.join(OUT, "summary.json")) | |
| np.save(os.path.join(OUT, "spi.npy"), spi.astype("float32")) | |
| np.save(os.path.join(OUT, "sti.npy"), sti.astype("float32")) | |
| print(open(os.path.join(OUT, "summary.json")).read()) | |
| if __name__ == "__main__": | |
| main() | |