Store hourly maps (fields) next to the scores
Browse files- pardig_eval/fields.py +115 -0
- pardig_eval/run.py +104 -71
- pardig_eval/sources.py +8 -3
pardig_eval/fields.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hourly rain maps of a day, both sources at their own resolution, in one zipped Zarr store.
|
| 2 |
+
|
| 3 |
+
``fields/YYYY/MM/YYYY-MM-DD.zarr.zip`` holds
|
| 4 |
+
|
| 5 |
+
* ``pardig`` (time, lat_pardig, lon_pardig): PARDIG-NRT at 0.1° (1801 x 3600), and
|
| 6 |
+
* ``era5`` (time, lat_era5, lon_era5): ERA5 at 0.25° (721 x 1440),
|
| 7 |
+
|
| 8 |
+
hourly depths in mm over ``(time-1h, time]``, ascending latitudes and longitudes 0..360. Values are
|
| 9 |
+
stored as uint16 hundredths of a mm (up to 655.34 mm; 65535 = missing), compressed with zstd, in
|
| 10 |
+
chunks of 1 h x 20° x 20° so a regional map decompresses only what it shows.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import xarray as xr
|
| 20 |
+
|
| 21 |
+
from pardig_eval import grid, regrid
|
| 22 |
+
from pardig_eval.sources import hours
|
| 23 |
+
|
| 24 |
+
SCALE = 0.01
|
| 25 |
+
MISSING = 65535
|
| 26 |
+
MAX_MM = (MISSING - 1) * SCALE
|
| 27 |
+
CHUNK_DEGREES = 20
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def path_for(day) -> str:
|
| 31 |
+
day = pd.Timestamp(day)
|
| 32 |
+
return f"fields/{day:%Y}/{day:%m}/{day:%Y-%m-%d}.zarr.zip"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def dataset(day, pardig: np.ndarray, era5: np.ndarray, era5_source: str = "") -> xr.Dataset:
|
| 36 |
+
"""Both sources' hourly fields for a day as one dataset."""
|
| 37 |
+
if pardig.shape != (24, 1801, 3600) or era5.shape != (24, 721, 1440):
|
| 38 |
+
raise ValueError("expected PARDIG (24, 1801, 3600) and ERA5 (24, 721, 1440) hourly fields")
|
| 39 |
+
attrs = {"units": "mm", "interval": "(time-1h, time]"}
|
| 40 |
+
return xr.Dataset(
|
| 41 |
+
{
|
| 42 |
+
"pardig": (("time", "lat_pardig", "lon_pardig"), pardig, {**attrs, "source": "PARDIG-NRT, gs://pardig_1"}),
|
| 43 |
+
"era5": (("time", "lat_era5", "lon_era5"), era5, {**attrs, "source": era5_source or "ERA5"}),
|
| 44 |
+
},
|
| 45 |
+
coords={
|
| 46 |
+
"time": hours(day),
|
| 47 |
+
"lat_pardig": regrid.PARDIG_LAT,
|
| 48 |
+
"lon_pardig": regrid.PARDIG_LON,
|
| 49 |
+
"lat_era5": grid.LAT,
|
| 50 |
+
"lon_era5": grid.LON,
|
| 51 |
+
},
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _encoding(ds: xr.Dataset) -> dict:
|
| 56 |
+
from zarr.codecs import BloscCodec
|
| 57 |
+
|
| 58 |
+
compressor = BloscCodec(cname="zstd", clevel=5, shuffle="bitshuffle")
|
| 59 |
+
enc = {}
|
| 60 |
+
for name, step in (("pardig", regrid.PARDIG_STEP), ("era5", grid.STEP)):
|
| 61 |
+
size = int(round(CHUNK_DEGREES / step))
|
| 62 |
+
enc[name] = {"dtype": "uint16", "scale_factor": SCALE, "_FillValue": MISSING,
|
| 63 |
+
"chunks": (1, size, size), "compressors": [compressor]}
|
| 64 |
+
return enc
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def write(ds: xr.Dataset, path: Path) -> Path:
|
| 68 |
+
"""Write a day's fields to a zipped Zarr v3 store (values clipped to what uint16 holds)."""
|
| 69 |
+
import shutil
|
| 70 |
+
import tempfile
|
| 71 |
+
import zipfile
|
| 72 |
+
|
| 73 |
+
path = Path(path)
|
| 74 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
clipped = ds.copy()
|
| 76 |
+
for name in ("pardig", "era5"):
|
| 77 |
+
clipped[name] = ds[name].clip(0, MAX_MM)
|
| 78 |
+
# Write a directory store, then zip it once: writing into a ZipStore directly leaves duplicate
|
| 79 |
+
# entries, because the metadata is rewritten while arrays are added. Chunks are compressed already.
|
| 80 |
+
with tempfile.TemporaryDirectory(dir=path.parent) as tmp:
|
| 81 |
+
folder = Path(tmp) / "store.zarr"
|
| 82 |
+
clipped.to_zarr(folder, zarr_format=3, consolidated=False, encoding=_encoding(clipped))
|
| 83 |
+
partial = Path(tmp) / "store.zip"
|
| 84 |
+
with zipfile.ZipFile(partial, "w", compression=zipfile.ZIP_STORED, allowZip64=True) as zf:
|
| 85 |
+
for file in sorted(folder.rglob("*")):
|
| 86 |
+
if file.is_file():
|
| 87 |
+
zf.write(file, file.relative_to(folder).as_posix())
|
| 88 |
+
shutil.move(partial, path)
|
| 89 |
+
return path
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def open_fields(path) -> xr.Dataset:
|
| 93 |
+
"""Open a day's fields lazily (decoded to float mm, NaN where missing)."""
|
| 94 |
+
import zarr
|
| 95 |
+
|
| 96 |
+
store = zarr.storage.ZipStore(Path(path), mode="r")
|
| 97 |
+
return xr.open_zarr(store, consolidated=False, zarr_format=3)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def crop(da: xr.DataArray, lat_min: float, lat_max: float, lon_min: float, lon_max: float) -> xr.DataArray:
|
| 101 |
+
"""A box of a 0..360 field, returned on signed longitudes -180..180 (Greenwich-crossing boxes work)."""
|
| 102 |
+
lat_name, lon_name = (d for d in da.dims if d != "time")
|
| 103 |
+
da = da.sel({lat_name: slice(lat_min, lat_max)})
|
| 104 |
+
lon = da[lon_name].values
|
| 105 |
+
signed = ((lon + 180) % 360) - 180
|
| 106 |
+
lo, hi = ((lon_min + 180) % 360) - 180, ((lon_max + 180) % 360) - 180
|
| 107 |
+
if lon_max - lon_min >= 360:
|
| 108 |
+
keep = np.ones_like(signed, bool)
|
| 109 |
+
elif lo <= hi:
|
| 110 |
+
keep = (signed >= lo) & (signed <= hi)
|
| 111 |
+
else: # crosses the date line: keep both ends, east part shown beyond 180
|
| 112 |
+
keep = (signed >= lo) | (signed <= hi)
|
| 113 |
+
signed = np.where(signed < lo, signed + 360, signed)
|
| 114 |
+
da = da.isel({lon_name: np.flatnonzero(keep)}).assign_coords({lon_name: signed[keep]})
|
| 115 |
+
return da.sortby(lon_name)
|
pardig_eval/run.py
CHANGED
|
@@ -1,11 +1,16 @@
|
|
| 1 |
-
"""Score days of ERA5 against PARDIG and
|
| 2 |
|
| 3 |
python -m pardig_eval.run --start 2026-01-01 --end 2026-01-03 --era5 earthmover,arco \
|
| 4 |
-
--out data --repo EmmaScharfmann/era5-pardig-scores
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
from __future__ import annotations
|
|
@@ -19,10 +24,11 @@ import numpy as np
|
|
| 19 |
import pandas as pd
|
| 20 |
import xarray as xr
|
| 21 |
|
| 22 |
-
from pardig_eval import sums
|
| 23 |
from pardig_eval.sources import ERA5_SOURCES, PARDIG, PARDIG_LIVE_START
|
| 24 |
|
| 25 |
logger = logging.getLogger("pardig_eval")
|
|
|
|
| 26 |
|
| 27 |
|
| 28 |
def month_name(day) -> str:
|
|
@@ -46,62 +52,72 @@ def write(ds: xr.Dataset, path: Path):
|
|
| 46 |
|
| 47 |
|
| 48 |
class Store:
|
| 49 |
-
"""Month files in a local folder, mirrored to a Hub dataset if ``repo`` is given."""
|
| 50 |
|
| 51 |
def __init__(self, out: Path, repo: str | None):
|
| 52 |
-
self.
|
|
|
|
| 53 |
self.dir.mkdir(parents=True, exist_ok=True)
|
| 54 |
self.repo = repo
|
|
|
|
|
|
|
| 55 |
if repo:
|
| 56 |
from huggingface_hub import HfApi
|
| 57 |
|
| 58 |
self.api = HfApi()
|
| 59 |
self.api.create_repo(repo, repo_type="dataset", exist_ok=True)
|
|
|
|
| 60 |
|
| 61 |
def load(self, day) -> xr.Dataset | None:
|
| 62 |
path = self.dir / month_name(day)
|
| 63 |
-
if not path.exists() and self.
|
| 64 |
from huggingface_hub import hf_hub_download
|
| 65 |
-
from huggingface_hub.errors import EntryNotFoundError
|
| 66 |
|
| 67 |
-
|
| 68 |
-
hf_hub_download(self.repo, f"months/{path.name}", repo_type="dataset", local_dir=self.dir.parent)
|
| 69 |
-
except EntryNotFoundError:
|
| 70 |
-
pass
|
| 71 |
if not path.exists():
|
| 72 |
return None
|
| 73 |
with xr.open_dataset(path, engine="h5netcdf") as ds:
|
| 74 |
return ds.load()
|
| 75 |
|
| 76 |
def days(self) -> pd.DatetimeIndex:
|
| 77 |
-
names = sorted(p.name for p in self.dir.glob("*.nc")
|
| 78 |
-
|
| 79 |
-
names = sorted({*names, *(Path(f).name for f in self.api.list_repo_files(self.repo, repo_type="dataset")
|
| 80 |
-
if f.startswith("months/") and f.endswith(".nc"))})
|
| 81 |
if not names:
|
| 82 |
return pd.DatetimeIndex([])
|
| 83 |
ds = self.load(pd.Timestamp(names[-1][:7]))
|
| 84 |
return pd.DatetimeIndex(ds["day"].values) if ds is not None else pd.DatetimeIndex([])
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
def save(self, ds: xr.Dataset, day):
|
| 87 |
"""Write the month file locally; it is pushed by :meth:`push`."""
|
| 88 |
write(ds, self.dir / month_name(day))
|
| 89 |
-
self.pending
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
def push(self):
|
| 92 |
-
"""Upload every
|
| 93 |
-
pending = sorted(
|
| 94 |
if not (self.repo and pending):
|
| 95 |
return
|
| 96 |
from huggingface_hub import CommitOperationAdd
|
| 97 |
|
| 98 |
-
operations = [CommitOperationAdd(
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
logger.info("pushed %s",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
self.pending = set()
|
| 106 |
|
| 107 |
|
|
@@ -114,76 +130,93 @@ def _available(source, day) -> bool:
|
|
| 114 |
return False
|
| 115 |
|
| 116 |
|
| 117 |
-
def
|
|
|
|
| 118 |
t0 = time.perf_counter()
|
| 119 |
f = era5.hourly(day)
|
| 120 |
t1 = time.perf_counter()
|
| 121 |
-
|
| 122 |
t2 = time.perf_counter()
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
|
| 129 |
def main(argv=None):
|
| 130 |
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 131 |
-
parser.add_argument("--start", help="first day (default: the day after the last one
|
| 132 |
parser.add_argument("--end", help="last day (default: the last day both sources have complete)")
|
| 133 |
parser.add_argument("--era5", default="earthmover",
|
| 134 |
help=f"ERA5 sources to try in order for each day, comma-separated, from {sorted(ERA5_SOURCES)};"
|
| 135 |
" e.g. 'earthmover,arco' falls back to ARCO for days Earthmover does not have yet")
|
| 136 |
-
parser.add_argument("--
|
| 137 |
-
parser.add_argument("--
|
| 138 |
-
parser.add_argument("--
|
|
|
|
| 139 |
parser.add_argument("--upload-every", type=int, default=1,
|
| 140 |
-
help="push to the Hub every this many
|
| 141 |
args = parser.parse_args(argv)
|
| 142 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
|
|
| 143 |
|
| 144 |
-
|
| 145 |
names = [n.strip() for n in args.era5.split(",") if n.strip()]
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
| 149 |
era5_sources, pardig = [ERA5_SOURCES[n]() for n in names], PARDIG()
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
| 153 |
end = pd.Timestamp(args.end) if args.end else pd.Timestamp.utcnow().tz_localize(None).normalize()
|
| 154 |
-
|
|
|
|
| 155 |
month, month_key = None, None
|
| 156 |
try:
|
| 157 |
for day in pd.date_range(start, end, freq="D"):
|
| 158 |
-
if month_name(day) != month_key:
|
| 159 |
store.push()
|
| 160 |
month, month_key = store.load(day), month_name(day)
|
| 161 |
-
|
| 162 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
break
|
| 164 |
finally:
|
| 165 |
store.push()
|
| 166 |
-
logger.info("
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
def _one_day(day, month, store, era5_sources, pardig, args, scored):
|
| 170 |
-
"""Score one day into ``month``; returns (scored, month, stop)."""
|
| 171 |
-
if month is not None and np.isin(day.to_datetime64(), month["day"].values):
|
| 172 |
-
logger.info("%s already scored", day.date())
|
| 173 |
-
return scored, month, False
|
| 174 |
-
era5 = next((source for source in era5_sources if _available(source, day)), None)
|
| 175 |
-
if era5 is None or not pardig.available(day):
|
| 176 |
-
if args.end:
|
| 177 |
-
logger.warning("%s: a source is incomplete, skipping", day.date())
|
| 178 |
-
return scored, month, False
|
| 179 |
-
logger.info("%s: a source is incomplete, stopping here", day.date())
|
| 180 |
-
return scored, month, True
|
| 181 |
-
month = sums.add_day(month, score_day(day, era5, pardig))
|
| 182 |
-
store.save(month, day)
|
| 183 |
-
scored += 1
|
| 184 |
-
if scored % args.upload_every == 0:
|
| 185 |
-
store.push()
|
| 186 |
-
return scored, month, bool(args.max_days and scored >= args.max_days)
|
| 187 |
|
| 188 |
|
| 189 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
"""Score days of ERA5 against PARDIG and store their hourly maps, locally and on the Hub.
|
| 2 |
|
| 3 |
python -m pardig_eval.run --start 2026-01-01 --end 2026-01-03 --era5 earthmover,arco \
|
| 4 |
+
--out data --repo EmmaScharfmann/era5-pardig-scores [--what scores,fields]
|
| 5 |
|
| 6 |
+
Two products per day, each skipped when already stored, so the command can be re-run safely
|
| 7 |
+
(one writer per product at a time):
|
| 8 |
+
|
| 9 |
+
* ``scores``: per-tile sums added to ``months/YYYY-MM.nc`` (:mod:`pardig_eval.sums`);
|
| 10 |
+
* ``fields``: hourly maps in ``fields/YYYY/MM/YYYY-MM-DD.zarr.zip`` (:mod:`pardig_eval.fields`).
|
| 11 |
+
|
| 12 |
+
Without ``--start``, resumes after the last day stored; without ``--end``, stops at the last day
|
| 13 |
+
both PARDIG and ERA5 have complete.
|
| 14 |
"""
|
| 15 |
|
| 16 |
from __future__ import annotations
|
|
|
|
| 24 |
import pandas as pd
|
| 25 |
import xarray as xr
|
| 26 |
|
| 27 |
+
from pardig_eval import fields, regrid, sums
|
| 28 |
from pardig_eval.sources import ERA5_SOURCES, PARDIG, PARDIG_LIVE_START
|
| 29 |
|
| 30 |
logger = logging.getLogger("pardig_eval")
|
| 31 |
+
PRODUCTS = ("scores", "fields")
|
| 32 |
|
| 33 |
|
| 34 |
def month_name(day) -> str:
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
class Store:
|
| 55 |
+
"""Month and field files in a local folder, mirrored to a Hub dataset if ``repo`` is given."""
|
| 56 |
|
| 57 |
def __init__(self, out: Path, repo: str | None):
|
| 58 |
+
self.root = Path(out)
|
| 59 |
+
self.dir = self.root / "months"
|
| 60 |
self.dir.mkdir(parents=True, exist_ok=True)
|
| 61 |
self.repo = repo
|
| 62 |
+
self.pending: set[str] = set() # paths relative to root, written since the last push
|
| 63 |
+
self.remote: set[str] = set()
|
| 64 |
if repo:
|
| 65 |
from huggingface_hub import HfApi
|
| 66 |
|
| 67 |
self.api = HfApi()
|
| 68 |
self.api.create_repo(repo, repo_type="dataset", exist_ok=True)
|
| 69 |
+
self.remote = set(self.api.list_repo_files(repo, repo_type="dataset"))
|
| 70 |
|
| 71 |
def load(self, day) -> xr.Dataset | None:
|
| 72 |
path = self.dir / month_name(day)
|
| 73 |
+
if not path.exists() and f"months/{path.name}" in self.remote:
|
| 74 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 75 |
|
| 76 |
+
hf_hub_download(self.repo, f"months/{path.name}", repo_type="dataset", local_dir=self.root)
|
|
|
|
|
|
|
|
|
|
| 77 |
if not path.exists():
|
| 78 |
return None
|
| 79 |
with xr.open_dataset(path, engine="h5netcdf") as ds:
|
| 80 |
return ds.load()
|
| 81 |
|
| 82 |
def days(self) -> pd.DatetimeIndex:
|
| 83 |
+
names = sorted({p.name for p in self.dir.glob("*.nc")} |
|
| 84 |
+
{Path(f).name for f in self.remote if f.startswith("months/") and f.endswith(".nc")})
|
|
|
|
|
|
|
| 85 |
if not names:
|
| 86 |
return pd.DatetimeIndex([])
|
| 87 |
ds = self.load(pd.Timestamp(names[-1][:7]))
|
| 88 |
return pd.DatetimeIndex(ds["day"].values) if ds is not None else pd.DatetimeIndex([])
|
| 89 |
|
| 90 |
+
def has_fields(self, day) -> bool:
|
| 91 |
+
rel = fields.path_for(day)
|
| 92 |
+
return rel in self.remote or (self.root / rel).exists()
|
| 93 |
+
|
| 94 |
def save(self, ds: xr.Dataset, day):
|
| 95 |
"""Write the month file locally; it is pushed by :meth:`push`."""
|
| 96 |
write(ds, self.dir / month_name(day))
|
| 97 |
+
self.pending.add(f"months/{month_name(day)}")
|
| 98 |
+
|
| 99 |
+
def save_fields(self, ds: xr.Dataset, day):
|
| 100 |
+
fields.write(ds, self.root / fields.path_for(day))
|
| 101 |
+
self.pending.add(fields.path_for(day))
|
| 102 |
|
| 103 |
def push(self):
|
| 104 |
+
"""Upload every file written since the last push, in one commit; field files are then deleted locally."""
|
| 105 |
+
pending = sorted(self.pending)
|
| 106 |
if not (self.repo and pending):
|
| 107 |
return
|
| 108 |
from huggingface_hub import CommitOperationAdd
|
| 109 |
|
| 110 |
+
operations = [CommitOperationAdd(rel, self.root / rel) for rel in pending]
|
| 111 |
+
days = sorted(Path(rel).name[:10] for rel in pending if rel.startswith("fields/"))
|
| 112 |
+
months = [Path(rel).stem for rel in pending if rel.startswith("months/")]
|
| 113 |
+
what = ", ".join(filter(None, [f"scores {', '.join(months)}" if months else "",
|
| 114 |
+
f"maps {days[0]}..{days[-1]}" if days else ""]))
|
| 115 |
+
self.api.create_commit(self.repo, operations, repo_type="dataset", commit_message=f"Add {what}")
|
| 116 |
+
logger.info("pushed %s", what)
|
| 117 |
+
self.remote.update(pending)
|
| 118 |
+
for rel in pending:
|
| 119 |
+
if rel.startswith("fields/"):
|
| 120 |
+
(self.root / rel).unlink(missing_ok=True)
|
| 121 |
self.pending = set()
|
| 122 |
|
| 123 |
|
|
|
|
| 130 |
return False
|
| 131 |
|
| 132 |
|
| 133 |
+
def process_day(day, era5, pardig, store: Store, month: xr.Dataset | None, what: set[str]):
|
| 134 |
+
"""Read both sources once and write what is missing; returns the updated month."""
|
| 135 |
t0 = time.perf_counter()
|
| 136 |
f = era5.hourly(day)
|
| 137 |
t1 = time.perf_counter()
|
| 138 |
+
fine = pardig.hourly_fine(day)
|
| 139 |
t2 = time.perf_counter()
|
| 140 |
+
timing = [f"ERA5 {t1 - t0:.0f}s", f"PARDIG {t2 - t1:.0f}s"]
|
| 141 |
+
if "fields" in what:
|
| 142 |
+
store.save_fields(fields.dataset(day, fine, f, era5.name), day)
|
| 143 |
+
t3 = time.perf_counter()
|
| 144 |
+
timing.append(f"maps {t3 - t2:.0f}s")
|
| 145 |
+
t2 = t3
|
| 146 |
+
if "scores" in what:
|
| 147 |
+
o = regrid.to_era5_grid(fine)
|
| 148 |
+
del fine
|
| 149 |
+
month = sums.add_day(month, sums.as_month(sums.day_sums(f, o), day, era5.name, era5.preliminary(day)))
|
| 150 |
+
store.save(month, day)
|
| 151 |
+
timing.append(f"scores {time.perf_counter() - t2:.0f}s")
|
| 152 |
+
logger.info("%s (%s): %s", pd.Timestamp(day).date(), era5.name, ", ".join(timing))
|
| 153 |
+
return month
|
| 154 |
|
| 155 |
|
| 156 |
def main(argv=None):
|
| 157 |
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 158 |
+
parser.add_argument("--start", help="first day (default: the day after the last one with scores)")
|
| 159 |
parser.add_argument("--end", help="last day (default: the last day both sources have complete)")
|
| 160 |
parser.add_argument("--era5", default="earthmover",
|
| 161 |
help=f"ERA5 sources to try in order for each day, comma-separated, from {sorted(ERA5_SOURCES)};"
|
| 162 |
" e.g. 'earthmover,arco' falls back to ARCO for days Earthmover does not have yet")
|
| 163 |
+
parser.add_argument("--what", default="scores,fields", help=f"products to write, from {list(PRODUCTS)}")
|
| 164 |
+
parser.add_argument("--out", default="data", help="local working folder")
|
| 165 |
+
parser.add_argument("--repo", help="Hub dataset to read and push files, e.g. user/era5-pardig-scores")
|
| 166 |
+
parser.add_argument("--max-days", type=int, default=None, help="stop after this many processed days")
|
| 167 |
parser.add_argument("--upload-every", type=int, default=1,
|
| 168 |
+
help="push to the Hub every this many processed days (and when a month ends, and at the end)")
|
| 169 |
args = parser.parse_args(argv)
|
| 170 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 171 |
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
| 172 |
|
| 173 |
+
what = {w.strip() for w in args.what.split(",") if w.strip()}
|
| 174 |
names = [n.strip() for n in args.era5.split(",") if n.strip()]
|
| 175 |
+
if not what or what - set(PRODUCTS):
|
| 176 |
+
parser.error(f"--what takes {list(PRODUCTS)}")
|
| 177 |
+
if not names or set(names) - set(ERA5_SOURCES):
|
| 178 |
+
parser.error(f"--era5 takes {sorted(ERA5_SOURCES)}")
|
| 179 |
+
|
| 180 |
+
store = Store(Path(args.out), args.repo)
|
| 181 |
era5_sources, pardig = [ERA5_SOURCES[n]() for n in names], PARDIG()
|
| 182 |
+
if args.start:
|
| 183 |
+
start = pd.Timestamp(args.start)
|
| 184 |
+
else:
|
| 185 |
+
done = store.days()
|
| 186 |
+
start = done[-1] + pd.Timedelta(days=1) if len(done) else PARDIG_LIVE_START
|
| 187 |
end = pd.Timestamp(args.end) if args.end else pd.Timestamp.utcnow().tz_localize(None).normalize()
|
| 188 |
+
|
| 189 |
+
processed = 0
|
| 190 |
month, month_key = None, None
|
| 191 |
try:
|
| 192 |
for day in pd.date_range(start, end, freq="D"):
|
| 193 |
+
if "scores" in what and month_name(day) != month_key:
|
| 194 |
store.push()
|
| 195 |
month, month_key = store.load(day), month_name(day)
|
| 196 |
+
todo = set(what)
|
| 197 |
+
if "scores" in todo and month is not None and np.isin(day.to_datetime64(), month["day"].values):
|
| 198 |
+
todo.discard("scores")
|
| 199 |
+
if "fields" in todo and store.has_fields(day):
|
| 200 |
+
todo.discard("fields")
|
| 201 |
+
if not todo:
|
| 202 |
+
logger.info("%s already stored", day.date())
|
| 203 |
+
continue
|
| 204 |
+
era5 = next((source for source in era5_sources if _available(source, day)), None)
|
| 205 |
+
if era5 is None or not pardig.available(day):
|
| 206 |
+
if args.end:
|
| 207 |
+
logger.warning("%s: a source is incomplete, skipping", day.date())
|
| 208 |
+
continue
|
| 209 |
+
logger.info("%s: a source is incomplete, stopping here", day.date())
|
| 210 |
+
break
|
| 211 |
+
month = process_day(day, era5, pardig, store, month, todo)
|
| 212 |
+
processed += 1
|
| 213 |
+
if processed % args.upload_every == 0:
|
| 214 |
+
store.push()
|
| 215 |
+
if args.max_days and processed >= args.max_days:
|
| 216 |
break
|
| 217 |
finally:
|
| 218 |
store.push()
|
| 219 |
+
logger.info("processed %d day(s)", processed)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
|
| 222 |
if __name__ == "__main__":
|
pardig_eval/sources.py
CHANGED
|
@@ -97,14 +97,19 @@ class PARDIG:
|
|
| 97 |
raise ValueError(f"unexpected PARDIG dimensions {dims} at {t}")
|
| 98 |
return values * 1000.0 # mm/h
|
| 99 |
|
| 100 |
-
def
|
|
|
|
| 101 |
stamps = self.stamps(day)
|
| 102 |
fine = np.zeros((24, 1801, 3600), dtype=np.float32)
|
| 103 |
with concurrent.futures.ThreadPoolExecutor(self.workers) as pool:
|
| 104 |
for i, rate in enumerate(pool.map(self._rate, stamps)):
|
| 105 |
fine[i // 4] += 0.25 * rate # NaN stays NaN
|
| 106 |
-
logger.info("PARDIG %s read
|
| 107 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
class ERA5:
|
|
|
|
| 97 |
raise ValueError(f"unexpected PARDIG dimensions {dims} at {t}")
|
| 98 |
return values * 1000.0 # mm/h
|
| 99 |
|
| 100 |
+
def hourly_fine(self, day) -> np.ndarray:
|
| 101 |
+
"""Hourly depths (24, 1801, 3600) in mm on PARDIG's own 0.1° grid."""
|
| 102 |
stamps = self.stamps(day)
|
| 103 |
fine = np.zeros((24, 1801, 3600), dtype=np.float32)
|
| 104 |
with concurrent.futures.ThreadPoolExecutor(self.workers) as pool:
|
| 105 |
for i, rate in enumerate(pool.map(self._rate, stamps)):
|
| 106 |
fine[i // 4] += 0.25 * rate # NaN stays NaN
|
| 107 |
+
logger.info("PARDIG %s read", pd.Timestamp(day).date())
|
| 108 |
+
return fine
|
| 109 |
+
|
| 110 |
+
def hourly(self, day) -> np.ndarray:
|
| 111 |
+
"""Hourly depths regridded conservatively to ERA5's 0.25° grid."""
|
| 112 |
+
return regrid.to_era5_grid(self.hourly_fine(day))
|
| 113 |
|
| 114 |
|
| 115 |
class ERA5:
|