EmmaScharfmann HF Staff commited on
Commit
59a662c
·
verified ·
1 Parent(s): e5a511b

Animated ERA5 | PARDIG maps; statistics removed

Browse files
Files changed (6) hide show
  1. ABOUT.md +16 -39
  2. README.md +7 -8
  3. app.py +91 -501
  4. maps.py +122 -153
  5. rainmaps.js +149 -0
  6. requirements.txt +1 -4
ABOUT.md CHANGED
@@ -1,47 +1,24 @@
1
- ## What is compared
2
 
3
- - **ERA5** hourly total precipitation (`tp`, the depth over the hour ending at the time stamp), 0.25°,
4
- read from Earthmover (`earthmover-public/era5`) or, as a fallback for the most recent days,
5
- Google's public ARCO copy. Days after the final ERA5 release are the preliminary **ERA5T** and may be
6
- revised; the summary says how many.
7
- - **PARDIG-NRT**, instantaneous rates every 15 min on a 0.1° grid, turned into hourly depths as in the
8
- PARDIG paper (Eq. A.3.8: the hour ending at *t* is ¼ h × the rates at *t*−45, −30, −15 and 0 min),
9
- then averaged onto ERA5's grid with area-conservative weights. ERA5 is never interpolated.
 
10
 
11
- A UTC day is the 24 hours ending at 01:00 … 24:00. The 6 h windows end at 06, 12, 18 and 24 UTC.
12
-
13
- ## How a region is scored
14
-
15
- A daily job reduces each day to area-weighted sums on **1° tiles** (4 × 4 ERA5 cells): moments of
16
- the two fields and their difference, event counts at fixed thresholds, fractions-skill-score terms at
17
- six neighbourhood sizes, intensity histograms and hourly sums by UTC hour. Every score shown is a ratio of
18
- sums, so it is exact for any union of tiles and days: the box you enter is snapped to the tiles whose
19
- centre falls inside it. Cells are weighted by their area. The definitions follow
20
- `precipitation_metrics.py` in [weather-forecast-model-downscaler](https://github.com/EmmaScharfmann/weather-forecast-model-downscaler/pull/8):
21
-
22
- | Question | Scores |
23
- | --- | --- |
24
- | How much? | mean of each, bias, relative bias, MAE, RMSE, correlation (ERA5 is deterministic: CRPS = MAE) |
25
- | How often? | event frequency, frequency bias (ERA5 events / PARDIG events), CSI, ETS, at thresholds per window |
26
- | How intense? | frequency and share of total rain per intensity bin; quantiles interpolated from the bins |
27
- | When? | mean rain and wet-hour frequency by local solar hour (each tile shifted by its longitude / 15) |
28
- | At what scale? | fractions skill score against neighbourhood width; "useful" when FSS ≥ 0.5 + f/2 (Roberts & Lean 2008) |
29
-
30
- Fractions are computed on the global grid before tiles are summed, so neighbourhoods reach past the box.
31
- Neighbourhood widths are in 0.25° cells (1, 3, 5, 9, 17, 33); the kilometres shown are approximate for the
32
- box's central latitude.
33
 
34
  ## Caveats
35
 
36
- - **PARDIG is a reference, not the truth.** It is a learned reconstruction from satellite and analysis
37
- inputs, calibrated against GPM CORRA. Its documented weak spots are snowfall, drizzle and complex
38
- terrain (e.g. the Alps), and it caps instantaneous rates at **75 mm/h**. Part of ERA5's apparent excess of
39
- drizzle may be PARDIG missing drizzle; differences at high latitudes and over ice are the least
40
- trustworthy.
41
- - ERA5 is compared on its own 0.25° grid. PARDIG's 0.1° detail is averaged away, which favours ERA5.
42
- - Scores start on 1 January 2026, when PARDIG-NRT switched to one store per time step.
43
 
44
  ## Data
45
 
46
- Scores: [`EmmaScharfmann/era5-pardig-scores`](https://huggingface.co/datasets/EmmaScharfmann/era5-pardig-scores),
47
- one file per month, updated daily. Coastlines: Natural Earth (public domain).
 
1
+ ## What you are looking at
2
 
3
+ - **ERA5**: ECMWF's reanalysis, hourly total precipitation (`tp`, the rain that fell in the hour ending at
4
+ the time stamp) on its native 0.25° grid, drawn cell by cell. Read from Earthmover (`earthmover-public/era5`)
5
+ up to 30 June 2026 and from Google's ARCO copy after that; the later days are the preliminary ERA5T and
6
+ may still be revised.
7
+ - **PARDIG-NRT**: Google DeepMind's rainfall reconstruction from satellite and analysis inputs, every 15 minutes
8
+ at 0.1°. Each hour shown is ¼ h × the rates at *t*−45, −30, −15 and 0 min (PARDIG paper, Eq. A.3.8), the
9
+ same hour as ERA5. With **PARDIG grid: 0.25°**, PARDIG is first averaged onto ERA5's cells
10
+ (area-conservative), so both have the same resolution.
11
 
12
+ Both use the same colours; areas with less than the first level are left clear. Hours are labelled in UTC.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  ## Caveats
15
 
16
+ - **PARDIG is a reference, not the truth.** It is a learned estimate, calibrated against GPM CORRA, with
17
+ known weak spots in snowfall, drizzle and complex terrain (e.g. the Alps), and it caps rates at 75 mm/h.
18
+ Part of the light rain ERA5 shows where PARDIG shows none may be drizzle PARDIG misses.
19
+ - Maps cover 2026 from 1 January; new days are added daily, a few days behind real time.
 
 
 
20
 
21
  ## Data
22
 
23
+ Hourly maps and daily scores: [`EmmaScharfmann/era5-pardig-scores`](https://huggingface.co/datasets/EmmaScharfmann/era5-pardig-scores).
24
+ Basemap © OpenStreetMap contributors © CARTO.
README.md CHANGED
@@ -9,18 +9,17 @@ python_version: "3.12"
9
  app_file: app.py
10
  pinned: false
11
  license: apache-2.0
12
- short_description: How wrong is ERA5 rainfall? Scored daily vs PARDIG
13
  datasets:
14
  - EmmaScharfmann/era5-pardig-scores
15
  ---
16
 
17
  # ERA5 vs PARDIG
18
 
19
- ERA5 hourly precipitation scored against PARDIG-NRT every day since 1 January 2026, on 1° tiles
20
- that any latitude/longitude box adds up: amounts, drizzle and heavy-rain frequencies, intensity
21
- distribution, diurnal cycle, spatial scale (FSS) and daily series.
22
 
23
- - `app.py`, `ABOUT.md`: the interface.
24
- - `pardig_eval/`: readers (PARDIG, ERA5 from Earthmover or ARCO), regridding, per-tile sums and
25
- scores. The daily HF Job mounts this repository and runs `pardig_eval.run`.
26
- - Scores: [`EmmaScharfmann/era5-pardig-scores`](https://huggingface.co/datasets/EmmaScharfmann/era5-pardig-scores).
 
 
9
  app_file: app.py
10
  pinned: false
11
  license: apache-2.0
12
+ short_description: Watch ERA5 and PARDIG rainfall side by side, hour by hour
13
  datasets:
14
  - EmmaScharfmann/era5-pardig-scores
15
  ---
16
 
17
  # ERA5 vs PARDIG
18
 
19
+ ERA5's hourly rain next to PARDIG-NRT's, animated over any region, for every day since 1 January 2026.
 
 
20
 
21
+ - `app.py`, `maps.py`, `rainmaps.js`: the interface. `maps.py` turns each hour into a paletted PNG on
22
+ Web-Mercator rows; `rainmaps.js` plays them on two synchronised MapLibre maps.
23
+ - `pardig_eval/`: readers (PARDIG, ERA5 from Earthmover or ARCO), regridding, stored maps and scores. The
24
+ daily HF Job mounts this repository and runs `pardig_eval.run`.
25
+ - Data: [`EmmaScharfmann/era5-pardig-scores`](https://huggingface.co/datasets/EmmaScharfmann/era5-pardig-scores).
app.py CHANGED
@@ -1,483 +1,121 @@
1
- """ERA5 vs PARDIG: how ERA5's hourly precipitation differs from PARDIG-NRT, for any region.
2
-
3
- Reads the monthly per-tile sums written by the daily job (``pardig_eval.run``) from a Hub
4
- dataset, adds up the tiles of the chosen box and months, and turns the sums into scores.
5
- """
6
 
7
  from __future__ import annotations
8
 
9
- import json
10
  import logging
11
- import os
12
- import threading
13
- import time
14
  from pathlib import Path
15
 
16
  import gradio as gr
17
- import numpy as np
18
- import pandas as pd
19
- import plotly.graph_objects as go
20
- import xarray as xr
21
 
22
  import maps
23
- from pardig_eval import grid, scores, sums
24
 
25
  logging.basicConfig(level=logging.INFO)
26
- logger = logging.getLogger("app")
27
-
28
  HERE = Path(__file__).parent
29
- DATA_REPO = os.environ.get("DATA_REPO", "EmmaScharfmann/era5-pardig-scores")
30
- DATA_DIR = os.environ.get("DATA_DIR") # local folder with months/*.nc, instead of the Hub
31
- REFRESH_S = 1800
32
-
33
- # Validated reference palette (dataviz skill): ERA5 = slot 1 blue, PARDIG = slot 2 orange.
34
- ERA5_C, PARDIG_C = "#2a78d6", "#eb6834"
35
- EXTRA_C = ["#2a78d6", "#eb6834", "#1baf7a"] # three-series cap for line sets
36
- INK, MUTED, GRID = "#52514e", "#898781", "rgba(137,135,129,0.25)"
37
- DIVERGING = [[0, "#b8322f"], [0.25, "#e88a7f"], [0.5, "#e8e7e3"], [0.75, "#86b6ef"], [1, "#1c5cab"]]
38
- SEQUENTIAL = [[0, "#f4f8fd"], [0.15, "#cde2fb"], [0.4, "#6da7ec"], [0.7, "#256abf"], [1, "#0d366b"]]
39
 
40
  REGIONS = {
41
- "Global": (-90, 90, -180, 180),
42
- "60°S–60°N": (-60, 60, -180, 180),
43
- "Tropics (20°S–20°N)": (-20, 20, -180, 180),
44
  "Europe": (35, 72, -25, 45),
45
  "France": (41, 51.5, -5.5, 10),
46
- "North America": (15, 72, -170, -50),
 
 
 
47
  "Contiguous US": (24, 50, -125, -66),
48
- "South America": (-56, 13, -82, -34),
49
  "Amazon": (-15, 5, -75, -45),
50
- "Africa": (-35, 37, -18, 52),
51
- "Sahel": (10, 20, -18, 40),
52
  "South Asia (India)": (5, 35, 65, 95),
53
  "East Asia": (20, 50, 100, 145),
54
  "Maritime Continent": (-11, 8, 95, 150),
55
  "Australia": (-45, -10, 110, 155),
56
- "Southern Ocean storm track": (-65, -40, -180, 180),
57
  }
 
 
 
58
 
59
- MAP_METRICS = {
60
- "Bias (ERA5 − PARDIG), mm": "bias_mm",
61
- "Relative bias (ERA5 / PARDIG − 1)": "relative_bias",
62
- "ERA5 mean, mm": "era5_mean_mm",
63
- "PARDIG mean, mm": "pardig_mean_mm",
64
- "MAE (= CRPS for ERA5), mm": "mae_mm",
65
- "RMSE, mm": "rmse_mm",
66
- "Frequency bias at threshold": "frequency_bias",
67
- "CSI at threshold": "csi",
68
- }
69
- WINDOW_LABELS = {"1 hour": 1, "6 hours": 6, "24 hours": 24}
70
-
71
- COAST = json.loads((HERE / "coastline.json").read_text())
72
-
73
-
74
- # ---------------------------------------------------------------------------
75
- # data
76
- # ---------------------------------------------------------------------------
77
- class Months:
78
- """All month files, loaded in memory and refreshed from the Hub every REFRESH_S seconds."""
79
-
80
- def __init__(self):
81
- self.lock = threading.Lock()
82
- self.data: dict[str, xr.Dataset] = {}
83
- self.revision = None
84
- self.checked = 0.0
85
- self.refresh(force=True)
86
-
87
- def _folder(self) -> Path:
88
- if DATA_DIR:
89
- return Path(DATA_DIR)
90
- from huggingface_hub import HfApi, snapshot_download
91
-
92
- info = HfApi().dataset_info(DATA_REPO)
93
- if info.sha == self.revision:
94
- return None
95
- self.revision = info.sha
96
- return Path(snapshot_download(DATA_REPO, repo_type="dataset", allow_patterns="months/*.nc",
97
- revision=info.sha))
98
-
99
- def refresh(self, force=False):
100
- if not force and time.time() - self.checked < REFRESH_S:
101
- return
102
- with self.lock:
103
- self.checked = time.time()
104
- try:
105
- folder = self._folder()
106
- except Exception as exc: # keep serving what we have
107
- logger.warning("could not refresh data: %s", exc)
108
- return
109
- if folder is None:
110
- return
111
- data = {}
112
- for path in sorted((folder / "months").glob("*.nc")):
113
- with xr.open_dataset(path, engine="h5netcdf") as ds:
114
- data[path.stem] = ds.load()
115
- self.data = data
116
- logger.info("loaded %d month(s): %s", len(data), ", ".join(data))
117
-
118
- def names(self) -> list[str]:
119
- return list(self.data)
120
-
121
- def days(self) -> pd.DatetimeIndex:
122
- return pd.DatetimeIndex(np.concatenate([d["day"].values for d in self.data.values()])) if self.data \
123
- else pd.DatetimeIndex([])
124
-
125
- def combine(self, first: str, last: str, box) -> tuple[xr.Dataset, xr.Dataset]:
126
- """(region totals over tiles and months, region per-tile sums over months)."""
127
- chosen = [m for m in self.data if first <= m <= last]
128
- if not chosen:
129
- raise gr.Error("No scored month in that range.")
130
- per_tile = None
131
- daily, sources, prelim = [], [], []
132
- for m in chosen:
133
- ds = scores.select(self.data[m], box)
134
- totals = ds.drop_vars(["daily", "era5_source", "era5_preliminary"])
135
- per_tile = totals if per_tile is None else per_tile + totals
136
- daily.append(ds["daily"])
137
- sources.extend(ds["era5_source"].values.tolist())
138
- prelim.extend(ds["era5_preliminary"].values.tolist())
139
- per_tile = per_tile.assign(daily=xr.concat(daily, "day"))
140
- per_tile.attrs.update(sources=sorted(set(sources)), preliminary_days=int(np.sum(prelim)),
141
- days=int(per_tile.sizes["day"]))
142
- return scores.total(per_tile.drop_vars("daily")), per_tile
143
-
144
-
145
- MONTHS = Months()
146
-
147
-
148
- # ---------------------------------------------------------------------------
149
- # figures
150
- # ---------------------------------------------------------------------------
151
- def _layout(fig: go.Figure, title: str, x: str, y: str, height=360) -> go.Figure:
152
- fig.update_layout(
153
- title=dict(text=title, x=0, xanchor="left", font=dict(size=15)),
154
- height=height, margin=dict(l=60, r=20, t=50, b=50),
155
- paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
156
- font=dict(family="system-ui, -apple-system, Segoe UI, sans-serif", color=INK, size=12),
157
- legend=dict(orientation="h", y=1.02, x=1, xanchor="right", yanchor="bottom"),
158
- hovermode="x unified",
159
- )
160
- fig.update_xaxes(title=x, gridcolor=GRID, linecolor=MUTED, zeroline=False)
161
- fig.update_yaxes(title=y, gridcolor=GRID, linecolor=MUTED, zeroline=False)
162
- return fig
163
-
164
-
165
- def _positive(values) -> np.ndarray:
166
- """Values for a log axis: zeros and negatives become gaps instead of plunging to -inf."""
167
- values = np.asarray(values, dtype=float)
168
- return np.where(values > 0, values, np.nan)
169
-
170
-
171
- def _box_shapes(box):
172
- lat0, lat1, lon0, lon1 = box
173
- if lon1 - lon0 >= 360:
174
- return [(-180, 180)]
175
- a, b = ((lon0 + 180) % 360) - 180, ((lon1 + 180) % 360) - 180
176
- if b == -180 and lon1 > lon0:
177
- b = 180
178
- return [(a, b)] if a < b else [(a, 180), (-180, b)]
179
-
180
-
181
- def map_figure(per_tile_all: xr.Dataset, metric_label: str, window: int, threshold: float | None, box) -> go.Figure:
182
- metric = MAP_METRICS[metric_label]
183
- values = scores.tile_map(per_tile_all, metric, window, threshold)
184
- lon = per_tile_all["tile_lon"].values
185
- lon = np.where(lon > 180, lon - 360, lon)
186
- order = np.argsort(lon)
187
- z = values.values[:, order]
188
- if metric in ("bias_mm", "relative_bias"):
189
- finite = np.abs(z[np.isfinite(z)])
190
- lim = float(np.quantile(finite, 0.98)) if finite.size else 1.0
191
- lim = min(lim, 1.0) if metric == "relative_bias" else lim
192
- scale, zmin, zmax = DIVERGING, -lim, lim
193
- elif metric == "frequency_bias":
194
- # Log-symmetric around 1: show log2 of the ratio.
195
- with np.errstate(divide="ignore", invalid="ignore"):
196
- z = np.log2(z)
197
- scale, zmin, zmax = DIVERGING, -2, 2
198
- else:
199
- finite = z[np.isfinite(z)]
200
- scale, zmin, zmax = SEQUENTIAL, 0, float(np.quantile(finite, 0.99)) if finite.size else 1
201
- colorbar = dict(thickness=12, len=0.8)
202
- if metric == "frequency_bias":
203
- colorbar.update(tickvals=[-2, -1, 0, 1, 2], ticktext=["¼", "½", "1", "2", "4"], title="ERA5 / PARDIG")
204
- fig = go.Figure(go.Heatmap(
205
- x=lon[order], y=per_tile_all["tile_lat"].values, z=z, colorscale=scale, zmin=zmin, zmax=zmax,
206
- colorbar=colorbar, hovertemplate="lat %{y:.2f}, lon %{x:.2f}<br>%{z:.3f}<extra></extra>"))
207
- fig.add_trace(go.Scatter(x=COAST["lon"], y=COAST["lat"], mode="lines", line=dict(color="#383835", width=0.7),
208
- hoverinfo="skip", showlegend=False))
209
- lat0, lat1, _, _ = box
210
- for a, b in _box_shapes(box):
211
- fig.add_shape(type="rect", x0=a, x1=b, y0=lat0, y1=lat1, line=dict(color="#0b0b0b", width=2))
212
- title = f"{metric_label}{f' ≥ {threshold:g} mm' if metric in ('csi', 'frequency_bias') else ''}, {window} h window"
213
- _layout(fig, title, "", "", height=460)
214
- fig.update_layout(hovermode="closest")
215
- fig.update_xaxes(range=[-180, 180], showgrid=False, ticksuffix="°")
216
- fig.update_yaxes(range=[-90, 90], showgrid=False, ticksuffix="°", scaleanchor="x", scaleratio=1)
217
- return fig
218
-
219
-
220
- def events_figures(t: xr.Dataset, window: int):
221
- occ = scores.occurrence(t).sel(window=window)
222
- th = occ["threshold_mm"].values
223
- labels = [f"≥ {x:g}" for x in th]
224
- freq = go.Figure()
225
- freq.add_trace(go.Scatter(x=labels, y=_positive(occ["era5_frequency"].values), name="ERA5", mode="lines+markers",
226
- line=dict(color=ERA5_C, width=2), marker=dict(size=8)))
227
- freq.add_trace(go.Scatter(x=labels, y=_positive(occ["pardig_frequency"].values), name="PARDIG", mode="lines+markers",
228
- line=dict(color=PARDIG_C, width=2), marker=dict(size=8)))
229
- _layout(freq, "How often each amount is reached", f"mm per {window} h", "fraction of area × time")
230
- freq.update_yaxes(type="log", tickformat="~%")
231
-
232
- ratio = _positive(occ["frequency_bias"].values)
233
- fb = go.Figure(go.Scatter(x=labels, y=ratio, mode="markers+text", marker=dict(color=ERA5_C, size=12),
234
- text=[f"{r:.2f}×" if np.isfinite(r) else "no ERA5 event" for r in ratio],
235
- textposition="middle right", textfont=dict(color=INK),
236
- name="frequency bias", hovertemplate="%{x} mm: %{y:.2f}<extra></extra>"))
237
- fb.add_hline(y=1, line=dict(color=MUTED, dash="dot"), annotation_text="unbiased",
238
- annotation_position="bottom right")
239
- _layout(fb, "Frequency bias: ERA5 events / PARDIG events", f"mm per {window} h", "ratio (log)")
240
- finite = ratio[np.isfinite(ratio)]
241
- lo = min(0.5, float(finite.min()) / 1.5) if finite.size else 0.1
242
- hi = max(2.0, float(finite.max()) * 1.5) if finite.size else 10
243
- ticks = [t for t in (0.05, 0.1, 0.25, 0.5, 1, 2, 4, 8) if lo <= t <= hi]
244
- fb.update_yaxes(type="log", range=[np.log10(lo), np.log10(hi)], tickvals=ticks,
245
- ticktext=[f"{t:g}×" for t in ticks], minor=dict(showgrid=False))
246
-
247
- skill = go.Figure()
248
- for name, color, key in (("CSI", ERA5_C, "csi"), ("ETS", PARDIG_C, "ets")):
249
- skill.add_trace(go.Scatter(x=labels, y=occ[key].values, name=name, mode="lines+markers",
250
- line=dict(color=color, width=2), marker=dict(size=8)))
251
- _layout(skill, "Event skill: CSI and ETS", f"mm per {window} h", "score (1 = perfect)")
252
- skill.update_yaxes(range=[0, 1])
253
- return freq, fb, skill
254
-
255
-
256
- def intensity_figures(t: xr.Dataset, window: int):
257
- it = scores.intensity(t).sel(window=window)
258
- lo, hi = t["bin_low_mm"].values, t["bin_high_mm"].values
259
- labels = [f"{a:g}–{b:g}" if np.isfinite(b) else f"≥ {a:g}" for a, b in zip(lo, hi)]
260
- labels[0] = f"< {hi[0]:g} (dry)"
261
- share = go.Figure()
262
- for src, name, color in (("era5", "ERA5", ERA5_C), ("pardig", "PARDIG", PARDIG_C)):
263
- share.add_trace(go.Bar(x=labels[1:], y=it["rain_share"].sel(source=src).values[1:], name=name,
264
- marker=dict(color=color, cornerradius=4)))
265
- _layout(share, "Where the rain comes from: share of the total by intensity", f"mm per {window} h",
266
- "share of total rain")
267
- share.update_layout(bargap=0.25, bargroupgap=0.08)
268
- share.update_yaxes(tickformat=".0%")
269
- freq = go.Figure()
270
- for src, name, color in (("era5", "ERA5", ERA5_C), ("pardig", "PARDIG", PARDIG_C)):
271
- freq.add_trace(go.Bar(x=labels, y=_positive(it["frequency"].sel(source=src).values), name=name,
272
- marker=dict(color=color, cornerradius=4)))
273
- _layout(freq, "How often each intensity occurs", f"mm per {window} h", "frequency (log)")
274
- freq.update_layout(bargap=0.25, bargroupgap=0.08)
275
- freq.update_yaxes(type="log", tickformat="~%")
276
- q = scores.quantiles(t).sel(window=window)["quantile_mm"].to_pandas()
277
- table = pd.DataFrame({
278
- "quantile": [f"{x * 100:g}th" for x in q.index],
279
- f"ERA5, mm / {window} h": q["era5"].round(2).values,
280
- f"PARDIG, mm / {window} h": q["pardig"].round(2).values,
281
- "ERA5 / PARDIG": (q["era5"] / q["pardig"]).round(2).values,
282
- })
283
- return share, freq, table
284
-
285
-
286
- def diurnal_figures(per_tile: xr.Dataset):
287
- d = scores.diurnal(per_tile)
288
- hours = d["local_hour"].values
289
- figs = []
290
- for key, title, ylab, fmt in (("rain_mm_h", "Mean rain by local solar hour", "mm/h", ".3f"),
291
- ("wet_frequency", "Wet hours (≥ 0.1 mm) by local solar hour", "fraction", ".0%")):
292
- fig = go.Figure()
293
- for src, name, color in (("era5", "ERA5", ERA5_C), ("pardig", "PARDIG", PARDIG_C)):
294
- fig.add_trace(go.Scatter(x=hours, y=d[key].sel(source=src).values, name=name, mode="lines",
295
- line=dict(color=color, width=2)))
296
- _layout(fig, title, "local solar hour (end of the hour)", ylab)
297
- fig.update_xaxes(dtick=3, range=[0, 23])
298
- fig.update_yaxes(tickformat=fmt, rangemode="tozero")
299
- figs.append(fig)
300
- return figs
301
-
302
-
303
- def scale_figure(t: xr.Dataset, window: int, box):
304
- st = scores.structure(t).sel(window=window)
305
- mid_lat = np.deg2rad(np.clip((box[0] + box[1]) / 2, -80, 80))
306
- km = np.array(sums.FSS_SCALES) * 0.25 * 111.2 * np.sqrt(np.cos(mid_lat)) # geometric mean of the cell sides
307
- fig = go.Figure()
308
- for i, th in enumerate(st["fss_threshold_mm"].values):
309
- fig.add_trace(go.Scatter(x=km, y=st["fss"].isel(fss_threshold=i).values, name=f"≥ {th:g} mm",
310
- mode="lines+markers", line=dict(color=EXTRA_C[i], width=2), marker=dict(size=8)))
311
- fig.add_hline(y=float(st["useful_fss"].isel(fss_threshold=i)),
312
- line=dict(color=EXTRA_C[i], dash="dot", width=1))
313
- _layout(fig, "Fractions skill score against neighbourhood size (dotted: 'useful' level)",
314
- "neighbourhood width, km (approx., at the box's centre)", "FSS")
315
- fig.update_xaxes(type="log", tickvals=km, ticktext=[f"{k:.0f}" for k in km], minor=dict(showgrid=False))
316
- fig.update_yaxes(range=[0, 1])
317
- return fig
318
-
319
-
320
- def daily_figures(per_tile: xr.Dataset):
321
- d = scores.daily(per_tile)
322
- days = pd.DatetimeIndex(d["day"].values)
323
- amounts = go.Figure()
324
- for key, name, color in (("era5_mm", "ERA5", ERA5_C), ("pardig_mm", "PARDIG", PARDIG_C)):
325
- amounts.add_trace(go.Scatter(x=days, y=d[key].values, name=name, mode="lines+markers",
326
- line=dict(color=color, width=2), marker=dict(size=6)))
327
- _layout(amounts, "Daily mean rain over the region", "", "mm/day")
328
- amounts.update_yaxes(rangemode="tozero")
329
- skill = go.Figure()
330
- for i, t in enumerate((1, 10, 50)):
331
- skill.add_trace(go.Scatter(x=days, y=d[f"csi_{t}mm"].values, name=f"≥ {t} mm/day", mode="lines+markers",
332
- line=dict(color=EXTRA_C[i], width=2), marker=dict(size=6)))
333
- _layout(skill, "Daily CSI of 24 h totals", "", "CSI")
334
- skill.update_yaxes(range=[0, 1])
335
- return amounts, skill
336
-
337
-
338
- def scorecard(t: xr.Dataset) -> pd.DataFrame:
339
- a = scores.amount(t)
340
- rows = []
341
- for w in sums.WINDOWS:
342
- x = a.sel(window=w)
343
- rows.append({
344
- "window": f"{w} h",
345
- "ERA5 mean, mm": round(float(x.era5_mean_mm), 3),
346
- "PARDIG mean, mm": round(float(x.pardig_mean_mm), 3),
347
- "bias, mm": round(float(x.bias_mm), 3),
348
- "relative bias": f"{float(x.relative_bias):+.0%}",
349
- "MAE (= CRPS), mm": round(float(x.mae_mm), 3),
350
- "RMSE, mm": round(float(x.rmse_mm), 3),
351
- "correlation": round(float(x.correlation), 2),
352
- })
353
- return pd.DataFrame(rows)
354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
 
356
- def headline(t: xr.Dataset, per_tile: xr.Dataset, box_label: str) -> str:
357
- occ = scores.occurrence(t).sel(window=1)
358
- a = scores.amount(t).sel(window=24)
359
- q = scores.quantiles(t, qs=(0.999,)).sel(window=1, quantile=0.999)["quantile_mm"]
360
- fb = occ["frequency_bias"].values
361
- th = occ["threshold_mm"].values
362
- heavy = int(np.nanargmax(np.where(np.isfinite(fb) & (occ["pardig_frequency"].values > 1e-4), th, -1)))
363
- d = scores.diurnal(per_tile)["rain_mm_h"]
364
- peak_e, peak_p = int(d.sel(source="era5").argmax()), int(d.sel(source="pardig").argmax())
365
- attrs = per_tile.attrs
366
- lines = [
367
- f"### {box_label}: {attrs['days']} day(s) scored",
368
- f"- **Totals**: ERA5 {float(a.era5_mean_mm):.2f} mm/day vs PARDIG {float(a.pardig_mean_mm):.2f} "
369
- f"({float(a.relative_bias):+.0%}).",
370
- f"- **Drizzle**: ERA5 has **{fb[0]:.1f}×** as many hours with ≥ {th[0]:g} mm as PARDIG.",
371
- f"- **Heavy rain**: hours with ≥ {th[heavy]:g} mm are **{fb[heavy]:.2f}×** as frequent in ERA5.",
372
- f"- **Extremes**: the 99.9th percentile of hourly rain is {float(q.sel(source='era5')):.1f} mm in ERA5 "
373
- f"vs {float(q.sel(source='pardig')):.1f} mm in PARDIG.",
374
- f"- **Timing**: mean rain peaks at {peak_e:02d}:00 local solar time in ERA5, {peak_p:02d}:00 in PARDIG.",
375
- f"\n<small>ERA5 from {', '.join(attrs['sources'])}"
376
- f"{f'; {attrs['preliminary_days']} day(s) are preliminary ERA5T' if attrs['preliminary_days'] else ''}."
377
- " Tiles are 1°: the box is snapped to the tiles whose centre falls inside it.</small>",
378
- ]
379
- return "\n".join(lines)
380
 
381
 
382
- # ---------------------------------------------------------------------------
383
- # callbacks
384
- # ---------------------------------------------------------------------------
385
  def _box(lat0, lat1, lon0, lon1):
386
  try:
387
  box = tuple(float(v) for v in (lat0, lat1, lon0, lon1))
388
  except (TypeError, ValueError):
389
  raise gr.Error("Enter four numbers for the box.")
390
- if not (-90 <= box[0] < box[1] <= 90):
391
- raise gr.Error("Latitudes must satisfy -90 ≤ south < north ≤ 90.")
392
- rows, cols = grid.tiles_in_box(*box)
393
- if not rows.any() or not cols.any():
394
- raise gr.Error("The box contains no 1° tile centre; make it larger.")
395
  return box
396
 
397
 
398
- def month_choices(first, last):
399
- """Refresh the month lists with months added since the app started."""
400
- MONTHS.refresh()
401
- names = MONTHS.names()
402
- first = first if first in names else (names[0] if names else None)
403
- last = names[-1] if names else None # a fresh page always ends at the latest month
404
- return gr.update(choices=names, value=first), gr.update(choices=names, value=last)
405
-
406
-
407
  def choose_region(name):
408
- lat0, lat1, lon0, lon1 = REGIONS[name]
409
- return lat0, lat1, lon0, lon1
410
-
411
 
412
- def evaluate(region, lat0, lat1, lon0, lon1, first, last, window_label, map_metric, threshold):
413
- """Score ERA5 against PARDIG over a lat/lon box and a range of months.
414
 
415
- Args:
416
- region: preset name, used as the title.
417
- lat0: southern edge, degrees north.
418
- lat1: northern edge, degrees north.
419
- lon0: western edge, degrees east (-180..360; west > east crosses the date line).
420
- lon1: eastern edge, degrees east.
421
- first: first month, YYYY-MM.
422
- last: last month, YYYY-MM.
423
- window_label: accumulation window, "1 hour", "6 hours" or "24 hours".
424
- map_metric: metric drawn on the world map.
425
- threshold: threshold (mm per window) for the CSI and frequency-bias maps.
426
- """
427
- MONTHS.refresh()
428
- if not MONTHS.data:
429
- raise gr.Error("No day has been scored yet: the first ones are being computed.")
430
- first = first or MONTHS.names()[0]
431
- last = last or MONTHS.names()[-1]
432
- box = _box(lat0, lat1, lon0, lon1)
433
- window = WINDOW_LABELS[window_label]
434
- if first > last:
435
- first, last = last, first
436
- t, per_tile = MONTHS.combine(first, last, box)
437
- _, world = MONTHS.combine(first, last, None)
438
- label = region if REGIONS.get(region) == box else f"{box[0]:g}..{box[1]:g}°N, {box[2]:g}..{box[3]:g}°E"
439
- thresholds = list(sums.THRESHOLDS[window])
440
- threshold = float(threshold) if threshold and float(threshold) in thresholds else thresholds[2]
441
- freq, fb, skill = events_figures(t, window)
442
- share, hist, qtable = intensity_figures(t, window)
443
- diurnal_rain, diurnal_wet = diurnal_figures(per_tile)
444
- amounts, daily_skill = daily_figures(per_tile)
445
- return (
446
- headline(t, per_tile, label),
447
- scorecard(t),
448
- map_figure(world, map_metric, window, threshold, box),
449
- gr.update(choices=[str(x) for x in thresholds], value=str(threshold)),
450
- freq, fb, skill, share, hist, qtable, diurnal_rain, diurnal_wet,
451
- scale_figure(t, window, box), amounts, daily_skill,
452
- )
453
-
454
-
455
- # ---------------------------------------------------------------------------
456
- # maps tab
457
- # ---------------------------------------------------------------------------
458
- HOURS = ["Daily total"] + [f"{h:02d}:00–{h + 1:02d}:00 UTC" for h in range(24)]
459
- PARDIG_GRIDS = {"0.1° (native)": False, "0.25° (ERA5 grid)": True}
460
-
461
-
462
- def show_maps(lat0, lat1, lon0, lon1, day, hour_label, pardig_grid):
463
- """ERA5 and PARDIG rain maps of a box for one day (daily total) or one hour.
464
 
465
  Args:
466
  lat0: southern edge, degrees north.
467
  lat1: northern edge, degrees north.
468
  lon0: western edge, degrees east.
469
  lon1: eastern edge, degrees east.
470
- day: YYYY-MM-DD.
471
- hour_label: "Daily total" or "HH:00–HH:00 UTC".
 
472
  pardig_grid: "0.1° (native)" or "0.25° (ERA5 grid)".
473
  """
474
  maps.DAYS.refresh()
475
  if not maps.DAYS.days:
476
  raise gr.Error("No maps stored yet.")
477
  box = _box(lat0, lat1, lon0, lon1)
478
- day = day if day in maps.DAYS.days else maps.DAYS.days[-1]
479
- hour = None if hour_label == HOURS[0] else HOURS.index(hour_label)
480
- return maps.render(day, hour, box, PARDIG_GRIDS[pardig_grid])
481
 
482
 
483
  def day_choices(day):
@@ -493,97 +131,49 @@ def step_day(day, step):
493
  return gr.update(value=days[min(max(days.index(day) + step, 0), len(days) - 1)])
494
 
495
 
496
- # ---------------------------------------------------------------------------
497
- # interface
498
- # ---------------------------------------------------------------------------
499
  ABOUT = (HERE / "ABOUT.md").read_text()
500
- CSS = ".compact-row { gap: 8px; } footer { display: none !important; }"
501
 
502
- with gr.Blocks(title="ERA5 vs PARDIG", css=CSS) as demo:
503
  gr.Markdown(
504
  "# ERA5 vs PARDIG\n"
505
- "ERA5's rainfall next to **PARDIG-NRT**, Google DeepMind's 0.1° satellite-based rainfall reconstruction. "
506
- "PARDIG is an estimate too, not ground truth (see *About*).")
507
- with gr.Row(equal_height=True, elem_classes="compact-row"):
 
508
  region = gr.Dropdown(list(REGIONS), value="Europe", label="Region", scale=2)
509
- day = gr.Dropdown(maps.DAYS.days, value=maps.DAYS.days[-1] if maps.DAYS.days else None,
510
- label="Day", scale=2)
511
  prev_day = gr.Button("◀", scale=0, min_width=44)
512
  next_day = gr.Button("▶", scale=0, min_width=44)
513
- hour = gr.Dropdown(HOURS, value=HOURS[0], label="Time", scale=2)
 
514
  pardig_grid = gr.Radio(list(PARDIG_GRIDS), value="0.1° (native)", label="PARDIG grid", scale=2)
515
  with gr.Accordion("Custom box", open=False):
516
  with gr.Row():
517
- lat0 = gr.Number(REGIONS["Europe"][0], label="South (°N)", minimum=-90, maximum=90)
518
- lat1 = gr.Number(REGIONS["Europe"][1], label="North (°N)", minimum=-90, maximum=90)
519
  lon0 = gr.Number(REGIONS["Europe"][2], label="West (°E)")
520
  lon1 = gr.Number(REGIONS["Europe"][3], label="East (°E)")
521
- apply_box = gr.Button("Apply", scale=0, min_width=90)
522
 
523
  with gr.Tabs():
524
  with gr.Tab("Maps"):
525
- with gr.Row(equal_height=True):
526
- era5_map = gr.Plot(show_label=False)
527
- pardig_map = gr.Plot(show_label=False)
528
- map_legend = gr.HTML()
529
- map_stats = gr.Markdown()
530
- with gr.Tab("Statistics") as stats_tab:
531
- with gr.Row():
532
- months = MONTHS.names()
533
- first = gr.Dropdown(months, value=months[0] if months else None, label="From month")
534
- last = gr.Dropdown(months, value=months[-1] if months else None, label="To month")
535
- window = gr.Radio(list(WINDOW_LABELS), value="1 hour", label="Accumulation window")
536
- summary = gr.Markdown()
537
- card = gr.Dataframe(label="Amounts (area-weighted)", interactive=False)
538
- with gr.Accordion("World map of a score", open=False):
539
- with gr.Row():
540
- map_metric = gr.Dropdown(list(MAP_METRICS), value="Relative bias (ERA5 / PARDIG − 1)",
541
- label="Metric")
542
- threshold = gr.Dropdown(["1.0"], value="1.0", label="Threshold, mm per window")
543
- world = gr.Plot(show_label=False)
544
- with gr.Accordion("Drizzle and heavy rain", open=False):
545
- with gr.Row():
546
- ev_freq = gr.Plot(show_label=False)
547
- ev_fb = gr.Plot(show_label=False)
548
- ev_skill = gr.Plot(show_label=False)
549
- with gr.Accordion("Intensity", open=False):
550
- in_share = gr.Plot(show_label=False)
551
- in_freq = gr.Plot(show_label=False)
552
- in_q = gr.Dataframe(label="Quantiles of all values, dry included (approximate)", interactive=False)
553
- with gr.Accordion("Diurnal cycle", open=False):
554
- with gr.Row():
555
- di_rain = gr.Plot(show_label=False)
556
- di_wet = gr.Plot(show_label=False)
557
- with gr.Accordion("Spatial scale", open=False):
558
- fss = gr.Plot(show_label=False)
559
- with gr.Accordion("Day by day", open=False):
560
- da_amount = gr.Plot(show_label=False)
561
- da_skill = gr.Plot(show_label=False)
562
  with gr.Tab("About"):
563
  gr.Markdown(ABOUT)
564
 
565
- box_inputs = [lat0, lat1, lon0, lon1]
566
- map_inputs = box_inputs + [day, hour, pardig_grid]
567
- map_outputs = [era5_map, pardig_map, map_legend, map_stats]
568
- stat_inputs = [region] + box_inputs + [first, last, window, map_metric, threshold]
569
- stat_outputs = [summary, card, world, threshold, ev_freq, ev_fb, ev_skill, in_share, in_freq, in_q,
570
- di_rain, di_wet, fss, da_amount, da_skill]
571
-
572
- region.change(choose_region, region, box_inputs, api_name=False).then(
573
- show_maps, map_inputs, map_outputs, api_name=False)
574
- apply_box.click(show_maps, map_inputs, map_outputs, api_name="maps")
575
- for control in (day, hour, pardig_grid):
576
- control.change(show_maps, map_inputs, map_outputs, api_name=False)
577
  prev_day.click(lambda d: step_day(d, -1), day, day, api_name=False)
578
  next_day.click(lambda d: step_day(d, 1), day, day, api_name=False)
579
-
580
- stats_tab.select(evaluate, stat_inputs, stat_outputs, api_name="evaluate")
581
- for control in (first, last, window, map_metric):
582
- control.change(evaluate, stat_inputs, stat_outputs, api_name=False)
583
- threshold.input(evaluate, stat_inputs, stat_outputs, api_name=False)
584
-
585
- demo.load(day_choices, day, day, api_name=False).then(show_maps, map_inputs, map_outputs, api_name=False)
586
- demo.load(month_choices, [first, last], [first, last], api_name=False)
587
 
588
  if __name__ == "__main__":
589
- demo.launch(mcp_server=True)
 
1
+ """ERA5 vs PARDIG: watch ERA5's and PARDIG's rain move over a region, hour by hour, side by side."""
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
 
5
  import logging
 
 
 
6
  from pathlib import Path
7
 
8
  import gradio as gr
 
 
 
 
9
 
10
  import maps
 
11
 
12
  logging.basicConfig(level=logging.INFO)
 
 
13
  HERE = Path(__file__).parent
 
 
 
 
 
 
 
 
 
 
14
 
15
  REGIONS = {
 
 
 
16
  "Europe": (35, 72, -25, 45),
17
  "France": (41, 51.5, -5.5, 10),
18
+ "British Isles": (49, 61, -11, 3),
19
+ "Alps": (43, 49, 4, 17),
20
+ "Iberia": (35, 44.5, -10, 4),
21
+ "Scandinavia": (54, 71.5, 4, 32),
22
  "Contiguous US": (24, 50, -125, -66),
23
+ "US Southeast": (25, 37, -95, -75),
24
  "Amazon": (-15, 5, -75, -45),
25
+ "West Africa & Sahel": (2, 22, -18, 15),
 
26
  "South Asia (India)": (5, 35, 65, 95),
27
  "East Asia": (20, 50, 100, 145),
28
  "Maritime Continent": (-11, 8, 95, 150),
29
  "Australia": (-45, -10, 110, 155),
 
30
  }
31
+ SPANS = {"1 day": 1, "2 days": 2, "3 days": 3}
32
+ VIEWS = {"Hour by hour": "hourly", "Total": "total"}
33
+ PARDIG_GRIDS = {"0.1° (native)": False, "0.25° (ERA5 grid)": True}
34
 
35
+ COMPONENT_HTML = """
36
+ <div class="rm">
37
+ <div class="rm-maps">
38
+ <div class="rm-panel"><div class="rm-title" data-src="era5">ERA5</div><div class="rm-map" data-map="era5"></div></div>
39
+ <div class="rm-panel"><div class="rm-title" data-src="pardig">PARDIG</div><div class="rm-map" data-map="pardig"></div></div>
40
+ </div>
41
+ <div class="rm-bar">
42
+ <button class="rm-play" aria-label="Pause">❚❚</button>
43
+ <input class="rm-slider" type="range" min="0" max="0" value="0" aria-label="Hour">
44
+ <span class="rm-time"></span>
45
+ <select class="rm-speed" aria-label="Speed">
46
+ <option value="900">Slow</option><option value="450" selected>Normal</option><option value="180">Fast</option>
47
+ </select>
48
+ </div>
49
+ <div class="rm-legend"></div>
50
+ <div class="rm-status"></div>
51
+ </div>
52
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ COMPONENT_CSS = """
55
+ .rm { display: flex; flex-direction: column; gap: 10px; }
56
+ .rm-maps { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
57
+ @media (max-width: 760px) { .rm-maps { grid-template-columns: 1fr; } }
58
+ .rm-panel { border: 1px solid var(--border-color-primary); border-radius: 8px; overflow: hidden; }
59
+ .rm-title { padding: 6px 10px; font-weight: 600; font-size: 14px; }
60
+ .rm-map { height: 520px; }
61
+ .rm-bar { display: flex; align-items: center; gap: 12px; }
62
+ .rm-play { width: 44px; height: 36px; border-radius: 8px; border: 1px solid var(--border-color-primary);
63
+ background: var(--button-secondary-background-fill); cursor: pointer; font-size: 15px; }
64
+ .rm-slider { flex: 1; accent-color: #2a78d6; }
65
+ .rm-time { min-width: 270px; font-variant-numeric: tabular-nums; font-size: 14px; }
66
+ .rm-speed { height: 36px; border-radius: 8px; border: 1px solid var(--border-color-primary);
67
+ background: var(--background-fill-primary); color: var(--body-text-color); padding: 0 6px; }
68
+ .rm-legend { display: flex; gap: 12px; align-items: flex-start; max-width: 760px; margin: 0 auto; width: 100%; }
69
+ .rm-leg-unit { font-size: 12px; white-space: nowrap; }
70
+ .rm-leg-unit span { color: var(--body-text-color-subdued); }
71
+ .rm-leg-cells { display: flex; flex: 1; gap: 2px; }
72
+ .rm-leg-cell { flex: 1; text-align: center; }
73
+ .rm-leg-swatch { height: 12px; }
74
+ .rm-leg-cell:first-child .rm-leg-swatch { border-radius: 4px 0 0 4px; }
75
+ .rm-leg-cell:last-child .rm-leg-swatch { border-radius: 0 4px 4px 0; }
76
+ .rm-leg-text { font-size: 12px; color: var(--body-text-color-subdued); margin-top: 3px; }
77
+ .rm-status { font-size: 13px; color: var(--body-text-color-subdued); min-height: 1em; }
78
+ """
79
 
80
+ MAPLIBRE = ('<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script>'
81
+ '<link href="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css" rel="stylesheet">')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
 
 
 
 
84
  def _box(lat0, lat1, lon0, lon1):
85
  try:
86
  box = tuple(float(v) for v in (lat0, lat1, lon0, lon1))
87
  except (TypeError, ValueError):
88
  raise gr.Error("Enter four numbers for the box.")
89
+ if not (-85 <= box[0] < box[1] <= 85):
90
+ raise gr.Error("Latitudes must satisfy -85 ≤ south < north ≤ 85.")
91
+ if (box[1] - box[0]) * ((box[3] - box[2]) % 360 or 360) > 80 * 160:
92
+ raise gr.Error("That box is too large to animate; try something up to about twice the size of Europe.")
 
93
  return box
94
 
95
 
 
 
 
 
 
 
 
 
 
96
  def choose_region(name):
97
+ return REGIONS[name]
 
 
98
 
 
 
99
 
100
+ def show(lat0, lat1, lon0, lon1, start, span, view, pardig_grid):
101
+ """ERA5 and PARDIG rain over a box, hour by hour (or summed), for 1-3 days.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  Args:
104
  lat0: southern edge, degrees north.
105
  lat1: northern edge, degrees north.
106
  lon0: western edge, degrees east.
107
  lon1: eastern edge, degrees east.
108
+ start: first day, YYYY-MM-DD.
109
+ span: "1 day", "2 days" or "3 days".
110
+ view: "Hour by hour" or "Total".
111
  pardig_grid: "0.1° (native)" or "0.25° (ERA5 grid)".
112
  """
113
  maps.DAYS.refresh()
114
  if not maps.DAYS.days:
115
  raise gr.Error("No maps stored yet.")
116
  box = _box(lat0, lat1, lon0, lon1)
117
+ start = start if start in maps.DAYS.days else maps.DAYS.days[-1]
118
+ return maps.payload(start, SPANS[span], box, PARDIG_GRIDS[pardig_grid], VIEWS[view])
 
119
 
120
 
121
  def day_choices(day):
 
131
  return gr.update(value=days[min(max(days.index(day) + step, 0), len(days) - 1)])
132
 
133
 
 
 
 
134
  ABOUT = (HERE / "ABOUT.md").read_text()
135
+ CSS = ".controls { gap: 8px; } footer { display: none !important; }"
136
 
137
+ with gr.Blocks(title="ERA5 vs PARDIG") as demo:
138
  gr.Markdown(
139
  "# ERA5 vs PARDIG\n"
140
+ "ERA5's rain next to **PARDIG-NRT**, Google DeepMind's 0.1° satellite-based rainfall reconstruction, "
141
+ "hour by hour. PARDIG is an estimate too, not ground truth (see *About*).")
142
+ days = maps.DAYS.days
143
+ with gr.Row(equal_height=True, elem_classes="controls"):
144
  region = gr.Dropdown(list(REGIONS), value="Europe", label="Region", scale=2)
145
+ day = gr.Dropdown(days, value=days[-1] if days else None, label="Start day", scale=2)
 
146
  prev_day = gr.Button("◀", scale=0, min_width=44)
147
  next_day = gr.Button("▶", scale=0, min_width=44)
148
+ span = gr.Radio(list(SPANS), value="1 day", label="Span", scale=2)
149
+ view = gr.Radio(list(VIEWS), value="Hour by hour", label="Show", scale=2)
150
  pardig_grid = gr.Radio(list(PARDIG_GRIDS), value="0.1° (native)", label="PARDIG grid", scale=2)
151
  with gr.Accordion("Custom box", open=False):
152
  with gr.Row():
153
+ lat0 = gr.Number(REGIONS["Europe"][0], label="South (°N)", minimum=-85, maximum=85)
154
+ lat1 = gr.Number(REGIONS["Europe"][1], label="North (°N)", minimum=-85, maximum=85)
155
  lon0 = gr.Number(REGIONS["Europe"][2], label="West (°E)")
156
  lon1 = gr.Number(REGIONS["Europe"][3], label="East (°E)")
157
+ apply_box = gr.Button("Show", scale=0, min_width=90)
158
 
159
  with gr.Tabs():
160
  with gr.Tab("Maps"):
161
+ rain = gr.HTML(value="", html_template=COMPONENT_HTML, css_template=COMPONENT_CSS,
162
+ js_on_load=(HERE / "rainmaps.js").read_text(), apply_default_css=False, head=MAPLIBRE)
163
+ totals = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  with gr.Tab("About"):
165
  gr.Markdown(ABOUT)
166
 
167
+ inputs = [lat0, lat1, lon0, lon1, day, span, view, pardig_grid]
168
+ outputs = [rain, totals]
169
+ region.change(choose_region, region, [lat0, lat1, lon0, lon1], api_name=False).then(
170
+ show, inputs, outputs, api_name=False)
171
+ apply_box.click(show, inputs, outputs, api_name="maps")
172
+ for control in (day, span, view, pardig_grid):
173
+ control.change(show, inputs, outputs, api_name=False)
 
 
 
 
 
174
  prev_day.click(lambda d: step_day(d, -1), day, day, api_name=False)
175
  next_day.click(lambda d: step_day(d, 1), day, day, api_name=False)
176
+ demo.load(day_choices, day, day, api_name=False).then(show, inputs, outputs, api_name=False)
 
 
 
 
 
 
 
177
 
178
  if __name__ == "__main__":
179
+ demo.launch(mcp_server=True, css=CSS)
maps.py CHANGED
@@ -1,8 +1,9 @@
1
- """Side-by-side ERA5 and PARDIG rain maps of a region, from the stored hourly fields.
2
 
3
- Each field is drawn as a transparent PNG over a MapLibre basemap. The PNG is resampled onto
4
- Web-Mercator rows with nearest-neighbour lookup, so cells stay crisp (ERA5's 0.25° squares stay
5
- squares) and line up with the basemap at any latitude.
 
6
  """
7
 
8
  from __future__ import annotations
@@ -10,6 +11,7 @@ from __future__ import annotations
10
  import base64
11
  import functools
12
  import io
 
13
  import logging
14
  import os
15
  import threading
@@ -18,7 +20,7 @@ from pathlib import Path
18
 
19
  import numpy as np
20
  import pandas as pd
21
- import plotly.graph_objects as go
22
  from PIL import Image
23
 
24
  from pardig_eval import fields, grid, regrid
@@ -28,24 +30,22 @@ logger = logging.getLogger("maps")
28
  DATA_REPO = os.environ.get("DATA_REPO", "EmmaScharfmann/era5-pardig-scores")
29
  DATA_DIR = os.environ.get("DATA_DIR") # local folder with fields/YYYY/MM/*.zarr.zip, instead of the Hub
30
  REFRESH_S = 1800
31
- MAP_WIDTH_PX = 900 # resolution of the rendered rain layer
32
  MAX_LAT = 85.0 # Web Mercator limit
 
33
 
34
- # One-hue sequential blue ramp (dataviz reference palette, steps 150 -> 700), transparent when dry.
35
  RAIN_COLORS = ["#b7d3f6", "#86b6ef", "#5598e7", "#3987e5", "#2a78d6", "#256abf", "#1c5cab", "#104281", "#0d366b"]
36
  LEVELS = {
37
- "hour": [0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50], # mm in the hour
38
- "day": [0.5, 1, 2, 5, 10, 20, 50, 100, 200], # mm in the day
39
  }
40
- WET = {"hour": 0.1, "day": 1.0}
41
- ALPHA = 200
42
 
43
 
44
  # ---------------------------------------------------------------------------
45
  # data
46
  # ---------------------------------------------------------------------------
47
  class Days:
48
- """The days whose hourly fields are stored, refreshed from the Hub every REFRESH_S seconds."""
49
 
50
  def __init__(self):
51
  self.lock = threading.Lock()
@@ -77,8 +77,8 @@ class Days:
77
  DAYS = Days()
78
 
79
 
80
- @functools.lru_cache(maxsize=4)
81
- def open_day(day: str):
82
  if DATA_DIR:
83
  path = Path(DATA_DIR) / fields.path_for(day)
84
  else:
@@ -88,160 +88,129 @@ def open_day(day: str):
88
  return fields.open_fields(path)
89
 
90
 
91
- def get_fields(day: str, hour: int | None, box, pardig_on_era5_grid: bool):
92
- """(ERA5, PARDIG) DataArrays over the box: the day's total (hour None) or one hour (1..24, end of hour)."""
93
- ds = open_day(day)
94
- pick = (lambda da: da.sum("time", min_count=24)) if hour is None else (lambda da: da.isel(time=hour - 1))
95
- era5 = fields.crop(pick(ds["era5"]), *box).load()
96
- if pardig_on_era5_grid:
97
- whole = pick(ds["pardig"]).values.astype(np.float32)
98
- pardig = fields.crop(_like_era5(regrid.to_era5_grid(whole)), *box)
99
- else:
100
- pardig = fields.crop(pick(ds["pardig"]), *box).load()
101
- return era5, pardig
102
-
103
-
104
- def _like_era5(values: np.ndarray):
105
- import xarray as xr
106
-
107
- return xr.DataArray(values, dims=("lat_era5", "lon_era5"), coords={"lat_era5": grid.LAT, "lon_era5": grid.LON})
 
 
 
 
 
 
 
 
108
 
109
 
110
  # ---------------------------------------------------------------------------
111
- # rendering
112
  # ---------------------------------------------------------------------------
113
  def _merc(lat_deg):
114
  lat = np.deg2rad(np.clip(lat_deg, -MAX_LAT, MAX_LAT))
115
  return np.log(np.tan(np.pi / 4 + lat / 2))
116
 
117
 
118
- def _edges(da):
119
- lat_name, lon_name = da.dims
120
- lat, lon = da[lat_name].values, da[lon_name].values
121
- dlat = float(np.median(np.diff(lat))) if lat.size > 1 else 0.25
122
- dlon = float(np.median(np.diff(lon))) if lon.size > 1 else 0.25
123
- south = max(lat[0] - dlat / 2, -MAX_LAT)
124
- north = min(lat[-1] + dlat / 2, MAX_LAT)
125
- return lat, lon, dlat, dlon, south, north, lon[0] - dlon / 2, lon[-1] + dlon / 2
126
-
127
-
128
- def rain_png(da, levels) -> tuple[str, list]:
129
- """A data-URL PNG of the field on Web-Mercator rows, and its corner coordinates for MapLibre."""
130
- lat, lon, dlat, dlon, south, north, west, east = _edges(da)
131
- width = MAP_WIDTH_PX
132
- x_span = np.deg2rad(east - west)
133
- y0, y1 = _merc(south), _merc(north)
134
- height = int(np.clip(round(width * (y1 - y0) / x_span), 50, 2000))
135
- # Pixel centres -> nearest source cell (cells stay crisp).
136
- xs = west + (np.arange(width) + 0.5) / width * (east - west)
137
- ys = y1 - (np.arange(height) + 0.5) / height * (y1 - y0)
138
- lat_px = np.rad2deg(2 * np.arctan(np.exp(ys)) - np.pi / 2)
139
- cols = np.clip(np.round((xs - lon[0]) / dlon).astype(int), 0, lon.size - 1)
140
- rows = np.clip(np.round((lat_px - lat[0]) / dlat).astype(int), 0, lat.size - 1)
141
- values = np.asarray(da.values)[rows][:, cols]
142
- index = np.digitize(np.nan_to_num(values, nan=-1), levels) # 0 = below the first level
143
- palette = np.zeros((len(levels) + 1, 4), np.uint8)
144
- for i, color in enumerate(RAIN_COLORS[: len(levels)]):
145
- palette[i + 1] = [int(color[j:j + 2], 16) for j in (1, 3, 5)] + [ALPHA]
146
- image = Image.fromarray(palette[index], "RGBA")
147
- buffer = io.BytesIO()
148
- image.save(buffer, format="PNG", optimize=True)
149
- url = "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
150
- return url, [[west, north], [east, north], [east, south], [west, south]]
151
 
152
 
153
  def view(box) -> dict:
154
- """Centre and zoom that fit a box in a ~600 x 520 px map."""
155
  lat0, lat1 = max(box[0], -MAX_LAT), min(box[1], MAX_LAT)
156
  lon0, lon1 = box[2], box[3] if box[3] > box[2] else box[3] + 360
157
- lon_span = max(lon1 - lon0, 1e-3)
158
- y_span = max(_merc(lat1) - _merc(lat0), 1e-3)
159
- # MapLibre zoom 0 shows the world in 512 px.
160
- zoom_x = np.log2(600 * 360 / (512 * lon_span))
161
- zoom_y = np.log2(500 * 2 * np.pi / (512 * y_span))
162
  centre_lat = float(np.rad2deg(2 * np.arctan(np.exp((_merc(lat0) + _merc(lat1)) / 2)) - np.pi / 2))
163
  lon_c = (lon0 + lon1) / 2
164
- return {"center": {"lat": centre_lat, "lon": ((lon_c + 180) % 360) - 180},
165
- "zoom": float(np.clip(min(zoom_x, zoom_y) - 0.15, 0, 12))}
166
-
167
-
168
- def map_figure(da, title: str, levels, box) -> go.Figure:
169
- url, corners = rain_png(da, levels)
170
- # An invisible point: a map figure needs one trace to draw its basemap.
171
- fig = go.Figure(go.Scattermap(lat=[box[0]], lon=[box[2]], mode="markers", hoverinfo="skip",
172
- showlegend=False, marker=dict(size=1, opacity=0)))
173
- fig.update_layout(
174
- map=dict(style="carto-positron", **view(box),
175
- layers=[dict(sourcetype="image", source=url, coordinates=corners, type="raster",
176
- below="traces")]),
177
- title=dict(text=title, x=0.01, xanchor="left", font=dict(size=15)),
178
- margin=dict(l=0, r=0, t=40, b=0), height=560,
179
- paper_bgcolor="rgba(0,0,0,0)",
180
- font=dict(family="system-ui, -apple-system, Segoe UI, sans-serif", color="#52514e", size=12),
181
- )
182
- return fig
183
-
184
-
185
- def legend_html(levels, unit: str) -> str:
186
- """One stepped colour legend shared by both maps."""
187
- cells = "".join(
188
- f'<div style="flex:1;text-align:center"><div style="height:12px;background:{c};'
189
- f'border-radius:{"4px 0 0 4px" if i == 0 else ("0 4px 4px 0" if i == len(levels) - 1 else "0")}"></div>'
190
- f'<div style="font-size:12px;color:var(--body-text-color-subdued);margin-top:3px">≥ {v:g}</div></div>'
191
- for i, (c, v) in enumerate(zip(RAIN_COLORS, levels)))
192
- return (f'<div style="display:flex;align-items:flex-start;gap:12px;max-width:760px;margin:4px auto 0">'
193
- f'<div style="font-size:12px;white-space:nowrap;padding-top:0">{unit}<br>'
194
- f'<span style="color:var(--body-text-color-subdued)">clear = dry</span></div>'
195
- f'<div style="display:flex;flex:1;gap:2px">{cells}</div></div>')
196
-
197
-
198
- def region_stats(da, wet: float) -> dict:
199
- lat_name = da.dims[0]
200
- weight = np.cos(np.deg2rad(da[lat_name].values))[:, None] * np.ones(da.shape)
201
- values = np.asarray(da.values, dtype=float)
202
- ok = np.isfinite(values)
203
- w = np.where(ok, weight, 0)
204
- return {
205
- "mean": float((w * np.nan_to_num(values)).sum() / w.sum()) if w.sum() else np.nan,
206
- "wet": float((w * (np.nan_to_num(values) >= wet)).sum() / w.sum()) if w.sum() else np.nan,
207
- "max": float(np.nanmax(values)) if ok.any() else np.nan,
208
- }
209
 
210
 
211
- def stats_markdown(era5, pardig, kind: str) -> str:
212
- e, p = region_stats(era5, WET[kind]), region_stats(pardig, WET[kind])
213
- unit = "mm" if kind == "hour" else "mm/day"
214
-
215
- def ratio(a, b):
216
- return f"{a / b:.1f}×" if b > 0 else "—"
217
-
218
- return (
219
- "| | ERA5 | PARDIG | ERA5 / PARDIG |\n|---|---:|---:|---:|\n"
220
- f"| Mean rain, {unit} | {e['mean']:.2f} | {p['mean']:.2f} | {ratio(e['mean'], p['mean'])} |\n"
221
- f"| Area with rain ≥ {WET[kind]:g} {unit} | {e['wet']:.0%} | {p['wet']:.0%} | {ratio(e['wet'], p['wet'])} |\n"
222
- f"| Heaviest cell, {unit} | {e['max']:.1f} | {p['max']:.1f} | {ratio(e['max'], p['max'])} |"
223
- )
224
-
225
-
226
- def time_label(day: str, hour: int | None) -> str:
227
- d = pd.Timestamp(day)
228
- if hour is None:
229
- return f"{d:%-d %B %Y}, daily total"
230
- start = d + pd.Timedelta(hours=hour - 1)
231
- return f"{d:%-d %B %Y}, {start:%H}:00–{(start + pd.Timedelta(hours=1)):%H}:00 UTC"
232
-
233
-
234
- def render(day: str, hour: int | None, box, pardig_on_era5_grid: bool):
235
- """(ERA5 figure, PARDIG figure, stats markdown) for a day or hour over a box."""
236
- kind = "day" if hour is None else "hour"
237
- levels = LEVELS[kind]
238
- unit = "mm/day" if kind == "day" else "mm/h"
239
- era5, pardig = get_fields(day, hour, box, pardig_on_era5_grid)
240
- label = time_label(day, hour)
241
- pardig_res = "0.25°, averaged" if pardig_on_era5_grid else "0.1°"
242
- return (
243
- map_figure(era5, f"<b>ERA5</b> (0.25°) · {label}", levels, box),
244
- map_figure(pardig, f"<b>PARDIG</b> ({pardig_res}) · {label}", levels, box),
245
- legend_html(levels, unit),
246
- stats_markdown(era5, pardig, kind),
247
- )
 
 
 
 
 
 
1
+ """ERA5 and PARDIG rain over a region, hour by hour, as frames for the animated map component.
2
 
3
+ Each frame of each source is a small paletted PNG, resampled onto Web-Mercator rows by nearest
4
+ neighbour (so 0.25° ERA5 cells stay square and line up with the basemap at any latitude). The
5
+ browser component (``rainmaps.js``) preloads the frames and plays them on two synchronised
6
+ MapLibre maps.
7
  """
8
 
9
  from __future__ import annotations
 
11
  import base64
12
  import functools
13
  import io
14
+ import json
15
  import logging
16
  import os
17
  import threading
 
20
 
21
  import numpy as np
22
  import pandas as pd
23
+ import xarray as xr
24
  from PIL import Image
25
 
26
  from pardig_eval import fields, grid, regrid
 
30
  DATA_REPO = os.environ.get("DATA_REPO", "EmmaScharfmann/era5-pardig-scores")
31
  DATA_DIR = os.environ.get("DATA_DIR") # local folder with fields/YYYY/MM/*.zarr.zip, instead of the Hub
32
  REFRESH_S = 1800
 
33
  MAX_LAT = 85.0 # Web Mercator limit
34
+ MAX_PX = 900 # widest rendered frame
35
 
36
+ # One-hue sequential blue ramp (dataviz reference palette, steps 150 -> 700); dry is transparent.
37
  RAIN_COLORS = ["#b7d3f6", "#86b6ef", "#5598e7", "#3987e5", "#2a78d6", "#256abf", "#1c5cab", "#104281", "#0d366b"]
38
  LEVELS = {
39
+ "hour": [0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50], # mm in an hour
40
+ "total": [0.5, 1, 2, 5, 10, 20, 50, 100, 200], # mm over the span
41
  }
 
 
42
 
43
 
44
  # ---------------------------------------------------------------------------
45
  # data
46
  # ---------------------------------------------------------------------------
47
  class Days:
48
+ """Days whose hourly fields are stored, refreshed from the Hub every REFRESH_S seconds."""
49
 
50
  def __init__(self):
51
  self.lock = threading.Lock()
 
77
  DAYS = Days()
78
 
79
 
80
+ @functools.lru_cache(maxsize=6)
81
+ def open_day(day: str) -> xr.Dataset:
82
  if DATA_DIR:
83
  path = Path(DATA_DIR) / fields.path_for(day)
84
  else:
 
88
  return fields.open_fields(path)
89
 
90
 
91
+ def _pardig_on_era5_grid(fine: xr.DataArray, lat_min: float, lat_max: float) -> xr.DataArray:
92
+ """Conservative 0.1° -> 0.25° for the ERA5 rows of a latitude band only (all longitudes)."""
93
+ lat_m, lon_m = regrid.matrices()
94
+ rows = np.flatnonzero((grid.LAT >= lat_min - 0.3) & (grid.LAT <= lat_max + 0.3))
95
+ band = lat_m[rows]
96
+ needed = np.unique(band.indices)
97
+ band = band[:, needed]
98
+ values = fine.isel(lat_pardig=needed).values # (time, rows, 3600)
99
+ out = np.stack([(lon_m @ (band @ v.astype(np.float64)).T).T for v in values]).astype(np.float32)
100
+ return xr.DataArray(out, dims=("time", "lat_era5", "lon_era5"),
101
+ coords={"time": fine["time"].values, "lat_era5": grid.LAT[rows], "lon_era5": grid.LON})
102
+
103
+
104
+ def load_span(start: str, n_days: int, box, pardig_on_era5_grid: bool) -> tuple[xr.DataArray, xr.DataArray]:
105
+ """Hourly ERA5 and PARDIG over the box for ``n_days`` stored days from ``start``."""
106
+ days = [d for d in DAYS.days if d >= start][:n_days]
107
+ era5, pardig = [], []
108
+ for day in days:
109
+ ds = open_day(day)
110
+ era5.append(fields.crop(ds["era5"], *box).load())
111
+ if pardig_on_era5_grid:
112
+ pardig.append(fields.crop(_pardig_on_era5_grid(ds["pardig"], box[0], box[1]), *box))
113
+ else:
114
+ pardig.append(fields.crop(ds["pardig"], *box).load())
115
+ return xr.concat(era5, "time"), xr.concat(pardig, "time")
116
 
117
 
118
  # ---------------------------------------------------------------------------
119
+ # frames
120
  # ---------------------------------------------------------------------------
121
  def _merc(lat_deg):
122
  lat = np.deg2rad(np.clip(lat_deg, -MAX_LAT, MAX_LAT))
123
  return np.log(np.tan(np.pi / 4 + lat / 2))
124
 
125
 
126
+ class Raster:
127
+ """Nearest-neighbour lookup from a regular lat/lon grid to Web-Mercator pixels, built once per source."""
128
+
129
+ def __init__(self, da: xr.DataArray):
130
+ lat_name, lon_name = da.dims[-2:]
131
+ lat, lon = da[lat_name].values, da[lon_name].values
132
+ dlat = float(np.median(np.diff(lat))) if lat.size > 1 else 0.25
133
+ dlon = float(np.median(np.diff(lon))) if lon.size > 1 else 0.25
134
+ south, north = max(lat[0] - dlat / 2, -MAX_LAT), min(lat[-1] + dlat / 2, MAX_LAT)
135
+ west, east = lon[0] - dlon / 2, lon[-1] + dlon / 2
136
+ width = int(np.clip(3 * lon.size, 300, MAX_PX))
137
+ y0, y1 = _merc(south), _merc(north)
138
+ height = int(np.clip(round(width * (y1 - y0) / np.deg2rad(east - west)), 30, 2 * MAX_PX))
139
+ xs = west + (np.arange(width) + 0.5) / width * (east - west)
140
+ ys = y1 - (np.arange(height) + 0.5) / height * (y1 - y0)
141
+ lat_px = np.rad2deg(2 * np.arctan(np.exp(ys)) - np.pi / 2)
142
+ self.cols = np.clip(np.round((xs - lon[0]) / dlon).astype(int), 0, lon.size - 1)
143
+ self.rows = np.clip(np.round((lat_px - lat[0]) / dlat).astype(int), 0, lat.size - 1)
144
+ self.corners = [[west, north], [east, north], [east, south], [west, south]]
145
+
146
+ def png(self, values: np.ndarray, levels) -> str:
147
+ index = np.digitize(np.nan_to_num(values, nan=-1.0), levels).astype(np.uint8)[self.rows][:, self.cols]
148
+ image = Image.fromarray(index, "P")
149
+ palette = [0, 0, 0]
150
+ for color in RAIN_COLORS[: len(levels)]:
151
+ palette += [int(color[j:j + 2], 16) for j in (1, 3, 5)]
152
+ image.putpalette(palette)
153
+ buffer = io.BytesIO()
154
+ image.save(buffer, format="PNG", transparency=0) # index 0 (dry) is clear
155
+ return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
 
 
 
156
 
157
 
158
  def view(box) -> dict:
159
+ """Centre and zoom that fit a box in a ~600 x 520 px map (MapLibre: the world is 512 px at zoom 0)."""
160
  lat0, lat1 = max(box[0], -MAX_LAT), min(box[1], MAX_LAT)
161
  lon0, lon1 = box[2], box[3] if box[3] > box[2] else box[3] + 360
162
+ zoom_x = np.log2(600 * 360 / (512 * max(lon1 - lon0, 1e-3)))
163
+ zoom_y = np.log2(500 * 2 * np.pi / (512 * max(_merc(lat1) - _merc(lat0), 1e-3)))
 
 
 
164
  centre_lat = float(np.rad2deg(2 * np.arctan(np.exp((_merc(lat0) + _merc(lat1)) / 2)) - np.pi / 2))
165
  lon_c = (lon0 + lon1) / 2
166
+ return {"center": [((lon_c + 180) % 360) - 180, centre_lat], "zoom": float(np.clip(min(zoom_x, zoom_y) - 0.1, 0, 12))}
167
+
168
+
169
+ def _label(t) -> str:
170
+ end = pd.Timestamp(t)
171
+ start = end - pd.Timedelta(hours=1)
172
+ return f"{start:%a %-d %b %Y} · {start:%H}:00–{end:%H}:00 UTC"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
 
175
+ def _weights(da: xr.DataArray) -> np.ndarray:
176
+ return np.cos(np.deg2rad(da[da.dims[-2]].values))[:, None] * np.ones(da.shape[-2:])
177
+
178
+
179
+ def summary(era5: xr.DataArray, pardig: xr.DataArray) -> str:
180
+ """One line: mean total over the span, share of rainy hours, heaviest hour, for each source."""
181
+ def stats(da):
182
+ v = np.asarray(da.values, dtype=float) # (hours, lat, lon)
183
+ w = _weights(da)
184
+ mean_total = float((w * np.nansum(v, axis=0)).sum() / w.sum())
185
+ wet = float((w[None] * (np.nan_to_num(v) >= 0.1)).sum() / (w.sum() * v.shape[0]))
186
+ return mean_total, wet, float(np.nanmax(v)), v.shape[0]
187
+
188
+ e, p = stats(era5), stats(pardig)
189
+ return (f"**Over these {e[3]} hours** ��� mean rain: ERA5 **{e[0]:.1f} mm**, PARDIG **{p[0]:.1f} mm** · "
190
+ f"rainy hours (≥ 0.1 mm/h): ERA5 **{e[1]:.0%}**, PARDIG **{p[1]:.0%}** of the region · "
191
+ f"heaviest hour in one cell: ERA5 **{e[2]:.0f} mm**, PARDIG **{p[2]:.0f} mm**")
192
+
193
+
194
+ def payload(start: str, n_days: int, box, pardig_on_era5_grid: bool, mode: str) -> tuple[str, str]:
195
+ """(JSON for the map component, summary line). ``mode`` is "hourly" (animation) or "total" (one frame)."""
196
+ era5, pardig = load_span(start, n_days, box, pardig_on_era5_grid)
197
+ times = pd.DatetimeIndex(era5["time"].values)
198
+ if mode == "total":
199
+ e_frames, p_frames = [era5.sum("time", min_count=1).values], [pardig.sum("time", min_count=1).values]
200
+ labels = [f"Total, {_label(times[0]).split(' · ')[0]} to {(times[-1] - pd.Timedelta(hours=1)):%a %-d %b %Y}"]
201
+ levels, unit = LEVELS["total"], "mm"
202
+ else:
203
+ e_frames, p_frames = list(era5.values), list(pardig.values)
204
+ labels = [_label(t) for t in times]
205
+ levels, unit = LEVELS["hour"], "mm/h"
206
+ re, rp = Raster(era5), Raster(pardig)
207
+ data = {
208
+ "key": f"{box}",
209
+ "view": view(box),
210
+ "labels": labels,
211
+ "era5": {"title": "ERA5 · 0.25°", "corners": re.corners, "frames": [re.png(v, levels) for v in e_frames]},
212
+ "pardig": {"title": "PARDIG · " + ("0.25°, averaged" if pardig_on_era5_grid else "0.1°"),
213
+ "corners": rp.corners, "frames": [rp.png(v, levels) for v in p_frames]},
214
+ "legend": {"unit": unit, "levels": [f"{v:g}" for v in levels], "colors": RAIN_COLORS[: len(levels)]},
215
+ }
216
+ return json.dumps(data), summary(era5, pardig)
rainmaps.js ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Two synchronised MapLibre maps (ERA5 | PARDIG) playing hourly rain frames.
2
+ // Runs as gr.HTML js_on_load: `element` is the component, `props.value` the JSON payload from Python.
3
+ const STYLE = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json";
4
+ const state = { maps: {}, ctx: {}, images: { era5: [], pardig: [] }, frame: 0, n: 0, timer: null,
5
+ playing: true, key: null, token: 0 };
6
+ const $ = (sel) => element.querySelector(sel);
7
+
8
+ function whenMaplibre() {
9
+ return new Promise((resolve) => {
10
+ const check = () => (window.maplibregl ? resolve(window.maplibregl) : setTimeout(check, 50));
11
+ check();
12
+ });
13
+ }
14
+
15
+ function loadImages(urls) {
16
+ return Promise.all(urls.map((url) => new Promise((resolve, reject) => {
17
+ const img = new Image();
18
+ img.onload = () => resolve(img);
19
+ img.onerror = reject;
20
+ img.src = url;
21
+ })));
22
+ }
23
+
24
+ async function createMap(name, view) {
25
+ const maplibregl = await whenMaplibre();
26
+ const container = $(`.rm-map[data-map="${name}"]`);
27
+ container.innerHTML = "";
28
+ const map = new maplibregl.Map({ container, style: STYLE, center: view.center, zoom: view.zoom,
29
+ attributionControl: { compact: true }, dragRotate: false,
30
+ pitchWithRotate: false });
31
+ map.touchZoomRotate.disableRotation();
32
+ map.addControl(new maplibregl.NavigationControl({ showCompass: false }), "top-right");
33
+ await new Promise((resolve) => map.on("load", resolve));
34
+ return map;
35
+ }
36
+
37
+ // (Re)create the rain layer for frames of a given size: a canvas source must not be resized after
38
+ // it is created (its texture keeps the first size and renders opaque).
39
+ function rainLayer(name, width, height, corners) {
40
+ const map = state.maps[name];
41
+ const ctx = state.ctx[name];
42
+ if (ctx && ctx.canvas.width === width && ctx.canvas.height === height && map.getSource("rain")) {
43
+ map.getSource("rain").setCoordinates(corners);
44
+ return;
45
+ }
46
+ if (map.getLayer("rain")) map.removeLayer("rain");
47
+ if (map.getSource("rain")) map.removeSource("rain");
48
+ const canvas = document.createElement("canvas");
49
+ canvas.width = width; canvas.height = height;
50
+ state.ctx[name] = canvas.getContext("2d");
51
+ map.addSource("rain", { type: "canvas", canvas, animate: true, coordinates: corners });
52
+ // Rain under the place names, so labels stay readable.
53
+ const firstLabel = map.getStyle().layers.find((l) => l.type === "symbol");
54
+ map.addLayer({ id: "rain", type: "raster", source: "rain",
55
+ paint: { "raster-opacity": 0.85, "raster-resampling": "nearest", "raster-fade-duration": 0 } },
56
+ firstLabel ? firstLabel.id : undefined);
57
+ }
58
+
59
+ function syncMaps(a, b) {
60
+ let busy = false;
61
+ const follow = (from, to) => from.on("move", () => {
62
+ if (busy) return;
63
+ busy = true;
64
+ to.jumpTo({ center: from.getCenter(), zoom: from.getZoom() });
65
+ busy = false;
66
+ });
67
+ follow(a, b);
68
+ follow(b, a);
69
+ }
70
+
71
+ async function ensureMaps(view) {
72
+ const alive = (name) => state.maps[name] && $(`.rm-map[data-map="${name}"] canvas.maplibregl-canvas`);
73
+ if (alive("era5") && alive("pardig")) return;
74
+ state.ctx = {};
75
+ state.maps.era5 = await createMap("era5", view);
76
+ state.maps.pardig = await createMap("pardig", view);
77
+ syncMaps(state.maps.era5, state.maps.pardig);
78
+ }
79
+
80
+ function draw(i) {
81
+ state.frame = i;
82
+ for (const name of ["era5", "pardig"]) {
83
+ const img = state.images[name][i];
84
+ const ctx = state.ctx[name];
85
+ if (!img || !ctx) continue;
86
+ ctx.clearRect(0, 0, img.width, img.height);
87
+ ctx.drawImage(img, 0, 0);
88
+ }
89
+ $(".rm-slider").value = i;
90
+ $(".rm-time").textContent = state.labels[i] || "";
91
+ }
92
+
93
+ function speed() { return Number($(".rm-speed").value); }
94
+
95
+ function play(on) {
96
+ state.playing = on && state.n > 1;
97
+ $(".rm-play").textContent = state.playing ? "❚❚" : "▶";
98
+ $(".rm-play").setAttribute("aria-label", state.playing ? "Pause" : "Play");
99
+ clearInterval(state.timer);
100
+ if (state.playing) state.timer = setInterval(() => draw((state.frame + 1) % state.n), speed());
101
+ }
102
+
103
+ function legend(spec) {
104
+ const cells = spec.colors.map((c, i) =>
105
+ `<div class="rm-leg-cell"><div class="rm-leg-swatch" style="background:${c}"></div>` +
106
+ `<div class="rm-leg-text">≥ ${spec.levels[i]}</div></div>`).join("");
107
+ $(".rm-legend").innerHTML = `<div class="rm-leg-unit">${spec.unit}<br><span>clear = dry</span></div>` +
108
+ `<div class="rm-leg-cells">${cells}</div>`;
109
+ }
110
+
111
+ async function show() {
112
+ if (!props.value) return;
113
+ let data;
114
+ try { data = JSON.parse(props.value); } catch (e) { return; }
115
+ const token = ++state.token;
116
+ $(".rm-status").textContent = "Loading frames…";
117
+ await ensureMaps(data.view);
118
+ const [era5, pardig] = await Promise.all([loadImages(data.era5.frames), loadImages(data.pardig.frames)]);
119
+ if (token !== state.token) return; // a newer request arrived meanwhile
120
+ state.images = { era5, pardig };
121
+ state.labels = data.labels;
122
+ state.n = data.labels.length;
123
+ for (const name of ["era5", "pardig"]) {
124
+ const first = state.images[name][0];
125
+ rainLayer(name, first.width, first.height, data[name].corners);
126
+ $(`.rm-title[data-src="${name}"]`).textContent = data[name].title;
127
+ }
128
+ if (data.key !== state.key) {
129
+ state.maps.era5.jumpTo({ center: data.view.center, zoom: data.view.zoom });
130
+ state.key = data.key;
131
+ }
132
+ $(".rm-slider").max = Math.max(state.n - 1, 0);
133
+ $(".rm-bar").style.visibility = state.n > 1 ? "visible" : "hidden";
134
+ legend(data.legend);
135
+ $(".rm-status").textContent = "";
136
+ draw(Math.min(state.frame, state.n - 1));
137
+ play(state.n > 1 && state.playing !== false);
138
+ }
139
+
140
+ $(".rm-play").addEventListener("click", () => play(!state.playing));
141
+ $(".rm-slider").addEventListener("input", (e) => { play(false); draw(Number(e.target.value)); });
142
+ $(".rm-speed").addEventListener("change", () => play(state.playing));
143
+ document.addEventListener("keydown", (e) => {
144
+ if (!element.isConnected || state.n < 2 || ["INPUT", "SELECT", "TEXTAREA"].includes(document.activeElement?.tagName)) return;
145
+ if (e.key === "ArrowRight") { play(false); draw((state.frame + 1) % state.n); }
146
+ if (e.key === "ArrowLeft") { play(false); draw((state.frame - 1 + state.n) % state.n); }
147
+ });
148
+ watch("value", show);
149
+ show();
requirements.txt CHANGED
@@ -1,9 +1,6 @@
1
  numpy
2
  pandas
3
- scipy
4
  xarray
5
- h5netcdf
6
- h5py
7
- plotly
8
  pillow
9
  zarr>=3
 
 
1
  numpy
2
  pandas
 
3
  xarray
 
 
 
4
  pillow
5
  zarr>=3
6
+ scipy