File size: 14,050 Bytes
2621a72
9ac2fa1
 
2621a72
9ac2fa1
06dc5fa
 
 
 
2621a72
3df6e8d
2621a72
 
 
3df6e8d
06dc5fa
 
 
9ac2fa1
 
 
 
 
 
 
 
 
 
 
 
 
06dc5fa
2621a72
9ac2fa1
 
3df6e8d
9ac2fa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06dc5fa
9ac2fa1
 
06dc5fa
 
9ac2fa1
 
06dc5fa
 
9ac2fa1
 
 
 
 
06dc5fa
9ac2fa1
 
 
06dc5fa
9ac2fa1
 
06dc5fa
9ac2fa1
 
 
 
 
 
06dc5fa
 
9ac2fa1
 
 
 
 
2621a72
 
06dc5fa
 
9ac2fa1
 
 
06dc5fa
 
2621a72
 
 
9ac2fa1
 
06dc5fa
 
9ac2fa1
 
 
 
06dc5fa
 
2621a72
3df6e8d
06dc5fa
 
2621a72
3df6e8d
2621a72
06dc5fa
 
 
 
3df6e8d
06dc5fa
9ac2fa1
 
 
 
 
 
 
 
 
 
 
 
06dc5fa
 
9ac2fa1
 
 
06dc5fa
9ac2fa1
06dc5fa
 
 
 
 
 
 
 
 
 
 
 
 
 
9ac2fa1
 
3df6e8d
 
 
 
 
 
 
 
 
 
2621a72
 
3df6e8d
 
9d0feef
2621a72
3df6e8d
2621a72
3df6e8d
 
 
2621a72
 
9d0feef
3df6e8d
 
 
9d0feef
 
3df6e8d
9d0feef
 
3df6e8d
 
2621a72
 
 
 
 
 
 
 
9ac2fa1
 
06dc5fa
9ac2fa1
 
 
 
2621a72
 
3df6e8d
06dc5fa
 
 
f44e04f
9ac2fa1
06dc5fa
9ac2fa1
 
06dc5fa
9ac2fa1
06dc5fa
9ac2fa1
06dc5fa
 
 
 
2621a72
 
 
06dc5fa
 
9ac2fa1
06dc5fa
 
 
 
 
9ac2fa1
06dc5fa
 
9ac2fa1
3df6e8d
9ac2fa1
2621a72
06dc5fa
9ac2fa1
 
2621a72
06dc5fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ac2fa1
3df6e8d
 
 
 
 
 
 
9ac2fa1
 
06dc5fa
f44e04f
 
 
 
9ac2fa1
 
 
 
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
"""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()