EmmaScharfmann HF Staff
IMERG: retry NASA 5xx/network errors, skip a failed day instead of stopping
9d0feef verified Download pardig_eval/sources.py from EmmaScharfmann/visualizing-different-rain-maps: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/spaces/EmmaScharfmann/visualizing-different-rain-maps/resolve/main/pardig_eval/sources.py
- Command line
-
hf download hf://spaces/EmmaScharfmann/visualizing-different-rain-maps/pardig_eval/sources.py
-
curl -L -o sources.py https://huggingface.co/spaces/EmmaScharfmann/visualizing-different-rain-maps/resolve/main/pardig_eval/sources.py
16.4 kB
| """Hourly global rainfall for one UTC day, from PARDIG-NRT and from ERA5. | |
| A day ``D`` is the 24 hours ending at ``D 01:00`` ... ``D+1 00:00`` UTC, each value the depth in | |
| mm over ``(t-1h, t]``: ERA5's own convention for ``tp``. Every reader returns | |
| ``(24, 721, 1440)`` float32 on the grid of :mod:`pardig_eval.grid`. | |
| ERA5 comes from Earthmover (default, fastest) or from Google's public ARCO copy (no account), | |
| behind the same interface: ``available(day)`` and ``hourly(day)``. Add a source by adding a | |
| class with those two methods to :data:`ERA5_SOURCES`. | |
| """ | |
| from __future__ import annotations | |
| import concurrent.futures | |
| import logging | |
| import os | |
| import numpy as np | |
| import pandas as pd | |
| import xarray as xr | |
| from pardig_eval import grid, regrid | |
| logger = logging.getLogger(__name__) | |
| PARDIG_BUCKET = "pardig_1" | |
| #: From 2026 on, one Zarr store per 15-minute timestamp, written next to a ``success`` marker. | |
| PARDIG_LIVE = "NRT/zarr/2026_to_present" | |
| PARDIG_LIVE_START = pd.Timestamp("2026-01-01") | |
| #: PARDIG caps instantaneous rates at 75 mm/h. | |
| PARDIG_CAP_MM_H = 75.0 | |
| def hours(day) -> pd.DatetimeIndex: | |
| """The 24 interval ends of a UTC day.""" | |
| day = pd.Timestamp(day).normalize() | |
| return pd.date_range(day + pd.Timedelta(hours=1), periods=24, freq="h") | |
| def _gcs(prefix: str = ""): | |
| from obstore.store import GCSStore | |
| return GCSStore(PARDIG_BUCKET, prefix=prefix or None, skip_signature=True) | |
| class PARDIG: | |
| """PARDIG-NRT hourly depth (paper Eq. A.3.8), regridded conservatively to 0.25°. | |
| The hour ending at ``t`` is 0.25 h x (rate at t-45, t-30, t-15 and t min), in mm. | |
| """ | |
| name = "PARDIG-NRT" | |
| def __init__(self, workers: int = 16): | |
| self.workers = workers | |
| def stamps(day) -> pd.DatetimeIndex: | |
| day = pd.Timestamp(day).normalize() | |
| return pd.date_range(day + pd.Timedelta(minutes=15), periods=96, freq="15min") | |
| def available(self, day) -> bool: | |
| """True when all 96 quarter-hour stores of the day have their success marker.""" | |
| day = pd.Timestamp(day).normalize() | |
| if day < PARDIG_LIVE_START: | |
| raise NotImplementedError("only the 2026-onward PARDIG stores are wired in") | |
| store = _gcs() | |
| def present(t): | |
| try: | |
| store.head(f"{PARDIG_LIVE}/{t:%Y%m%dT%H%M%S}/success") | |
| return True | |
| except FileNotFoundError: | |
| return False | |
| with concurrent.futures.ThreadPoolExecutor(self.workers) as pool: | |
| missing = [t for t, ok in zip(self.stamps(day), pool.map(present, self.stamps(day))) if not ok] | |
| if missing: | |
| logger.info("PARDIG %s: %d of 96 timestamps missing", day.date(), len(missing)) | |
| return not missing | |
| def _rate(self, t: pd.Timestamp) -> np.ndarray: | |
| import zarr | |
| store = zarr.storage.ObjectStore(_gcs(f"{PARDIG_LIVE}/{t:%Y%m%dT%H%M%S}/predictions.zarr"), read_only=True) | |
| group = zarr.open_group(store, mode="r") | |
| rate = group["precipitation"] | |
| if rate.attrs.get("units") not in ("m h**-1", "m/h"): | |
| raise ValueError(f"unexpected PARDIG units {rate.attrs.get('units')!r} at {t}") | |
| lat = group["latitude"][:] | |
| lon = group["longitude"][:] | |
| if not (np.allclose(lat, regrid.PARDIG_LAT) and np.allclose(lon, regrid.PARDIG_LON)): | |
| raise ValueError(f"PARDIG grid changed at {t}") | |
| dims = rate.metadata.dimension_names | |
| values = np.asarray(rate[...], dtype=np.float32).squeeze() | |
| if dims and [d for d in dims if d not in ("time",)] != ["latitude", "longitude"]: | |
| raise ValueError(f"unexpected PARDIG dimensions {dims} at {t}") | |
| return values * 1000.0 # mm/h | |
| def hourly_fine(self, day) -> np.ndarray: | |
| """Hourly depths (24, 1801, 3600) in mm on PARDIG's own 0.1° grid.""" | |
| stamps = self.stamps(day) | |
| fine = np.zeros((24, 1801, 3600), dtype=np.float32) | |
| with concurrent.futures.ThreadPoolExecutor(self.workers) as pool: | |
| for i, rate in enumerate(pool.map(self._rate, stamps)): | |
| fine[i // 4] += 0.25 * rate # NaN stays NaN | |
| logger.info("PARDIG %s read", pd.Timestamp(day).date()) | |
| return fine | |
| def hourly(self, day) -> np.ndarray: | |
| """Hourly depths regridded conservatively to ERA5's 0.25° grid.""" | |
| return regrid.to_era5_grid(self.hourly_fine(day)) | |
| class ERA5: | |
| """Shared logic: open a store lazily, select 24 hours of ``tp`` and put them on the scoring grid.""" | |
| name = "ERA5" | |
| variables = ("tp", "total_precipitation") | |
| #: Final ERA5 ends here in the store; later hours are the preliminary ERA5T (may be revised). | |
| final_until: pd.Timestamp | None = None | |
| def __init__(self): | |
| self._ds = None | |
| def open(self) -> xr.Dataset: # pragma: no cover - network | |
| raise NotImplementedError | |
| def ds(self) -> xr.Dataset: | |
| if self._ds is None: | |
| ds = self.open() | |
| ds = ds.rename({k: v for k, v in {"valid_time": "time", "latitude": "lat", "longitude": "lon"}.items() | |
| if k in ds.dims or k in ds.coords}) | |
| self._ds = ds | |
| return self._ds | |
| def tp(self) -> xr.DataArray: | |
| name = next((v for v in self.variables if v in self.ds), None) | |
| if name is None: | |
| raise KeyError(f"none of {self.variables} in {sorted(self.ds.data_vars)}") | |
| return self.ds[name] | |
| def available(self, day) -> bool: | |
| """True when the store holds all 24 hours and the last one is filled.""" | |
| times = hours(day) | |
| index = self.ds.get_index("time") | |
| if not index.isin(times).sum() == 24: | |
| return False | |
| last = self.tp.sel(time=times[-1]).isel(lat=slice(0, None, 60), lon=slice(0, None, 60)).values | |
| return bool(np.isfinite(last).all()) | |
| def preliminary(self, day) -> bool: | |
| return self.final_until is not None and hours(day)[-1] > self.final_until | |
| def hourly(self, day) -> np.ndarray: | |
| da = self.tp.sel(time=hours(day)).load() | |
| units = da.attrs.get("units", "m") | |
| if units not in ("m", "metres", "meters"): | |
| raise ValueError(f"unexpected ERA5 tp units {units!r}") | |
| lat = da["lat"].values | |
| lon = da["lon"].values % 360 | |
| if lat[0] > lat[-1]: | |
| da = da.isel(lat=slice(None, None, -1)) | |
| lat = lat[::-1] | |
| order = np.argsort(lon) | |
| da = da.isel(lon=order) | |
| if not (np.allclose(lat, grid.LAT) and np.allclose(lon[order], grid.LON)): | |
| raise ValueError("ERA5 is not on the regular 0.25° grid") | |
| # ERA5 accumulations carry tiny negative values from GRIB packing. | |
| return np.clip(da.transpose("time", "lat", "lon").values.astype(np.float32) * 1000.0, 0, None) | |
| class ERA5Earthmover(ERA5): | |
| """ERA5 from Earthmover, ``earthmover-public/era5`` (one global field per chunk). | |
| Needs an account: ``arraylake auth login`` or ``ARRAYLAKE_TOKEN``. | |
| """ | |
| name = "ERA5 (Earthmover)" | |
| repo = "earthmover-public/era5" | |
| group = "single/spatial" | |
| def open(self) -> xr.Dataset: | |
| from arraylake import Client | |
| token = os.environ.get("ARRAYLAKE_TOKEN") | |
| client = Client(token=token) if token else Client() | |
| session = client.get_repo(self.repo).readonly_session(branch="main") | |
| return xr.open_zarr(session.store, group=self.group, consolidated=False, chunks=None) | |
| class ERA5ARCO(ERA5): | |
| """ERA5 from Google's public ARCO store (no account), updated with ERA5T a few days behind real time.""" | |
| name = "ERA5 (ARCO)" | |
| url = "gcp-public-data-arco-era5/ar/full_37-1h-0p25deg-chunk-1.zarr-v3" | |
| def open(self) -> xr.Dataset: | |
| import zarr | |
| from obstore.store import GCSStore | |
| bucket, prefix = self.url.split("/", 1) | |
| store = zarr.storage.ObjectStore(GCSStore(bucket, prefix=prefix, skip_signature=True), read_only=True) | |
| ds = xr.open_zarr(store, chunks=None) | |
| stop = ds.attrs.get("valid_time_stop") | |
| self.final_until = pd.Timestamp(stop) + pd.Timedelta(hours=23) if stop else None | |
| return ds[["total_precipitation"]] | |
| ERA5_SOURCES = {"earthmover": ERA5Earthmover, "arco": ERA5ARCO} | |
| # --------------------------------------------------------------------------- | |
| # IMERG (NASA GPM), half-hourly at 0.1°, from GES DISC | |
| # --------------------------------------------------------------------------- | |
| #: NASA's catalogue: finds each half-hour file and its download link (Earthdata Cloud, GES DISC). | |
| CMR = "https://cmr.earthdata.nasa.gov/search/granules.json" | |
| #: Runs in order of preference, as (label, CMR short name, version). Final V07 ends on 2025-09-30 (Final | |
| #: moves to V08), so 2026 comes from Late V07 (~14 h behind) until Final V08 is published. | |
| IMERG_RUNS = { | |
| "final": ("Final", "GPM_3IMERGHH", "07"), | |
| "late": ("Late", "GPM_3IMERGHHL", "07"), | |
| } | |
| class IMERG: | |
| """One IMERG run (Final or Late) as hourly depths on its own 0.1° grid. | |
| Files are half-hourly (``S000000-E002959`` = rate in mm/h averaged over 00:00-00:30). The hour ending at | |
| ``t`` is 0.5 h x (the rates of the half-hours starting at t-60 and t-30 min), in mm, so a UTC day needs the | |
| 48 files of that day. The HDF5 grid is (time, lon, lat) with longitudes -180..180: it is transposed and | |
| rolled to ascending latitudes and longitudes 0..360 (:data:`pardig_eval.regrid.IMERG_LAT`/``IMERG_LON``). | |
| Searching the catalogue is anonymous; downloading needs a NASA Earthdata token in ``EARTHDATA_TOKEN``, from an | |
| account that has approved the GES DISC application. | |
| """ | |
| def __init__(self, run: str = "late", workers: int = 8): | |
| self.run = run | |
| self.label, self.short_name, self.collection_version = IMERG_RUNS[run] | |
| self.workers = workers | |
| self._listing: dict[pd.Timestamp, dict[pd.Timestamp, str]] = {} | |
| self.version = "" | |
| def name(self) -> str: | |
| return f"IMERG {self.label} {self.version}".strip() | |
| def _client(self): | |
| import httpx | |
| return httpx.Client(timeout=120, follow_redirects=False) | |
| def files(self, day) -> dict[pd.Timestamp, str]: | |
| """Half-hour start -> HTTPS download link for the day (the latest file version, e.g. V07C over V07B).""" | |
| import re | |
| day = pd.Timestamp(day).normalize() | |
| if day in self._listing: | |
| return self._listing[day] | |
| params = {"short_name": self.short_name, "version": self.collection_version, "page_size": 200, | |
| "temporal": f"{day:%Y-%m-%dT00:00:00Z},{day:%Y-%m-%dT23:59:59Z}"} | |
| with self._client() as client: | |
| r = client.get(CMR, params=params) | |
| r.raise_for_status() | |
| pattern = re.compile(r"\.(\d{8})-S(\d{6})-E\d{6}\.\d{4}\.(V\w+)\.HDF5$") | |
| found: dict[pd.Timestamp, tuple[str, str]] = {} | |
| for granule in r.json()["feed"]["entry"]: | |
| href = next((link["href"] for link in granule.get("links", []) | |
| if link["href"].startswith("https://") and link["href"].endswith(".HDF5") | |
| and link.get("rel", "").endswith("/data#")), None) | |
| match = pattern.search(href or "") | |
| if not match: | |
| continue | |
| start = pd.Timestamp(f"{match[1]}T{match[2]}") | |
| if start.normalize() == day and (start not in found or match[3] > found[start][1]): | |
| found[start] = (href, match[3]) | |
| out = {t: href for t, (href, _) in sorted(found.items())} | |
| if len(out) == 48: # only cache complete days: a partial one may still fill up | |
| self._listing[day] = out | |
| return out | |
| def available(self, day) -> bool: | |
| day = pd.Timestamp(day).normalize() | |
| wanted = pd.date_range(day, periods=48, freq="30min") | |
| files = self.files(day) | |
| missing = [t for t in wanted if t not in files] | |
| if missing: | |
| logger.info("%s %s: %d of 48 half-hours missing", self.label, day.date(), len(missing)) | |
| return not missing | |
| def _download(self, client, url: str) -> bytes: | |
| """GET with the Earthdata token, following the Earthdata Login redirects by hand (httpx drops the | |
| Authorization header on cross-host redirects).""" | |
| token = os.environ.get("EARTHDATA_TOKEN") | |
| if not token: | |
| raise RuntimeError("set EARTHDATA_TOKEN (urs.earthdata.nasa.gov -> Generate Token) to download IMERG") | |
| headers = {"Authorization": f"Bearer {token}"} | |
| for _ in range(6): | |
| r = self._get_retrying(client, url, headers) | |
| if r.is_redirect: | |
| url = str(r.next_request.url) | |
| host = r.next_request.url.host | |
| headers = {"Authorization": f"Bearer {token}"} if host.endswith("nasa.gov") else {} | |
| continue | |
| if r.status_code in (401, 403): | |
| raise RuntimeError(f"Earthdata refused {url}: {r.text[:300]} (approve the GES DISC application " | |
| "and its EULA in your Earthdata profile; check EARTHDATA_TOKEN has not expired)") | |
| r.raise_for_status() | |
| if r.content[:8] != b"\x89HDF\r\n\x1a\n": | |
| raise RuntimeError(f"not an HDF5 file from {url} (Earthdata token rejected?)") | |
| return r.content | |
| raise RuntimeError(f"too many redirects for {url}") | |
| def _get_retrying(client, url: str, headers: dict, attempts: int = 6): | |
| """GET, retrying network errors and 429/5xx answers (GES DISC returns the odd 502) with backoff.""" | |
| import time | |
| import httpx | |
| for attempt in range(attempts): | |
| try: | |
| r = client.get(url, headers=headers) | |
| if r.status_code != 429 and r.status_code < 500: | |
| return r | |
| problem = f"HTTP {r.status_code}" | |
| except httpx.TransportError as exc: | |
| problem = repr(exc) | |
| if attempt == attempts - 1: | |
| break | |
| wait = min(5 * 2 ** attempt, 120) | |
| logger.info("%s on %s, retrying in %ds", problem, url.rsplit("/", 1)[-1], wait) | |
| time.sleep(wait) | |
| raise RuntimeError(f"giving up on {url} after {attempts} attempts: {problem}") | |
| def read_rate(data: bytes) -> np.ndarray: | |
| """Half-hourly rate (1800, 3600) in mm/h on ascending latitudes, longitudes 0..360, NaN where missing.""" | |
| import io | |
| import h5py | |
| with h5py.File(io.BytesIO(data), "r") as f: | |
| grid_ = f["Grid"] | |
| rate = grid_["precipitation"] | |
| units = rate.attrs.get("units", b"") | |
| units = units.decode() if isinstance(units, bytes) else str(units) | |
| if units not in ("mm/hr", "mm/h"): | |
| raise ValueError(f"unexpected IMERG units {units!r}") | |
| if rate.shape != (1, 3600, 1800): # (time, lon, lat): unambiguous since lon has twice lat's size | |
| raise ValueError(f"unexpected IMERG shape {rate.shape}") | |
| lat, lon = grid_["lat"][:], grid_["lon"][:] | |
| values = rate[0].astype(np.float32) | |
| if not (np.allclose(lat, regrid.IMERG_LAT) and np.allclose(lon, np.sort(((regrid.IMERG_LON + 180) % 360) - 180))): | |
| raise ValueError("IMERG grid changed") | |
| values[values < 0] = np.nan # fill value -9999.9 | |
| return np.roll(values.T, -1800, axis=1) # (lat, lon from 0.05) | |
| def hourly_fine(self, day) -> np.ndarray: | |
| """Hourly depths (24, 1800, 3600) in mm on IMERG's 0.1° grid.""" | |
| day = pd.Timestamp(day).normalize() | |
| files = self.files(day) | |
| urls = [files[t] for t in pd.date_range(day, periods=48, freq="30min")] | |
| self.version = "/".join(sorted({u.rsplit(".", 2)[-2] for u in urls})) # e.g. V07B | |
| fine = np.zeros((24, 1800, 3600), dtype=np.float32) | |
| with self._client() as client, concurrent.futures.ThreadPoolExecutor(self.workers) as pool: | |
| for i, rate in enumerate(pool.map(lambda u: self.read_rate(self._download(client, u)), urls)): | |
| fine[i // 2] += 0.5 * rate # NaN stays NaN | |
| logger.info("%s %s read", self.name, day.date()) | |
| return fine | |
| def hourly(self, day) -> np.ndarray: | |
| return regrid.to_era5_grid(self.hourly_fine(day), "imerg") | |