EmmaScharfmann HF Staff
pardig_eval: PARDIG maps on their own (pardig/), one map pass per source
3df6e8d verified Download pardig_eval/run.py from EmmaScharfmann/visualizing-different-rain-maps: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/spaces/EmmaScharfmann/visualizing-different-rain-maps/resolve/main/pardig_eval/run.py
- Command line
-
hf download hf://spaces/EmmaScharfmann/visualizing-different-rain-maps/pardig_eval/run.py
-
curl -L -o run.py https://huggingface.co/spaces/EmmaScharfmann/visualizing-different-rain-maps/resolve/main/pardig_eval/run.py
14.1 kB
| """Score days of ERA5 against PARDIG and store their hourly maps (and IMERG's), locally and on the Hub. | |
| python -m pardig_eval.run --start 2026-01-01 --end 2026-01-03 --era5 earthmover,arco \ | |
| --imerg final,late --out data --repo EmmaScharfmann/era5-pardig-scores [--what scores,fields,imerg] | |
| Two products per day, each skipped when already stored, so the command can be re-run safely | |
| (one writer per product at a time): | |
| * ``scores``: per-tile sums added to ``months/YYYY-MM.nc`` (:mod:`pardig_eval.sums`); | |
| * ``fields``: hourly maps in ``fields/YYYY/MM/YYYY-MM-DD.zarr.zip`` (:mod:`pardig_eval.fields`); | |
| * ``pardig``: PARDIG's hourly maps alone in ``pardig/YYYY/MM/YYYY-MM-DD.zarr.zip``, as soon as PARDIG has the day; | |
| * ``imerg``: IMERG's hourly maps in ``imerg/YYYY/MM/YYYY-MM-DD.zarr.zip``, from the first ``--imerg`` run that | |
| has the day complete (needs ``EARTHDATA_TOKEN``). IMERG runs on its own pass, from 1 January 2026 (or | |
| ``--start``), filling every missing day, so its latency never holds back the scores, nor theirs IMERG. | |
| ``pardig`` runs the same way, so PARDIG's maps never wait for ERA5. | |
| Without ``--start``, resumes after the last day stored; without ``--end``, stops at the last day | |
| both PARDIG and ERA5 have complete. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import logging | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import xarray as xr | |
| from pardig_eval import fields, regrid, sums | |
| from pardig_eval.sources import ERA5_SOURCES, IMERG, IMERG_RUNS, PARDIG, PARDIG_LIVE_START | |
| logger = logging.getLogger("pardig_eval") | |
| PRODUCTS = ("scores", "fields", "pardig", "imerg") | |
| def month_name(day) -> str: | |
| return f"{pd.Timestamp(day):%Y-%m}.nc" | |
| def encoding(ds: xr.Dataset) -> dict: | |
| enc = {} | |
| for name, var in ds.data_vars.items(): | |
| if var.dtype.kind in "fiub": | |
| chunks = tuple(60 if d in ("tile_lat", "tile_lon") else (1 if d == "day" else s) | |
| for d, s in zip(var.dims, var.shape)) | |
| enc[name] = {"compression": "gzip", "compression_opts": 4, "chunksizes": chunks} | |
| return enc | |
| def write(ds: xr.Dataset, path: Path): | |
| tmp = path.with_suffix(".tmp") | |
| ds.to_netcdf(tmp, engine="h5netcdf", encoding=encoding(ds)) | |
| tmp.replace(path) | |
| class Store: | |
| """Month and field files in a local folder, mirrored to a Hub dataset if ``repo`` is given.""" | |
| def __init__(self, out: Path, repo: str | None): | |
| self.root = Path(out) | |
| self.dir = self.root / "months" | |
| self.dir.mkdir(parents=True, exist_ok=True) | |
| self.repo = repo | |
| self.pending: set[str] = set() # paths relative to root, written since the last push | |
| self.remote: set[str] = set() | |
| if repo: | |
| from huggingface_hub import HfApi | |
| self.api = HfApi() | |
| self.api.create_repo(repo, repo_type="dataset", exist_ok=True) | |
| self.remote = set(self.api.list_repo_files(repo, repo_type="dataset")) | |
| def load(self, day) -> xr.Dataset | None: | |
| path = self.dir / month_name(day) | |
| if not path.exists() and f"months/{path.name}" in self.remote: | |
| from huggingface_hub import hf_hub_download | |
| hf_hub_download(self.repo, f"months/{path.name}", repo_type="dataset", local_dir=self.root) | |
| if not path.exists(): | |
| return None | |
| with xr.open_dataset(path, engine="h5netcdf") as ds: | |
| return ds.load() | |
| def days(self) -> pd.DatetimeIndex: | |
| names = sorted({p.name for p in self.dir.glob("*.nc")} | | |
| {Path(f).name for f in self.remote if f.startswith("months/") and f.endswith(".nc")}) | |
| if not names: | |
| return pd.DatetimeIndex([]) | |
| ds = self.load(pd.Timestamp(names[-1][:7])) | |
| return pd.DatetimeIndex(ds["day"].values) if ds is not None else pd.DatetimeIndex([]) | |
| def has_fields(self, day, source: str = "fields") -> bool: | |
| rel = fields.path_for(day, source) | |
| return rel in self.remote or (self.root / rel).exists() | |
| def save(self, ds: xr.Dataset, day): | |
| """Write the month file locally; it is pushed by :meth:`push`.""" | |
| write(ds, self.dir / month_name(day)) | |
| self.pending.add(f"months/{month_name(day)}") | |
| def save_fields(self, ds: xr.Dataset, day, source: str = "fields"): | |
| fields.write(ds, self.root / fields.path_for(day, source)) | |
| self.pending.add(fields.path_for(day, source)) | |
| def push(self): | |
| """Upload every file written since the last push, in one commit; field files are then deleted locally.""" | |
| pending = sorted(self.pending) | |
| if not (self.repo and pending): | |
| return | |
| from huggingface_hub import CommitOperationAdd | |
| operations = [CommitOperationAdd(rel, self.root / rel) for rel in pending] | |
| days = sorted(Path(rel).name[:10] for rel in pending if rel.startswith("fields/")) | |
| imerg = sorted(Path(rel).name[:10] for rel in pending if rel.startswith("imerg/")) | |
| pardig_only = sorted(Path(rel).name[:10] for rel in pending if rel.startswith("pardig/")) | |
| months = [Path(rel).stem for rel in pending if rel.startswith("months/")] | |
| what = ", ".join(filter(None, [f"scores {', '.join(months)}" if months else "", | |
| f"maps {days[0]}..{days[-1]}" if days else "", | |
| f"PARDIG {pardig_only[0]}..{pardig_only[-1]}" if pardig_only else "", | |
| f"IMERG {imerg[0]}..{imerg[-1]}" if imerg else ""])) | |
| self.api.create_commit(self.repo, operations, repo_type="dataset", commit_message=f"Add {what}") | |
| logger.info("pushed %s", what) | |
| self.remote.update(pending) | |
| for rel in pending: | |
| if rel.startswith(("fields/", "pardig/", "imerg/")): | |
| (self.root / rel).unlink(missing_ok=True) | |
| self.pending = set() | |
| def _available(source, day) -> bool: | |
| """Whether a source has the day, treating a source that cannot be reached as not having it.""" | |
| try: | |
| return source.available(day) | |
| except Exception as exc: # e.g. Earthmover credentials missing: fall through to the next source | |
| logger.warning("%s unavailable for %s: %s", source.name, pd.Timestamp(day).date(), exc) | |
| return False | |
| def process_day(day, era5, pardig, store: Store, month: xr.Dataset | None, what: set[str]): | |
| """Read both sources once and write what is missing; returns the updated month.""" | |
| t0 = time.perf_counter() | |
| f = era5.hourly(day) | |
| t1 = time.perf_counter() | |
| fine = pardig.hourly_fine(day) | |
| t2 = time.perf_counter() | |
| timing = [f"ERA5 {t1 - t0:.0f}s", f"PARDIG {t2 - t1:.0f}s"] | |
| if "fields" in what: | |
| store.save_fields(fields.dataset(day, fine, f, era5.name), day) | |
| t3 = time.perf_counter() | |
| timing.append(f"maps {t3 - t2:.0f}s") | |
| t2 = t3 | |
| if "scores" in what: | |
| o = regrid.to_era5_grid(fine) | |
| del fine | |
| month = sums.add_day(month, sums.as_month(sums.day_sums(f, o), day, era5.name, era5.preliminary(day))) | |
| store.save(month, day) | |
| timing.append(f"scores {time.perf_counter() - t2:.0f}s") | |
| logger.info("%s (%s): %s", pd.Timestamp(day).date(), era5.name, ", ".join(timing)) | |
| return month | |
| #: Map-only products, one folder each, written on their own pass: label and dataset builder. | |
| MAP_PASSES = { | |
| "pardig": ("PARDIG", lambda day, fine, reader: fields.pardig_dataset(day, fine, reader.name)), | |
| "imerg": ("IMERG", lambda day, fine, reader: fields.imerg_dataset(day, fine, reader.name)), | |
| } | |
| def map_pass(store: Store, folder: str, readers: list, start, end, upload_every: int, max_days: int | None) -> int: | |
| """Write one source's maps (``folder/YYYY/MM/DD.zarr.zip``) for every day from start to end that has none yet, | |
| from the first reader with the day complete; returns the number written. | |
| Incomplete days are skipped, not waited for: a recent day is filled by a later run, and an old day with a | |
| file missing for good does not block the days after it.""" | |
| label, build = MAP_PASSES[folder] | |
| processed = failures = 0 | |
| for day in pd.date_range(start, end, freq="D"): | |
| if store.has_fields(day, folder): | |
| continue | |
| reader = next((r for r in readers if _available(r, day)), None) | |
| if reader is None: | |
| logger.info("%s: %s incomplete, skipping", day.date(), label) | |
| continue | |
| t0 = time.perf_counter() | |
| try: | |
| fine = reader.hourly_fine(day) | |
| except Exception as exc: # e.g. the source's server down for a while: the next run fills the day | |
| logger.warning("%s: %s read failed, skipping: %s", day.date(), label, exc) | |
| failures += 1 | |
| if failures >= 5: | |
| logger.error("%s: %d failed days, giving up for this run", label, failures) | |
| break | |
| continue | |
| store.save_fields(build(day, fine, reader), day, folder) | |
| logger.info("%s (%s): %s %.0fs", day.date(), reader.name, label, time.perf_counter() - t0) | |
| processed += 1 | |
| if processed % upload_every == 0: | |
| store.push() | |
| if max_days and processed >= max_days: | |
| break | |
| return processed | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--start", help="first day (default: the day after the last one with scores)") | |
| parser.add_argument("--end", help="last day (default: the last day both sources have complete)") | |
| parser.add_argument("--era5", default="earthmover", | |
| help=f"ERA5 sources to try in order for each day, comma-separated, from {sorted(ERA5_SOURCES)};" | |
| " e.g. 'earthmover,arco' falls back to ARCO for days Earthmover does not have yet") | |
| parser.add_argument("--imerg", default="final,late", | |
| help=f"IMERG runs to try in order for each day, from {list(IMERG_RUNS)}") | |
| parser.add_argument("--what", default="scores,fields,pardig,imerg", help=f"products to write, from {list(PRODUCTS)}") | |
| parser.add_argument("--out", default="data", help="local working folder") | |
| parser.add_argument("--repo", help="Hub dataset to read and push files, e.g. user/era5-pardig-scores") | |
| parser.add_argument("--max-days", type=int, default=None, help="stop after this many processed days") | |
| parser.add_argument("--no-events", action="store_true", help="do not refresh events.json at the end") | |
| parser.add_argument("--upload-every", type=int, default=1, | |
| help="push to the Hub every this many processed days (and when a month ends, and at the end)") | |
| args = parser.parse_args(argv) | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") | |
| logging.getLogger("httpx").setLevel(logging.WARNING) | |
| what = {w.strip() for w in args.what.split(",") if w.strip()} | |
| names = [n.strip() for n in args.era5.split(",") if n.strip()] | |
| if not what or what - set(PRODUCTS): | |
| parser.error(f"--what takes {list(PRODUCTS)}") | |
| if not names or set(names) - set(ERA5_SOURCES): | |
| parser.error(f"--era5 takes {sorted(ERA5_SOURCES)}") | |
| imerg_names = [n.strip() for n in args.imerg.split(",") if n.strip()] | |
| if "imerg" in what and (not imerg_names or set(imerg_names) - set(IMERG_RUNS)): | |
| parser.error(f"--imerg takes {list(IMERG_RUNS)}") | |
| store = Store(Path(args.out), args.repo) | |
| era5_sources, pardig = [ERA5_SOURCES[n]() for n in names], PARDIG() | |
| if args.start: | |
| start = pd.Timestamp(args.start) | |
| else: | |
| done = store.days() | |
| start = done[-1] + pd.Timedelta(days=1) if len(done) else PARDIG_LIVE_START | |
| end = pd.Timestamp(args.end) if args.end else pd.Timestamp.utcnow().tz_localize(None).normalize() | |
| processed = 0 | |
| month, month_key = None, None | |
| main_what = what - set(MAP_PASSES) | |
| try: | |
| for day in pd.date_range(start, end, freq="D") if main_what else []: | |
| if "scores" in what and month_name(day) != month_key: | |
| store.push() | |
| month, month_key = store.load(day), month_name(day) | |
| todo = set(main_what) | |
| if "scores" in todo and month is not None and np.isin(day.to_datetime64(), month["day"].values): | |
| todo.discard("scores") | |
| if "fields" in todo and store.has_fields(day): | |
| todo.discard("fields") | |
| if not todo: | |
| logger.info("%s already stored", day.date()) | |
| continue | |
| era5 = next((source for source in era5_sources if _available(source, day)), None) | |
| if era5 is None or not pardig.available(day): | |
| if args.end: | |
| logger.warning("%s: a source is incomplete, skipping", day.date()) | |
| continue | |
| logger.info("%s: a source is incomplete, stopping here", day.date()) | |
| break | |
| month = process_day(day, era5, pardig, store, month, todo) | |
| processed += 1 | |
| if processed % args.upload_every == 0: | |
| store.push() | |
| if args.max_days and processed >= args.max_days: | |
| break | |
| readers = {"pardig": lambda: [pardig], "imerg": lambda: [IMERG(r) for r in imerg_names]} | |
| for folder in MAP_PASSES: | |
| if folder in what: | |
| store.push() | |
| first = pd.Timestamp(args.start) if args.start else PARDIG_LIVE_START | |
| n = map_pass(store, folder, readers[folder](), first, end, args.upload_every, args.max_days) | |
| logger.info("%s: %d day(s)", MAP_PASSES[folder][0], n) | |
| finally: | |
| store.push() | |
| logger.info("processed %d day(s)", processed) | |
| if args.repo and processed and not args.no_events: | |
| from pardig_eval import events | |
| events.publish(args.repo, Path(args.out) / "events") | |
| if __name__ == "__main__": | |
| main() | |