File size: 7,823 Bytes
f44e04f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Find striking days and places to feature, from the stored daily per-tile sums.

Slides an 8° x 12° window over the 1° tiles of every scored day that also has stored maps, and ranks:

* ``storm``: the heaviest PARDIG rain (window mean, mm/day);
* ``missed``: where PARDIG had >= 50 mm/day over the largest area that ERA5 did not;
* ``drizzle``: where ERA5 rained most while PARDIG stayed nearly dry, within 35° of the equator only,
  since PARDIG underestimates snowfall and winter mountain precipitation.

A varied selection (no two events within 4 days and 20° of each other) is written to ``events.json``.

    python -m pardig_eval.events --repo EmmaScharfmann/era5-pardig-scores [--out data]
"""

from __future__ import annotations

import argparse
import json
import logging
from pathlib import Path

import numpy as np
import pandas as pd
import xarray as xr
from scipy.ndimage import uniform_filter

from pardig_eval import grid, places

logger = logging.getLogger("pardig_eval.events")

WINDOW = (8, 12)  # tiles: latitude, longitude
MAX_ABS_LAT = 55  # PARDIG is least trustworthy at high latitudes (snow, ice)
CELL_KM2 = (111.32 * 0.25) ** 2  # area of an equatorial 0.25° cell, the unit of the stored weights
KINDS = {"storm": 4, "missed": 3, "drizzle": 2}  # how many of each to keep
DRIZZLE_MAX_LAT = 35
NEAR_KM = 700  # window centre within this distance of a city of at least CITY_POPULATION
CITY_POPULATION = 1_000_000


def near_people() -> np.ndarray:
    """(180, 360) mask of tile centres near a large city: events people can relate to."""
    t = places.table()
    big = t["population"] >= CITY_POPULATION
    lat, lon = np.meshgrid(grid.TILE_LAT, grid.TILE_LON, indexing="ij")
    best = np.full(lat.shape, np.inf)
    for clat, clon in zip(t["lat"][big], t["lon"][big]):
        best = np.minimum(best, places.distance_km(clat, clon, lat, lon))
    return best <= NEAR_KM


def _window_sum(x: np.ndarray) -> np.ndarray:
    """Sum over an 8 x 12 tile window, longitude periodic, on (..., 180, 360)."""
    size = (1,) * (x.ndim - 2) + WINDOW
    mode = ("constant",) * (x.ndim - 1) + ("wrap",)
    return uniform_filter(x.astype(np.float64), size, mode=mode) * np.prod(WINDOW)


def candidates(month: xr.Dataset, days_with_maps: set[str]) -> list[dict]:
    """Best window of each kind for each day of one month file."""
    d = month["daily"]
    out = []
    allowed = (np.abs(grid.TILE_LAT) <= MAX_ABS_LAT)[:, None] & near_people()
    for i, day in enumerate(pd.DatetimeIndex(month["day"].values)):
        key = f"{day:%Y-%m-%d}"
        if key not in days_with_maps:
            continue
        get = lambda s: d.isel(day=i).sel(daily_stat=s).values  # noqa: E731
        n, f, o = _window_sum(get("n")), _window_sum(get("f")), _window_sum(get("o"))
        hit, false, miss = (_window_sum(get(f"{k}_50")) for k in ("hit", "false_alarm", "miss"))
        with np.errstate(invalid="ignore", divide="ignore"):
            f_mean, o_mean = f / n, o / n
        scores = {
            "storm": o_mean,
            "missed": miss * CELL_KM2,
            "drizzle": np.where((o_mean < 0.25 * f_mean) & (np.abs(grid.TILE_LAT) <= DRIZZLE_MAX_LAT)[:, None],
                                f_mean - o_mean, 0),
        }
        for kind, score in scores.items():
            s = np.where(allowed, np.nan_to_num(score), -np.inf)
            r, c = np.unravel_index(int(np.argmax(s)), s.shape)
            out.append({
                "kind": kind, "day": key, "score": float(s[r, c]),
                "lat": float(grid.TILE_LAT[r]), "lon": float(((grid.TILE_LON[c] + 180) % 360) - 180),
                "era5_mm": float(f_mean[r, c]), "pardig_mm": float(o_mean[r, c]),
                "pardig_50_km2": float((hit[r, c] + miss[r, c]) * CELL_KM2),
                "era5_50_km2": float((hit[r, c] + false[r, c]) * CELL_KM2),
            })
    return out


def _text(e: dict) -> tuple[str, str]:
    where = places.describe(e["lat"], e["lon"])
    date = f"{pd.Timestamp(e['day']):%-d %b}"
    if e["kind"] == "storm":
        return (f"Heavy rain {where}, {date}",
                f"PARDIG {e['pardig_mm']:.0f} mm on average over the area, ERA5 {e['era5_mm']:.0f} mm")
    if e["kind"] == "missed":
        ratio = e["pardig_50_km2"] / max(e["era5_50_km2"], 1)
        return (f"Downpours ERA5 missed {where}, {date}",
                f"≥ 50 mm fell over {e['pardig_50_km2'] / 1000:,.0f}k km² in PARDIG"
                + (f", {ratio:.0f}× ERA5's area" if e["era5_50_km2"] > 0 else ", none in ERA5"))
    return (f"ERA5 drizzle {where}, {date}",
            f"ERA5 {e['era5_mm']:.1f} mm on average over the area, PARDIG {e['pardig_mm']:.1f} mm")


def select(cands: list[dict]) -> list[dict]:
    """Top events of each kind, spread out in space and time, in display order."""
    chosen: list[dict] = []
    for kind, count in KINDS.items():
        taken = 0
        for e in sorted((c for c in cands if c["kind"] == kind), key=lambda c: -c["score"]):
            if taken == count or e["score"] <= 0:
                break
            close = any(abs((pd.Timestamp(e["day"]) - pd.Timestamp(c["day"])).days) <= 4
                        and places.distance_km(e["lat"], e["lon"], c["lat"], c["lon"]) < 2200 for c in chosen)
            if not close:
                chosen.append(e)
                taken += 1
    order = []  # interleave kinds: storm, missed, drizzle, storm, ...
    by_kind = {k: [e for e in chosen if e["kind"] == k] for k in KINDS}
    while any(by_kind.values()):
        for k in KINDS:
            if by_kind[k]:
                order.append(by_kind[k].pop(0))
    for i, e in enumerate(order):
        e["title"], e["subtitle"] = _text(e)
        e["id"] = f"{e['kind']}-{e['day']}-{i}"
        half_lat, half_lon = WINDOW[0] / 2 + 2, WINDOW[1] / 2 + 3
        e["box"] = [max(e["lat"] - half_lat, -80), min(e["lat"] + half_lat, 80), e["lon"] - half_lon, e["lon"] + half_lon]
    return order


def find_events(month_paths: list[Path], days_with_maps: set[str]) -> list[dict]:
    cands = []
    for path in sorted(month_paths):
        with xr.open_dataset(path, engine="h5netcdf") as month:
            cands.extend(candidates(month[["daily"]].load(), days_with_maps))
    return select(cands)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--repo", required=True)
    parser.add_argument("--out", default="data")
    parser.add_argument("--no-push", action="store_true")
    args = parser.parse_args(argv)
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    publish(args.repo, Path(args.out), push=not args.no_push)


def publish(repo: str, out: Path, push: bool = True) -> list[dict]:
    """Recompute events from the dataset's month files and push ``events.json``."""
    from huggingface_hub import HfApi, hf_hub_download

    api = HfApi()
    files = api.list_repo_files(repo, repo_type="dataset")
    days = {Path(f).name[:10] for f in files if f.startswith("fields/") and f.endswith(".zarr.zip")}
    months = [Path(hf_hub_download(repo, f, repo_type="dataset", local_dir=out))
              for f in files if f.startswith("months/") and f.endswith(".nc")]
    events = find_events(months, days)
    path = out / "events.json"
    path.write_text(json.dumps({"generated": pd.Timestamp.now("UTC").isoformat(), "events": events}, indent=1))
    logger.info("%d events: %s", len(events), "; ".join(e["title"] for e in events))
    if push and events:
        api.upload_file(path_or_fileobj=path, path_in_repo="events.json", repo_id=repo, repo_type="dataset",
                        commit_message=f"Update featured events ({len(events)})")
    return events


if __name__ == "__main__":
    main()