Download code/dcpp_fetch.py from Tonic/protostar-climate-2026: direct link, hf CLI and curl.
- Browser
- Download file 4.49 kB
-
https://huggingface.co/datasets/Tonic/protostar-climate-2026/resolve/main/code/dcpp_fetch.py
- Command line
-
hf download hf://datasets/Tonic/protostar-climate-2026/code/dcpp_fetch.py
-
curl -L -o dcpp_fetch.py https://huggingface.co/datasets/Tonic/protostar-climate-2026/resolve/main/code/dcpp_fetch.py
4.49 kB
| """Fetch DCPP city-level annual tas/pr from Pangeo CMIP6 zarr (MPI-ESM1-2-HR). | |
| For each (start, member, variable): annual means at the nearest grid cell to | |
| each of the 210 cities, calendar years start+1 .. start+7. Incremental: rows | |
| are appended to data/external/dcpp_city_annual.csv and finished datasets are | |
| skipped on rerun. Selection-era starts (<=2004) are fetched first. | |
| Only hindcasts initialised <= an origin are ever used for that origin | |
| (enforced in dcpp.py), including for drift climatology. | |
| """ | |
| from __future__ import annotations | |
| import csv | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import xarray as xr | |
| sys.path.insert(0, str(Path(__file__).parent)) | |
| from panel import Panel | |
| ROOT = Path(__file__).resolve().parent.parent | |
| OUT_CSV = ROOT / "data" / "external" / "dcpp_city_annual.csv" | |
| SOURCE = "MPI-ESM1-2-HR" | |
| def catalog_rows(variable: str, member: str, starts: range, source: str = SOURCE) -> list[dict]: | |
| rows = [] | |
| with (ROOT / "data" / "external" / "pangeo_dcpp_subset.csv").open(encoding="utf-8") as f: | |
| for r in csv.DictReader(f): | |
| if (r["source_id"] == source and r["variable_id"] == variable | |
| and r["member_id"] == member | |
| and int(float(r["dcpp_init_year"])) in starts): | |
| rows.append(r) | |
| return sorted(rows, key=lambda r: int(float(r["dcpp_init_year"]))) | |
| def extract(row: dict, panel: Panel) -> pd.DataFrame: | |
| start = int(float(row["dcpp_init_year"])) | |
| ds = xr.open_zarr(row["zstore"], consolidated=True, storage_options={"token": "anon"}) | |
| var = ds[row["variable_id"]] | |
| lat, lon = ds["lat"].to_numpy(), ds["lon"].to_numpy() | |
| ilat = np.abs(lat[None, :] - panel.lat[:, None]).argmin(1) | |
| ilon = np.abs(lon[None, :] - ((panel.lon[:, None] + 360) % 360)).argmin(1) | |
| pts = var.isel(lat=xr.DataArray(ilat), lon=xr.DataArray(ilon)) | |
| arr = pts.compute().to_numpy() # (time, city) | |
| years = pd.to_datetime(pts["time"].values).year.to_numpy() | |
| out = [] | |
| for year in range(start + 1, start + 8): | |
| sel = years == year | |
| if sel.sum() < 12: | |
| continue | |
| out.append({"source": row["source_id"], "variable": row["variable_id"], | |
| "member": row["member_id"], "start": start, | |
| "lead": year - start, "year": year, | |
| **{f"city{i}": float(v) for i, v in enumerate(arr[sel].mean(axis=0))}}) | |
| return pd.DataFrame(out) | |
| def main() -> None: | |
| panel = Panel(ROOT) | |
| # Grid indices depend on the model grid; read once from any dataset. | |
| # (variable, member, starts, priority, source); MPI-ESM1-2-HR has no pr | |
| # in the catalog, so precipitation comes from MIROC6 (also 1960-2018). | |
| jobs = [] | |
| jobs.append(("tas", "r1i1p1f1", range(1960, 2005), 0, SOURCE)) | |
| jobs.append(("tas", "r2i1p1f1", range(1990, 2005), 1, SOURCE)) | |
| jobs.append(("pr", "r1i1p1f1", range(1960, 2005), 2, "MIROC6")) | |
| jobs.append(("tas", "r1i1p1f1", range(2005, 2019), 3, SOURCE)) | |
| jobs.append(("tas", "r2i1p1f1", range(2005, 2019), 4, SOURCE)) | |
| jobs.append(("pr", "r1i1p1f1", range(2005, 2019), 5, "MIROC6")) | |
| done = set() | |
| if OUT_CSV.exists(): | |
| prev = pd.read_csv(OUT_CSV, usecols=["source", "variable", "member", "start"]) | |
| done = set(map(tuple, prev.drop_duplicates().to_numpy())) | |
| total, skipped = 0, 0 | |
| for variable, member, starts, _pri, source in sorted(jobs, key=lambda j: j[3]): | |
| for row in catalog_rows(variable, member, starts, source): | |
| start = int(float(row["dcpp_init_year"])) | |
| if (source, variable, member, start) in done: | |
| skipped += 1 | |
| continue | |
| t0 = time.time() | |
| try: | |
| df = extract(row, panel) | |
| except Exception as exc: | |
| print(f"FAILED {variable} {member} s{start}: {exc}", flush=True) | |
| continue | |
| df.insert(0, "city_ids", ",".join(panel.cities)) | |
| df = df.drop(columns=["city_ids"]) | |
| df.to_csv(OUT_CSV, mode="a", header=not OUT_CSV.exists(), index=False) | |
| total += 1 | |
| print(f"done {variable} {member} s{start} ({time.time() - t0:.0f}s, total {total})", | |
| flush=True) | |
| print(f"finished: {total} new datasets, {skipped} already present -> {OUT_CSV}") | |
| if __name__ == "__main__": | |
| main() | |