File size: 16,387 Bytes
9ac2fa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06dc5fa
 
9ac2fa1
 
 
 
 
06dc5fa
 
 
 
 
 
9ac2fa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2621a72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0feef
2621a72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d0feef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2621a72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
"""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

    @staticmethod
    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

    @property
    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

    @property
    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 = ""

    @property
    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}")

    @staticmethod
    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}")

    @staticmethod
    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")