"""Hourly rain maps of a day, both sources at their own resolution, in one zipped Zarr store. ``fields/YYYY/MM/YYYY-MM-DD.zarr.zip`` holds * ``pardig`` (time, lat_pardig, lon_pardig): PARDIG-NRT at 0.1° (1801 x 3600), and * ``era5`` (time, lat_era5, lon_era5): ERA5 at 0.25° (721 x 1440); ``pardig/YYYY/MM/YYYY-MM-DD.zarr.zip`` holds ``pardig`` alone, written as soon as PARDIG has the day (the Space reads PARDIG from here, so it does not wait for ERA5). ``imerg/YYYY/MM/YYYY-MM-DD.zarr.zip`` holds ``imerg`` (time, lat_imerg, lon_imerg): IMERG at 0.1° (1800 x 3600, cell centres at .05°), its run and version in the ``imerg_run`` attribute. Both files store hourly depths in mm over ``(time-1h, time]``, ascending latitudes and longitudes 0..360. Values are stored as uint16 hundredths of a mm (up to 655.34 mm; 65535 = missing), compressed with zstd, in chunks of 1 h x 20° x 20° so a regional map decompresses only what it shows. """ from __future__ import annotations from pathlib import Path import numpy as np import pandas as pd import xarray as xr from pardig_eval import grid, regrid from pardig_eval.sources import hours SCALE = 0.01 MISSING = 65535 MAX_MM = (MISSING - 1) * SCALE CHUNK_DEGREES = 20 def path_for(day, source: str = "fields") -> str: """``fields/...`` holds ERA5 and PARDIG; ``imerg/...`` holds IMERG, same layout and encoding.""" day = pd.Timestamp(day) return f"{source}/{day:%Y}/{day:%m}/{day:%Y-%m-%d}.zarr.zip" def imerg_dataset(day, imerg: np.ndarray, name: str = "IMERG") -> xr.Dataset: """IMERG's hourly fields for a day on its own 0.1° grid (cell centres at .05°).""" if imerg.shape != (24, 1800, 3600): raise ValueError("expected IMERG (24, 1800, 3600) hourly fields") attrs = {"units": "mm", "interval": "(time-1h, time]", "source": f"{name}, NASA GES DISC"} return xr.Dataset( {"imerg": (("time", "lat_imerg", "lon_imerg"), imerg, attrs)}, coords={"time": hours(day), "lat_imerg": regrid.IMERG_LAT, "lon_imerg": regrid.IMERG_LON}, attrs={"imerg_run": name}, ) def pardig_dataset(day, pardig: np.ndarray, name: str = "PARDIG-NRT") -> xr.Dataset: """PARDIG's hourly fields for a day on its own 0.1° grid, on their own (``pardig/`` folder).""" if pardig.shape != (24, 1801, 3600): raise ValueError("expected PARDIG (24, 1801, 3600) hourly fields") attrs = {"units": "mm", "interval": "(time-1h, time]", "source": f"{name}, gs://pardig_1"} return xr.Dataset( {"pardig": (("time", "lat_pardig", "lon_pardig"), pardig, attrs)}, coords={"time": hours(day), "lat_pardig": regrid.PARDIG_LAT, "lon_pardig": regrid.PARDIG_LON}, ) def dataset(day, pardig: np.ndarray, era5: np.ndarray, era5_source: str = "") -> xr.Dataset: """Both sources' hourly fields for a day as one dataset.""" if pardig.shape != (24, 1801, 3600) or era5.shape != (24, 721, 1440): raise ValueError("expected PARDIG (24, 1801, 3600) and ERA5 (24, 721, 1440) hourly fields") attrs = {"units": "mm", "interval": "(time-1h, time]"} return xr.Dataset( { "pardig": (("time", "lat_pardig", "lon_pardig"), pardig, {**attrs, "source": "PARDIG-NRT, gs://pardig_1"}), "era5": (("time", "lat_era5", "lon_era5"), era5, {**attrs, "source": era5_source or "ERA5"}), }, coords={ "time": hours(day), "lat_pardig": regrid.PARDIG_LAT, "lon_pardig": regrid.PARDIG_LON, "lat_era5": grid.LAT, "lon_era5": grid.LON, }, ) def _encoding(ds: xr.Dataset) -> dict: from zarr.codecs import BloscCodec compressor = BloscCodec(cname="zstd", clevel=5, shuffle="bitshuffle") enc = {} steps = {"pardig": regrid.PARDIG_STEP, "era5": grid.STEP, "imerg": regrid.IMERG_STEP} for name in ds.data_vars: step = steps[name] size = int(round(CHUNK_DEGREES / step)) enc[name] = {"dtype": "uint16", "scale_factor": SCALE, "_FillValue": MISSING, "chunks": (1, size, size), "compressors": [compressor]} return enc def write(ds: xr.Dataset, path: Path) -> Path: """Write a day's fields to a zipped Zarr v3 store (values clipped to what uint16 holds).""" import shutil import tempfile import zipfile path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) clipped = ds.copy() for name in ds.data_vars: clipped[name] = ds[name].clip(0, MAX_MM) # Write a directory store, then zip it once: writing into a ZipStore directly leaves duplicate # entries, because the metadata is rewritten while arrays are added. Chunks are compressed already. with tempfile.TemporaryDirectory(dir=path.parent) as tmp: folder = Path(tmp) / "store.zarr" clipped.to_zarr(folder, zarr_format=3, consolidated=False, encoding=_encoding(clipped)) partial = Path(tmp) / "store.zip" with zipfile.ZipFile(partial, "w", compression=zipfile.ZIP_STORED, allowZip64=True) as zf: for file in sorted(folder.rglob("*")): if file.is_file(): zf.write(file, file.relative_to(folder).as_posix()) shutil.move(partial, path) return path def open_fields(path) -> xr.Dataset: """Open a day's fields lazily (decoded to float mm, NaN where missing).""" import zarr store = zarr.storage.ZipStore(Path(path), mode="r") return xr.open_zarr(store, consolidated=False, zarr_format=3) def crop(da: xr.DataArray, lat_min: float, lat_max: float, lon_min: float, lon_max: float) -> xr.DataArray: """A box of a 0..360 field, returned on signed longitudes -180..180 (Greenwich-crossing boxes work).""" lat_name, lon_name = (d for d in da.dims if d != "time") da = da.sel({lat_name: slice(lat_min, lat_max)}) lon = da[lon_name].values signed = ((lon + 180) % 360) - 180 lo, hi = ((lon_min + 180) % 360) - 180, ((lon_max + 180) % 360) - 180 if lon_max - lon_min >= 360: keep = np.ones_like(signed, bool) elif lo <= hi: keep = (signed >= lo) & (signed <= hi) else: # crosses the date line: keep both ends, east part shown beyond 180 keep = (signed >= lo) | (signed <= hi) signed = np.where(signed < lo, signed + 360, signed) da = da.isel({lon_name: np.flatnonzero(keep)}).assign_coords({lon_name: signed[keep]}) return da.sortby(lon_name)