File size: 26,666 Bytes
7f68fbf
 
e5a511b
59a662c
 
 
 
7f68fbf
b0a36c3
 
e5a511b
 
 
 
 
 
 
59a662c
e5a511b
 
 
 
 
 
 
 
59a662c
e5a511b
 
 
 
 
 
 
 
 
 
59a662c
e5a511b
59a662c
e5a511b
ed7104e
 
6457edb
1c27952
 
44f4384
3346207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5a511b
59a662c
 
e5a511b
 
7f68fbf
 
 
b0a36c3
7f68fbf
 
 
e5a511b
 
 
 
 
7f68fbf
 
e5a511b
 
 
 
7f68fbf
e5a511b
 
 
7f68fbf
 
 
 
 
 
e5a511b
 
 
 
 
 
7f68fbf
 
 
e5a511b
 
 
7f68fbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5a511b
 
 
 
f44e04f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5a511b
7f68fbf
 
 
e5a511b
7f68fbf
e5a511b
 
 
7f68fbf
e5a511b
 
 
7f68fbf
59a662c
7f68fbf
59a662c
 
 
 
7f68fbf
59a662c
 
 
 
 
7f68fbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a662c
 
 
 
 
 
 
 
 
 
 
 
e5a511b
 
 
59a662c
e5a511b
 
 
 
 
 
59a662c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6457edb
 
 
 
 
 
 
 
59a662c
6457edb
 
 
59a662c
6457edb
59a662c
6457edb
59a662c
e5a511b
 
 
44f4384
e5a511b
 
44f4384
 
e5a511b
 
59a662c
 
 
 
 
 
 
e5a511b
 
59a662c
 
 
 
b2b8a15
 
ed7104e
b2b8a15
 
 
 
7f68fbf
 
 
 
 
 
b2b8a15
 
3346207
 
 
 
 
 
 
 
 
 
 
 
7f68fbf
 
59a662c
 
7f68fbf
 
 
6457edb
59a662c
7f68fbf
 
 
 
 
 
 
59a662c
7f68fbf
 
59a662c
 
f44e04f
7f68fbf
 
 
 
 
 
 
 
 
3346207
 
b2b8a15
 
7f68fbf
 
59a662c
 
 
6457edb
 
7f68fbf
 
 
 
 
 
6457edb
 
7f68fbf
3346207
 
b2b8a15
7f68fbf
b2b8a15
7f68fbf
ed7104e
6457edb
59a662c
7f68fbf
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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
"""Two rain maps over a region (any two of ERA5, PARDIG and IMERG), hour by hour, as frames for the animated
map component, with their difference.

Each frame of each source is a small paletted PNG, resampled onto Web-Mercator rows by nearest
neighbour (so 0.25° ERA5 cells stay square and line up with the basemap at any latitude). The
browser component (``rainmaps.js``) preloads the frames and plays them on two synchronised
MapLibre maps.

ERA5 comes from ``fields/YYYY/MM/DD.zarr.zip`` in the dataset, PARDIG from ``pardig/...`` and IMERG from
``imerg/...`` (same layout), so each pair is available as soon as both of its sources are.
"""

from __future__ import annotations

import base64
import functools
import io
import json
import logging
import os
import threading
import time
from pathlib import Path

import numpy as np
import pandas as pd
import xarray as xr
from PIL import Image

from pardig_eval import fields, grid, regrid

logger = logging.getLogger("maps")

DATA_REPO = os.environ.get("DATA_REPO", "EmmaScharfmann/era5-pardig-scores")
DATA_DIR = os.environ.get("DATA_DIR")  # local folder with fields/YYYY/MM/*.zarr.zip, instead of the Hub
REFRESH_S = 1800
MAX_LAT = 85.0  # Web Mercator limit
MAX_PX = 900  # widest rendered frame

# One-hue sequential blue ramp (dataviz reference palette, steps 150 -> 700); dry is transparent.
RAIN_COLORS = ["#b7d3f6", "#86b6ef", "#5598e7", "#3987e5", "#2a78d6", "#256abf", "#1c5cab", "#104281", "#0d366b"]
# Difference left - right (mm/h), ColorBrewer PuOr (colour-blind safe, no blue so it cannot be read as rain):
# purple where the left map is wetter, orange-brown where the right one is, clear near zero.
DIFF_LEVELS = [-10, -5, -2, -0.5, -0.1, 0.1, 0.5, 2, 5, 10]
DIFF_COLORS = ["#7f3b08", "#b35806", "#e08214", "#fdb863", "#fee0b6", None,
               "#d8daeb", "#b2abd2", "#8073ac", "#542788", "#2d004b"]
DIFF_LABELS = ["≤ −10", "−5", "−2", "−0.5", "−0.1", "", "0.1", "0.5", "2", "5", "≥ 10"]
# Rain in named intensity classes (mm in the hour), one blue step each; below 0.1 mm is clear.
RAIN_CLASSES = [("Drizzle", 0.1, "0.1–0.5"), ("Light", 0.5, "0.5–2.5"), ("Moderate", 2.5, "2.5–10"),
                ("Heavy", 10.0, "10–50"), ("Violent", 50.0, "50+")]
RAIN_CLASS_COLORS = ["#b7d3f6", "#6da7ec", "#2a78d6", "#1c5cab", "#0d366b"]

# Who sees rain, cell by cell on ERA5's grid (category codes 0-4).
WET = 0.1  # mm in the hour
HEAVY = 10.0  # PARDIG heavy rain ...
ERA5_LIGHT = 2.5  # ... where ERA5 has at most light rain
AGREEMENT = [  # (code, label, colour)
    (1, "Both see rain", "#b4b2aa"),
    (2, "Only ERA5 rains", "#8073ac"),
    (3, "Only PARDIG rains", "#f1a340"),
    (4, "Heavy rain ERA5 misses", "#b35806"),
]

LEVELS = {
    "hour": [0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50],  # mm in an hour
    "total": [0.5, 1, 2, 5, 10, 20, 50, 100, 200],  # mm over the span
}

#: Map sources: label, resolution, folder in the dataset, variable, fine grid name in pardig_eval.regrid.
SOURCES = {
    "imerg": {"label": "IMERG", "res": "10 km", "folder": "imerg", "var": "imerg", "fine": "imerg"},
    "pardig": {"label": "PARDIG", "res": "10 km", "folder": "pardig", "var": "pardig", "fine": "pardig"},
    "era5": {"label": "ERA5", "res": "28 km", "folder": "fields", "var": "era5", "fine": None},
}


# ---------------------------------------------------------------------------
# data
# ---------------------------------------------------------------------------
class Days:
    """Days whose hourly fields are stored, per folder (``fields``, ``imerg``), refreshed from the Hub every
    REFRESH_S seconds. ``days`` are those of ``fields`` (ERA5 and PARDIG)."""

    def __init__(self):
        self.lock = threading.Lock()
        self.days: list[str] = []
        self.by_folder: dict[str, set[str]] = {}
        self.checked = 0.0
        self.refresh(force=True)

    def for_sources(self, *sources: str) -> list[str]:
        """Days every one of the sources has maps for."""
        folders = {SOURCES[s]["folder"] for s in sources}
        sets = [self.by_folder.get(f, set()) for f in folders]
        return sorted(set.intersection(*sets)) if sets else []

    def refresh(self, force=False):
        if not force and time.time() - self.checked < REFRESH_S:
            return
        with self.lock:
            self.checked = time.time()
            try:
                by_folder = {}
                for folder in sorted({v["folder"] for v in SOURCES.values()}):
                    by_folder[folder] = {n[:10] for n in self._names(folder)}
            except Exception as exc:  # keep serving what we have
                logger.warning("could not list days: %s", exc)
                return
            self.by_folder = by_folder
            self.days = sorted(by_folder.get("fields", ()))
            logger.info("days of maps: %s", {k: len(v) for k, v in by_folder.items()})

    @staticmethod
    def _names(folder: str) -> list[str]:
        if DATA_DIR:
            return [p.name for p in Path(DATA_DIR).glob(f"{folder}/*/*/*.zarr.zip")]
        from huggingface_hub import HfApi
        from huggingface_hub.errors import EntryNotFoundError

        try:
            return [Path(f.path).name for f in HfApi().list_repo_tree(
                DATA_REPO, path_in_repo=folder, repo_type="dataset", recursive=True) if f.path.endswith(".zarr.zip")]
        except EntryNotFoundError:  # folder not created yet
            return []


DAYS = Days()

EVENT_KINDS = {"missed": "ERA5 missed it", "storm": "Heavy rain", "drizzle": "ERA5 drizzle"}


class Events:
    """Featured events (``events.json`` in the dataset), refreshed with the days."""

    def __init__(self):
        self.items: list[dict] = []
        self.checked = 0.0
        self.refresh(force=True)

    def refresh(self, force=False):
        if not force and time.time() - self.checked < REFRESH_S:
            return
        self.checked = time.time()
        try:
            if DATA_DIR:
                path = Path(DATA_DIR) / "events.json"
            else:
                from huggingface_hub import hf_hub_download

                path = hf_hub_download(DATA_REPO, "events.json", repo_type="dataset", force_download=True)
            items = json.loads(Path(path).read_text())["events"]
        except Exception as exc:
            logger.warning("could not load events: %s", exc)
            return
        days = set(DAYS.days)
        # Interleave kinds, "ERA5 missed it" first: it is the most telling.
        order = {k: i for i, k in enumerate(EVENT_KINDS)}
        seen: dict[str, int] = {}
        ranked = []
        for e in items:
            if e["day"] in days:
                seen[e["kind"]] = seen.get(e["kind"], -1) + 1
                ranked.append((seen[e["kind"]], order.get(e["kind"], 9), e))
        self.items = [e for _, _, e in sorted(ranked, key=lambda r: r[:2])]

    def cards(self) -> list[dict]:
        return [{"id": e["id"], "kind": EVENT_KINDS.get(e["kind"], e["kind"]), "title": e["title"],
                 "subtitle": e["subtitle"]} for e in self.items]

    def get(self, event_id: str) -> dict | None:
        return next((e for e in self.items if e["id"] == event_id), None)


EVENTS = Events()


@functools.lru_cache(maxsize=8)
def open_day(day: str, folder: str = "fields") -> xr.Dataset:
    rel = fields.path_for(day, folder)
    if DATA_DIR:
        path = Path(DATA_DIR) / rel
    else:
        from huggingface_hub import hf_hub_download

        path = hf_hub_download(DATA_REPO, rel, repo_type="dataset")
    return fields.open_fields(path)


def _fine_on_era5_grid(fine: xr.DataArray, lat_min: float, lat_max: float, source: str = "pardig") -> xr.DataArray:
    """Conservative 0.1° -> 0.25° for the ERA5 rows of a latitude band only (all longitudes)."""
    lat_m, lon_m = regrid.matrices(source)
    rows = np.flatnonzero((grid.LAT >= lat_min - 0.3) & (grid.LAT <= lat_max + 0.3))
    band = lat_m[rows]
    needed = np.unique(band.indices)
    band = band[:, needed]
    values = fine.isel({fine.dims[1]: needed}).values  # (time, rows, 3600)
    out = np.stack([(lon_m @ (band @ v.astype(np.float64)).T).T for v in values]).astype(np.float32)
    return xr.DataArray(out, dims=("time", "lat_era5", "lon_era5"),
                        coords={"time": fine["time"].values, "lat_era5": grid.LAT[rows], "lon_era5": grid.LON})


def _pardig_on_era5_grid(fine: xr.DataArray, lat_min: float, lat_max: float) -> xr.DataArray:
    return _fine_on_era5_grid(fine, lat_min, lat_max, "pardig")


def load_source(source: str, days: list[str], box, on_era5_grid: bool) -> xr.DataArray:
    """Hourly rain of one source over the box for the given days, at its own resolution or on ERA5's grid."""
    meta = SOURCES[source]
    parts = []
    for day in days:
        da = open_day(day, meta["folder"])[meta["var"]]
        if on_era5_grid and meta["fine"]:
            parts.append(fields.crop(_fine_on_era5_grid(da, box[0], box[1], meta["fine"]), *box))
        else:
            parts.append(fields.crop(da, *box).load())
    return xr.concat(parts, "time")


def load_span(start: str, n_days: int, box, pardig_on_era5_grid: bool) -> tuple[xr.DataArray, xr.DataArray]:
    """Hourly ERA5 and PARDIG over the box for ``n_days`` stored days from ``start``."""
    days = [d for d in DAYS.days if d >= start][:n_days]
    era5, pardig = [], []
    for day in days:
        ds = open_day(day)
        era5.append(fields.crop(ds["era5"], *box).load())
        if pardig_on_era5_grid:
            pardig.append(fields.crop(_pardig_on_era5_grid(ds["pardig"], box[0], box[1]), *box))
        else:
            pardig.append(fields.crop(ds["pardig"], *box).load())
    return xr.concat(era5, "time"), xr.concat(pardig, "time")


# ---------------------------------------------------------------------------
# frames
# ---------------------------------------------------------------------------
def _merc(lat_deg):
    lat = np.deg2rad(np.clip(lat_deg, -MAX_LAT, MAX_LAT))
    return np.log(np.tan(np.pi / 4 + lat / 2))


class Raster:
    """Nearest-neighbour lookup from a regular lat/lon grid to Web-Mercator pixels, built once per source."""

    def __init__(self, da: xr.DataArray):
        lat_name, lon_name = da.dims[-2:]
        lat, lon = da[lat_name].values, da[lon_name].values
        dlat = float(np.median(np.diff(lat))) if lat.size > 1 else 0.25
        dlon = float(np.median(np.diff(lon))) if lon.size > 1 else 0.25
        south, north = max(lat[0] - dlat / 2, -MAX_LAT), min(lat[-1] + dlat / 2, MAX_LAT)
        west, east = lon[0] - dlon / 2, lon[-1] + dlon / 2
        width = int(np.clip(3 * lon.size, 300, MAX_PX))
        y0, y1 = _merc(south), _merc(north)
        height = int(np.clip(round(width * (y1 - y0) / np.deg2rad(east - west)), 30, 2 * MAX_PX))
        xs = west + (np.arange(width) + 0.5) / width * (east - west)
        ys = y1 - (np.arange(height) + 0.5) / height * (y1 - y0)
        lat_px = np.rad2deg(2 * np.arctan(np.exp(ys)) - np.pi / 2)
        self.cols = np.clip(np.round((xs - lon[0]) / dlon).astype(int), 0, lon.size - 1)
        self.rows = np.clip(np.round((lat_px - lat[0]) / dlat).astype(int), 0, lat.size - 1)
        self.corners = [[west, north], [east, north], [east, south], [west, south]]

    def png(self, values: np.ndarray, levels, colors=None, clear: int = 0, nan_value: float = -1.0) -> str:
        """Paletted PNG: class ``i`` of ``np.digitize(values, levels)`` gets ``colors[i]``; class ``clear`` is transparent.

        With the default rain scale, class 0 (below the first level) is clear and class ``i`` gets RAIN_COLORS[i-1].
        """
        if colors is None:
            colors = [None] + RAIN_COLORS[: len(levels)]
        index = np.digitize(np.nan_to_num(values, nan=nan_value), levels).astype(np.uint8)[self.rows][:, self.cols]
        image = Image.fromarray(index, "P")
        palette = []
        for color in colors:
            palette += [0, 0, 0] if color is None else [int(color[j:j + 2], 16) for j in (1, 3, 5)]
        image.putpalette(palette)
        alpha = bytes(0 if i == clear else 255 for i in range(len(colors)))
        buffer = io.BytesIO()
        image.save(buffer, format="PNG", transparency=alpha)
        return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()


def view(box) -> dict:
    """Centre and zoom that fit a box in a ~450 x 470 px map (MapLibre: the world is 512 px at zoom 0)."""
    lat0, lat1 = max(box[0], -MAX_LAT), min(box[1], MAX_LAT)
    lon0, lon1 = box[2], box[3] if box[3] > box[2] else box[3] + 360
    zoom_x = np.log2(450 * 360 / (512 * max(lon1 - lon0, 1e-3)))
    zoom_y = np.log2(470 * 2 * np.pi / (512 * max(_merc(lat1) - _merc(lat0), 1e-3)))
    centre_lat = float(np.rad2deg(2 * np.arctan(np.exp((_merc(lat0) + _merc(lat1)) / 2)) - np.pi / 2))
    lon_c = (lon0 + lon1) / 2
    return {"center": [((lon_c + 180) % 360) - 180, centre_lat], "zoom": float(np.clip(min(zoom_x, zoom_y) - 0.1, 0, 12))}


def _label(t) -> str:
    end = pd.Timestamp(t)
    start = end - pd.Timedelta(hours=1)
    return f"{start:%a %-d %b %Y} · {start:%H}:00–{end:%H}:00 UTC"


def _weights(da: xr.DataArray) -> np.ndarray:
    return np.cos(np.deg2rad(da[da.dims[-2]].values))[:, None] * np.ones(da.shape[-2:])


# ERA5 - PARDIG (mm in the hour) in 9 classes; cells where both are dry stay clear.
DIFF_BOUNDS = [-10, -3, -1, -0.2, 0.2, 1, 3, 10]
# from "right much wetter" (d <= -10) to "left much wetter" (d >= 10), grey in the middle
DIFF_CLASS_COLORS = ["#7f3b08", "#b35806", "#e08214", "#fdb863", "#bdbcb5",
                     "#b2abd2", "#8073ac", "#542788", "#2d004b"]


def difference_classes(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    """0 where both are dry or either has no data, else 1 + the class of a - b in DIFF_BOUNDS."""
    missing = np.isnan(a) | np.isnan(b)
    a, b = np.nan_to_num(a), np.nan_to_num(b)
    codes = 1 + np.digitize(a - b, DIFF_BOUNDS)
    return np.where(((a < WET) & (b < WET)) | missing, 0, codes).astype(np.float32)


def agreement(era5: np.ndarray, pardig: np.ndarray) -> np.ndarray:
    """Per cell and hour: 0 both dry, 1 both rain, 2 only ERA5, 3 only PARDIG, 4 PARDIG heavy where ERA5 is light."""
    e, p = np.nan_to_num(era5), np.nan_to_num(pardig)
    e_wet, p_wet = e >= WET, p >= WET
    out = np.zeros(e.shape, np.float32)
    out[e_wet & p_wet] = 1
    out[e_wet & ~p_wet] = 2
    out[~e_wet & p_wet] = 3
    out[(p >= HEAVY) & (e < ERA5_LIGHT)] = 4
    return out


def summary(left: xr.DataArray, right: xr.DataArray, names=("ERA5", "PARDIG")) -> str:
    """One plain-language line comparing the two over the hours shown (each over the cells it has data for)."""
    def stats(da):
        v = np.asarray(da.values, dtype=float)  # (hours, lat, lon)
        w = _weights(da) * np.isfinite(v).all(0)
        if not w.sum():
            return 0.0, 0.0, 0.0, v.shape[0]
        total = float((w * np.nansum(v, axis=0)).sum() / w.sum())
        wet = float((w[None] * (np.nan_to_num(v) >= 0.1)).sum() / (w.sum() * v.shape[0]))
        return total, wet, float(np.nanmax(np.where(w[None] > 0, v, np.nan))), v.shape[0]

    a, b = stats(left), stats(right)
    return (f"Over these {a[3]} hours: on average it rained over **{a[1]:.0%}** of the area in {names[0]}, "
            f"**{b[1]:.0%}** in {names[1]}; the heaviest hour in one spot was **{a[2]:.0f} mm** in {names[0]}, "
            f"**{b[2]:.0f} mm** in {names[1]}.")


def _title(source: str) -> str:
    return f"{SOURCES[source]['label']} · {SOURCES[source]['res']}"


@functools.lru_cache(maxsize=16)
def payload(start: str, n_days: int, box: tuple, left: str = "imerg", right: str = "pardig") -> tuple[str, str]:
    """(JSON for the three-panel map component, one-line summary) for ``n_days`` from ``start``, hourly:
    ``left`` and ``right`` at their own resolution, and left minus right with both on ERA5's 0.25° grid."""
    days = [d for d in DAYS.for_sources(left, right) if d >= start][:n_days]
    a, b = load_source(left, days, box, False), load_source(right, days, box, False)
    a_c, b_c = load_source(left, days, box, True), load_source(right, days, box, True)
    diff = difference_classes(a_c.values, b_c.values)
    times = pd.DatetimeIndex(a["time"].values)
    ra, rb, rc = Raster(a), Raster(b), Raster(a_c)
    rain = [lower for _, lower, _ in RAIN_CLASSES]
    rain_colors = [None, *RAIN_CLASS_COLORS]
    diff_levels = [i + 0.5 for i in range(len(DIFF_CLASS_COLORS))]
    diff_colors = [None, *DIFF_CLASS_COLORS]
    la, lb = SOURCES[left]["label"], SOURCES[right]["label"]
    both_fine = SOURCES[left]["fine"] and SOURCES[right]["fine"]
    data = {
        "key": f"{box}",
        "view": view(box),
        "labels": [_label(t) for t in times],
        "panels": [
            {"key": "left", "title": _title(left), "corners": ra.corners,
             "frames": [ra.png(v, rain, rain_colors) for v in a.values]},
            {"key": "right", "title": _title(right), "corners": rb.corners,
             "frames": [rb.png(v, rain, rain_colors) for v in b.values]},
            {"key": "diff", "title": f"{la} minus {lb}, both {'averaged to' if both_fine else 'on'} the 28 km grid",
             "corners": rc.corners, "frames": [rc.png(v, diff_levels, diff_colors) for v in diff]},
        ],
        "legends": [
            {"target": "rain", "style": "classes", "title": "Rain in the hour, mm · clear: dry or no data",
             "names": [name for name, _, _ in RAIN_CLASSES], "labels": [r for _, _, r in RAIN_CLASSES],
             "colors": RAIN_CLASS_COLORS},
            # Bar drawn wettest first (purple on the left); ticks are the class boundaries, as sizes in mm.
            {"target": "diff", "style": "bar", "title": f"{la} minus {lb}, mm in the hour · clear: both dry",
             "colors": DIFF_CLASS_COLORS[::-1],
             "ticks": [f"{abs(v):g}" for v in DIFF_BOUNDS[::-1]],
             "ends": [f"{la} wetter", "about the same", f"{lb} wetter"]},
        ],
    }
    return json.dumps(data), summary(a, b, (la, lb))


# ---------------------------------------------------------------------------
# "a great RMSE, wrong rain": two forecasts built from the real rain
# ---------------------------------------------------------------------------
KM_PER_DEG = 111.32
OFFSET_KM = 50
MARGIN_DEG = 4.0


def _area_weights(lat: np.ndarray, shape) -> np.ndarray:
    return np.broadcast_to(np.cos(np.deg2rad(lat))[:, None], shape)


@functools.lru_cache(maxsize=8)
def rmse_test(start: str, n_days: int, box: tuple) -> dict:
    """Score two forecasts made from PARDIG's real rain (0.25°, hourly) against that rain, plus ERA5.

    * **A, sharp**: the real rain moved OFFSET_KM east, the right storm slightly misplaced.
    * **B, blurred**: A averaged with itself moved OFFSET_KM north, south, east and west: the same guess,
      hedged the way a model trained to minimise RMSE hedges when unsure where the storm will be.
    """
    big = (max(box[0] - MARGIN_DEG, -85), min(box[1] + MARGIN_DEG, 85), box[2] - MARGIN_DEG, box[3] + MARGIN_DEG)
    era5, pardig = load_span(start, n_days, big, True)
    lat_all = pardig[pardig.dims[1]].values
    lon_all = pardig[pardig.dims[2]].values
    k = int(MARGIN_DEG / 0.25)
    core = (slice(None), slice(k, -k), slice(k, -k))
    truth_all = np.nan_to_num(pardig.values.astype(np.float32))
    lat_c = np.deg2rad((box[0] + box[1]) / 2)
    sy = max(1, int(round(OFFSET_KM / (0.25 * KM_PER_DEG))))
    sx = max(1, int(round(OFFSET_KM / (0.25 * KM_PER_DEG * max(np.cos(lat_c), 0.2)))))
    sharp_all = np.roll(truth_all, sx, axis=2)
    blur_all = np.mean([sharp_all] + [np.roll(sharp_all, s, axis=a) for a, s in ((1, sy), (1, -sy), (2, sx), (2, -sx))],
                       axis=0)
    truth, sharp, blur = truth_all[core], sharp_all[core], blur_all[core]
    e = np.nan_to_num(era5.values.astype(np.float32))[core]
    lat, lon = lat_all[k:-k], lon_all[k:-k]
    w = _area_weights(lat, truth.shape[1:])[None]
    # Heavy-rain threshold: the highest of these the real rain reaches often enough to count.
    heavy = next((t for t in (30.0, 20.0, 10.0, 5.0, 2.0) if (truth >= t).sum() >= 50), 1.0)

    def stats(f):
        return {
            "rmse": float(np.sqrt((w * (f - truth) ** 2).sum() / (w.sum() * f.shape[0]))),
            "max": float(f.max()),
            "area": float((w * (f >= 0.1)).sum() / (w.sum() * f.shape[0])),
            "heavy": float((w * (f >= heavy)).sum()),
        }

    out = {"truth": stats(truth), "sharp": stats(sharp), "blur": stats(blur), "era5": stats(e), "heavy_mm": heavy,
           "offset_km": OFFSET_KM}
    hour = int(np.argmax((w * truth).sum((1, 2))))
    out["hour"] = str(pd.Timestamp(pardig["time"].values[hour]))
    out["maps"] = {"lat": lat, "lon": lon, "fields": [truth[hour], sharp[hour], blur[hour], e[hour]]}
    return out


def rmse_table(t: dict) -> str:
    names = [("truth", "Real rain (PARDIG)"), ("sharp", f"A · right storm, {t['offset_km']} km off"),
             ("blur", "B · same, blurred"), ("era5", "ERA5")]
    best = min(("sharp", "blur", "era5"), key=lambda k: t[k]["rmse"])
    heavy_truth = t["truth"]["heavy"]

    def row(label, key, fmt):
        cells = []
        for k, _ in names:
            if key == "rmse" and k == "truth":
                cells.append("—")
            elif key == "rmse":
                cells.append(f"**{t[k][key]:.2f} 🏆**" if k == best else f"{t[k][key]:.2f}")
            else:
                cells.append(fmt(t[k][key]))
        return f"| {label} | " + " | ".join(cells) + " |"

    return "\n".join([
        "| | " + " | ".join(n for _, n in names) + " |",
        "|---|" + "---:|" * len(names),
        row("RMSE, mm/h (lower is “better”)", "rmse", None),
        row("Heaviest rain, mm/h", "max", lambda v: f"{v:.0f}"),
        row("Area with rain", "area", lambda v: f"{v:.0%}"),
        row(f"Heavy rain (≥ {t['heavy_mm']:g} mm/h) kept", "heavy",
            lambda v: f"{v / heavy_truth:.0%}" if heavy_truth else "—"),
    ])


def rmse_sentence(t: dict) -> str:
    a, b = t["sharp"], t["blur"]
    if b["rmse"] >= a["rmse"]:
        return "Here the two forecasts score alike on RMSE; try a day with heavier rain (a featured event)."
    cut = 1 - b["max"] / a["max"] if a["max"] else 0
    more = b["area"] / a["area"] - 1 if a["area"] else 0
    lost = 1 - b["heavy"] / t["truth"]["heavy"] if t["truth"]["heavy"] else 0
    return (f"**RMSE prefers B** ({b['rmse']:.2f} against {a['rmse']:.2f}), yet B cuts the heaviest rain by "
            f"**{cut:.0%}**, rains over **{more:.0%} more area** and loses **{lost:.0%} of the heavy rain**: "
            "the forecast you would want for a flood warning is A. ERA5 looks much like B.")


def rmse_maps_png(t: dict, path: Path) -> Path:
    """Four small maps of the wettest hour (truth, A, B, ERA5) with coastlines, as one PNG."""
    from PIL import ImageDraw, ImageFont

    lat, lon = t["maps"]["lat"], t["maps"]["lon"]
    titles = ["Real rain (PARDIG)", f"A · {t['offset_km']} km off", "B · blurred", "ERA5"]
    da = xr.DataArray(t["maps"]["fields"][0], dims=("lat", "lon"), coords={"lat": lat, "lon": lon})
    raster = Raster(da)
    width, height = len(raster.cols), len(raster.rows)
    scale = min(1.0, 330 / width)
    pw, ph = max(int(width * scale), 1), max(int(height * scale), 1)
    pad, head = 8, 26
    canvas = Image.new("RGB", (4 * pw + 5 * pad, ph + head + pad), "#ffffff")
    draw = ImageDraw.Draw(canvas)
    font = ImageFont.load_default(size=14)
    coast = _coast_pixels(raster, pw, ph)
    levels = LEVELS["hour"]
    for i, (title, field) in enumerate(zip(titles, t["maps"]["fields"])):
        x0 = pad + i * (pw + pad)
        index = np.digitize(field, levels).astype(np.uint8)[raster.rows][:, raster.cols]
        rgb = np.full(index.shape + (3,), 240, np.uint8)
        for j, color in enumerate(RAIN_COLORS[: len(levels)]):
            rgb[index == j + 1] = [int(color[q:q + 2], 16) for q in (1, 3, 5)]
        panel = Image.fromarray(rgb).resize((pw, ph), Image.NEAREST)
        pdraw = ImageDraw.Draw(panel)
        for line in coast:
            if len(line) > 1:
                pdraw.line(line, fill="#6b6a66", width=1)
        canvas.paste(panel, (x0, head))
        draw.text((x0, 5), title, fill="#0b0b0b", font=font)
    canvas.save(path)
    return path


@functools.lru_cache(maxsize=1)
def _coastlines():
    data = json.loads((Path(__file__).parent / "coastline50.json").read_text())
    return [np.array(line, dtype=float) for line in data["lines"]]


def _coast_pixels(raster: Raster, pw: int, ph: int):
    (west, north), (east, _), _, (_, south) = raster.corners
    y0, y1 = _merc(south), _merc(north)
    out = []
    for line in _coastlines():
        lon = line[:, 0]
        if east > 180:  # boxes across the date line use longitudes beyond 180
            lon = np.where(lon < west - 1e-9, lon + 360, lon)
        inside = (lon >= west - 1) & (lon <= east + 1) & (line[:, 1] >= south - 1) & (line[:, 1] <= north + 1)
        if not inside.any():
            continue
        x = (lon - west) / (east - west) * pw
        y = (y1 - _merc(line[:, 1])) / (y1 - y0) * ph
        # split where a segment jumps (date line) so no line crosses the panel
        pts = list(zip(x.tolist(), y.tolist()))
        segment = [pts[0]]
        for a, b in zip(pts, pts[1:]):
            if abs(b[0] - a[0]) > pw / 2:
                out.append(segment)
                segment = []
            segment.append(b)
        out.append(segment)
    return out


# ---------------------------------------------------------------------------
# rain at a place
# ---------------------------------------------------------------------------
def point_series(start: str, n_days: int, lat: float, lon: float, pardig_on_era5_grid: bool) -> dict:
    """Hourly rain at the grid cells containing a point, for both sources."""
    days = [d for d in DAYS.days if d >= start][:n_days]
    lon360 = lon % 360
    times, e, p = [], [], []
    for day in days:
        ds = open_day(day)
        times.extend(pd.DatetimeIndex(ds["time"].values))
        e.extend(ds["era5"].sel(lat_era5=lat, lon_era5=lon360, method="nearest").values.tolist())
        if pardig_on_era5_grid:
            band = _pardig_on_era5_grid(ds["pardig"], lat - 0.3, lat + 0.3)
            p.extend(band.sel(lat_era5=lat, lon_era5=lon360, method="nearest").values.tolist())
        else:
            p.extend(ds["pardig"].sel(lat_pardig=lat, lon_pardig=lon360, method="nearest").values.tolist())
    return {"time": times, "era5": np.array(e, float), "pardig": np.array(p, float)}