Download code/build_demo_data.py from eduzrh/helloworld: direct link, hf CLI and curl.
- Browser
- Download file 3.63 kB
-
https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/code/build_demo_data.py
- Command line
-
hf download hf://datasets/eduzrh/helloworld/code/build_demo_data.py
-
curl -L -o build_demo_data.py https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/code/build_demo_data.py
3.63 kB
| """把结果打包为单文件 demo 数据(window.DEMO_DATA)。""" | |
| import base64 | |
| import json | |
| import os | |
| import numpy as np | |
| import netCDF4 as nc | |
| from shapely.geometry import shape, Point | |
| from shapely.prepared import prep | |
| BASE = os.path.dirname(os.path.abspath(__file__)) | |
| OUT = os.path.join(BASE, "results") | |
| DEMO = os.path.join(BASE, "demo") | |
| os.makedirs(DEMO, exist_ok=True) | |
| def land_mask(lat, lon): | |
| gj = json.load(open(os.path.join(BASE, "data", "land110.geojson"))) | |
| geoms = [prep(shape(f["geometry"])) for f in gj["features"]] | |
| lon_s = ((lon + 180) % 360) - 180 | |
| m = np.zeros((len(lat), len(lon)), dtype=bool) | |
| 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 b64(a): | |
| return base64.b64encode(a.tobytes()).decode() | |
| def main(): | |
| d = nc.Dataset(os.path.join(BASE, "data", "precip.mon.mean.nc")) | |
| lat = np.array(d["lat"][:], float) | |
| lon = np.array(d["lon"][:], float) | |
| d.close() | |
| spi = np.load(os.path.join(OUT, "spi.npy")) | |
| sti = np.load(os.path.join(OUT, "sti.npy")) | |
| monthly = json.load(open(os.path.join(OUT, "monthly_series.json"))) | |
| annual = json.load(open(os.path.join(OUT, "annual_series.json"))) | |
| region = json.load(open(os.path.join(OUT, "region_series.json"))) | |
| summary = json.load(open(os.path.join(OUT, "summary.json"))) | |
| mask = land_mask(lat, lon) | |
| flat = np.flatnonzero(mask.ravel()) | |
| ni, nj = mask.shape | |
| spi_f = spi.reshape(spi.shape[0], -1)[:, flat] | |
| sti_f = sti.reshape(sti.shape[0], -1)[:, flat] | |
| # 年度帧:每年 CDHE 面积占比最大的月份 | |
| frames = [] | |
| for y in sorted({r["year"] for r in monthly}): | |
| rows = [r for r in monthly if r["year"] == y] | |
| r = max(rows, key=lambda x: x["cdhe_frac"]) | |
| k = monthly.index(r) | |
| sp = np.nan_to_num(spi_f[k], nan=0.0) | |
| st = np.nan_to_num(sti_f[k], nan=0.0) | |
| flag = np.where((sp <= -1) & (st >= 1), 3, np.where(sp <= -1, 1, np.where(st >= 1, 2, 0))).astype("uint8") | |
| frames.append(dict( | |
| year=int(y), month=int(r["month"]), | |
| frac=round(r["cdhe_frac"] * 100, 2), | |
| dry=round(r["dry_frac"] * 100, 2), | |
| hot=round(r["hot_frac"] * 100, 2), | |
| cells=int(r["cdhe_cells"]), | |
| intensity=round(r["cdhe_intensity"], 2), | |
| flag=b64(flag), | |
| spi=b64(np.clip(np.round(sp * 10), -127, 127).astype("int8")), | |
| sti=b64(np.clip(np.round(st * 10), -127, 127).astype("int8")), | |
| )) | |
| payload = dict( | |
| grid=dict(lat=[round(float(x), 2) for x in lat], lon=[round(float(x), 2) for x in lon], | |
| ni=int(ni), nj=int(nj), land=b64(flat.astype("uint16"))), | |
| frames=frames, | |
| monthly=[dict(y=r["year"], m=r["month"], f=round(r["cdhe_frac"] * 100, 2)) for r in monthly], | |
| annual=[dict(y=a["year"], f=round(a["cdhe_frac_mean"] * 100, 2), | |
| mx=round(a["cdhe_frac_max"] * 100, 2)) for a in annual], | |
| region={k: [dict(y=r["year"], f=round(r["cdhe_frac"] * 100, 2)) for r in v] for k, v in region.items()}, | |
| summary=summary, | |
| ) | |
| s = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) | |
| with open(os.path.join(DEMO, "data.js"), "w") as f: | |
| f.write("window.DEMO_DATA=" + s + ";") | |
| print("frames", len(frames), "size MB", round(len(s) / 1e6, 2)) | |
| print(json.dumps(frames[-1], ensure_ascii=False)[:200]) | |
| json.dump({k: frames[k]["year"] for k in range(len(frames))}, open("/tmp/frames.json", "w")) | |
| if __name__ == "__main__": | |
| main() | |