EmmaScharfmann HF Staff commited on
Commit
7f68fbf
·
verified ·
1 Parent(s): 9d0feef

Pick any two of ERA5, PARDIG and IMERG (default IMERG vs PARDIG), with their difference

Browse files
Files changed (4) hide show
  1. ABOUT.md +11 -2
  2. app.py +62 -29
  3. maps.py +106 -47
  4. rainmaps.js +4 -0
ABOUT.md CHANGED
@@ -5,11 +5,20 @@
5
  - **The new satellite rain map** is PARDIG-NRT (Google DeepMind and Google Research, CC BY 4.0, `gs://pardig_1`):
6
  rain rates every 15 minutes on a 0.1° grid (about 10 km). Each hour shown is ¼ h × the rates at 45, 30, 15 and 0 minutes
7
  before its end (PARDIG paper, Eq. A.3.8), the same hour as ERA5.
 
 
 
 
 
 
 
8
  - **PARDIG is not a ground truth**, but an experimental dataset. It tends to underestimate snow and drizzle, is less accurate over high mountains and
9
  near the poles, and caps precipitation rates at 75 mm/h.
10
  - **PARDIG is the first global, high-resolution precipitation dataset** with realistic rain structures, which makes it a much better reference than ERA5 to evaluate precipitation predictions.
11
- - **ERA5 minus PARDIG** compares the two cell by cell, hour by hour, after averaging PARDIG onto ERA5's 28 km cells
12
- (area-conservative). Purple: ERA5 has more rain; orange: less; grey: within 0.2 mm. Classes change at 0.2, 1, 3 and
 
 
13
  10 mm. Cells where both have less than 0.1 mm are left clear. Grey therefore also includes cells where only one
14
  dataset has a little rain: for example, ERA5 drizzle of 0.15 mm where PARDIG is dry differs by less than 0.2 mm,
15
  so it shows as grey rather than purple. Much of the wide grey area around storms is ERA5 drizzle of this kind.
 
5
  - **The new satellite rain map** is PARDIG-NRT (Google DeepMind and Google Research, CC BY 4.0, `gs://pardig_1`):
6
  rain rates every 15 minutes on a 0.1° grid (about 10 km). Each hour shown is ¼ h × the rates at 45, 30, 15 and 0 minutes
7
  before its end (PARDIG paper, Eq. A.3.8), the same hour as ERA5.
8
+ - **IMERG** is NASA's GPM IMERG Late Run, version 07 (Huffman et al., doi:10.5067/GPM/IMERG/3B-HH-L/07, from NASA
9
+ GES DISC): rain rates averaged over each half-hour on a 0.1° grid, about 14 hours behind real time. Each hour shown
10
+ is the mean of its two half-hours (rate × ½ h each), the same hour as ERA5 and PARDIG. IMERG has no reliable rain
11
+ over snow and ice, so cells it marks missing stay clear in its map and in the difference. The gauge-adjusted
12
+ Final Run (version 07) stops in September 2025; its version 08 is not published for 2026 yet.
13
+ - **IMERG and PARDIG share a source**: PARDIG is trained on GPM data, the mission IMERG is built on, so their
14
+ agreement is partly by construction.
15
  - **PARDIG is not a ground truth**, but an experimental dataset. It tends to underestimate snow and drizzle, is less accurate over high mountains and
16
  near the poles, and caps precipitation rates at 75 mm/h.
17
  - **PARDIG is the first global, high-resolution precipitation dataset** with realistic rain structures, which makes it a much better reference than ERA5 to evaluate precipitation predictions.
18
+ - **The difference map** (left minus right) compares the two cell by cell, hour by hour, after averaging the 10 km
19
+ datasets onto ERA5's 28 km cells (area-conservative). Pick the two datasets with the dropdowns; IMERG and PARDIG
20
+ are shown by default. In what follows, "ERA5 minus PARDIG" stands for any pair.
21
+ Purple: ERA5 has more rain; orange: less; grey: within 0.2 mm. Classes change at 0.2, 1, 3 and
22
  10 mm. Cells where both have less than 0.1 mm are left clear. Grey therefore also includes cells where only one
23
  dataset has a little rain: for example, ERA5 drizzle of 0.15 mm where PARDIG is dry differs by less than 0.2 mm,
24
  so it shows as grey rather than purple. Much of the wide grey area around storms is ERA5 drizzle of this kind.
app.py CHANGED
@@ -1,4 +1,4 @@
1
- """How much did it really rain? The standard reconstruction (ERA5) next to a new satellite rain map (PARDIG)."""
2
 
3
  from __future__ import annotations
4
 
@@ -16,6 +16,10 @@ HERE = Path(__file__).parent
16
  N_DAYS = 2 # every view plays 48 hours
17
 
18
  FEATURED = "Tropical cyclone, Mozambique Channel"
 
 
 
 
19
  REGIONS = {
20
  FEATURED: ((-24, -6, 31, 55), "2026-01-29"),
21
  "Europe": ((35, 72, -25, 45), None),
@@ -49,42 +53,59 @@ PROBLEM = """
49
  STORY = """
50
  <div class="story">
51
  <section>
52
- <div class="kicker"><span class="tag tag-map">Left map</span></div>
53
- <h3>ERA5: a reconstruction of the past weather hour by hour since 1940e</h3>
54
  <p>ERA5 is a reanalysis produced by the European Centre for Medium-Range Weather Forecasts (ECMWF). It
55
  reconstructs the past weather hour by hour since 1940, by combining a physics model of the atmosphere with
56
  observations from satellites, weather stations and weather balloons. It is the dataset most AI weather models
57
  are trained on and evaluated against. ERA5 is very good for variables (such as temperature), but
58
- less accurate for precipitation. The rain from ERA5 is blured, with light rain over large areas and heavy rain
59
  events that are too weak and too spread out.</p>
60
  </section>
61
  <section>
62
- <div class="kicker"><span class="tag tag-map">Middle map</span></div>
 
 
 
 
 
 
 
 
 
63
  <h3>PARDIG: a new satellite-based reconstruction</h3>
64
  <p>PARDIG (Precipitation AI Reanalysis, Densely Inferred GPM) is a precipitation dataset recently released by
65
  Google DeepMind and Google Research. It estimates the rain over the whole planet every 15 minutes, on a 10 km
66
  grid. An AI model converts geostationary satellite images and weather
67
  analyses into rain. The dataset is openly available under a CC BY 4.0 license.</p>
68
  </section>
 
 
 
 
 
 
 
69
  </div>
70
  """
71
 
72
  FOOTER = ("Data: [`EmmaScharfmann/era5-pardig-scores`](https://huggingface.co/datasets/EmmaScharfmann/era5-pardig-scores) · "
 
73
  "Basemap © OpenStreetMap contributors © CARTO.")
74
 
75
  COMPONENT_HTML = """
76
  <div class="rm">
77
  <div class="rm-maps">
78
  <div class="rm-panel">
79
- <div class="rm-title">ERA5 · 28 km</div>
80
- <div class="rm-map" data-map="era5"></div>
81
  </div>
82
  <div class="rm-panel">
83
  <div class="rm-title">PARDIG · 10 km</div>
84
- <div class="rm-map" data-map="pardig"></div>
85
  </div>
86
  <div class="rm-panel">
87
- <div class="rm-title">ERA5 minus PARDIG, both on the 28 km grid</div>
88
  <div class="rm-map" data-map="diff"></div>
89
  </div>
90
  <div class="rm-legend rm-legend-rain" data-for="rain"></div>
@@ -192,8 +213,11 @@ def _day(value) -> str | None:
192
  return None
193
 
194
 
195
- def _nearest_day(value) -> str:
196
- days = maps.DAYS.days
 
 
 
197
  wanted = _day(value)
198
  if wanted is None:
199
  return days[-1]
@@ -202,27 +226,31 @@ def _nearest_day(value) -> str:
202
  return days[int(np.abs((pd.DatetimeIndex(days) - pd.Timestamp(wanted)).days).argmin())]
203
 
204
 
205
- def coverage() -> str:
206
- days = maps.DAYS.days
207
  return f"Maps from {days[0]} to {days[-1]}" if days else "No maps yet"
208
 
209
 
210
- def show(region, day):
211
- """Rain over a region for 48 hours from a day: the standard reconstruction (ERA5), the satellite map
212
- (PARDIG) and their difference.
213
 
214
  Args:
215
  region: a region name from the list.
216
  day: first day, YYYY-MM-DD.
 
 
217
  """
218
  maps.DAYS.refresh()
219
- if not maps.DAYS.days:
220
- raise gr.Error("No maps stored yet.")
 
 
 
 
221
  box = REGIONS.get(region, REGIONS[FEATURED])[0]
222
- picked, start = _day(day), _nearest_day(day)
223
  if picked and picked != start:
224
- gr.Info(f"No maps for {picked} yet: showing {start}. {coverage()}.")
225
- return maps.payload(start, N_DAYS, tuple(float(v) for v in box))
226
 
227
 
228
  def choose_region(region, day):
@@ -231,11 +259,11 @@ def choose_region(region, day):
231
  return gr.update(value=featured_day) if featured_day else gr.update(value=day)
232
 
233
 
234
- def step_day(day, step):
235
- days = maps.DAYS.days
236
  if not days:
237
  return gr.update()
238
- i = days.index(_nearest_day(day))
239
  return gr.update(value=days[min(max(i + step, 0), len(days) - 1)])
240
 
241
 
@@ -248,6 +276,8 @@ with gr.Blocks(title="How much did it really rain?") as demo:
248
  gr.HTML(INTRO, css_template=HERO_CSS, apply_default_css=False, head=GLOBAL_STYLE)
249
  gr.HTML(PROBLEM, css_template=STORY_CSS, apply_default_css=False)
250
  with gr.Row(equal_height=True):
 
 
251
  region = gr.Dropdown(list(REGIONS), value=FEATURED, label="Region", scale=4, min_width=260)
252
  day = gr.DateTime(value=REGIONS[FEATURED][1], include_time=False, type="string",
253
  label="Start day · plays 48 hours", scale=3, min_width=200, elem_id="start-day")
@@ -261,12 +291,15 @@ with gr.Blocks(title="How much did it really rain?") as demo:
261
  gr.Markdown((HERE / "ABOUT.md").read_text())
262
  gr.Markdown(FOOTER)
263
 
 
264
  region.input(choose_region, [region, day], day, api_name=False).then(
265
- show, [region, day], [rain, totals], api_name=False)
266
- day.change(show, [region, day], [rain, totals], api_name="maps")
267
- prev_day.click(lambda d: step_day(d, -1), day, day, api_name=False)
268
- next_day.click(lambda d: step_day(d, 1), day, day, api_name=False)
269
- demo.load(on_load, None, day, api_name=False).then(show, [region, day], [rain, totals], api_name=False)
 
 
270
 
271
  if __name__ == "__main__":
272
  demo.launch(mcp_server=True)
 
1
+ """How much did it really rain? Any two of ERA5 (reanalysis), PARDIG and IMERG (satellite rain maps), side by side."""
2
 
3
  from __future__ import annotations
4
 
 
16
  N_DAYS = 2 # every view plays 48 hours
17
 
18
  FEATURED = "Tropical cyclone, Mozambique Channel"
19
+ #: Dropdown label -> source key in maps.SOURCES.
20
+ DATASETS = {"IMERG (NASA, satellites)": "imerg", "PARDIG (Google, satellites + AI)": "pardig",
21
+ "ERA5 (ECMWF, reanalysis)": "era5"}
22
+ DEFAULT_LEFT, DEFAULT_RIGHT = "IMERG (NASA, satellites)", "PARDIG (Google, satellites + AI)"
23
  REGIONS = {
24
  FEATURED: ((-24, -6, 31, 55), "2026-01-29"),
25
  "Europe": ((35, 72, -25, 45), None),
 
53
  STORY = """
54
  <div class="story">
55
  <section>
56
+ <div class="kicker"><span class="tag tag-map">Reanalysis</span></div>
57
+ <h3>ERA5: a reconstruction of the past weather hour by hour since 1940</h3>
58
  <p>ERA5 is a reanalysis produced by the European Centre for Medium-Range Weather Forecasts (ECMWF). It
59
  reconstructs the past weather hour by hour since 1940, by combining a physics model of the atmosphere with
60
  observations from satellites, weather stations and weather balloons. It is the dataset most AI weather models
61
  are trained on and evaluated against. ERA5 is very good for variables (such as temperature), but
62
+ less accurate for precipitation. The rain from ERA5 is blurred, with light rain over large areas and heavy rain
63
  events that are too weak and too spread out.</p>
64
  </section>
65
  <section>
66
+ <div class="kicker"><span class="tag tag-map">Satellites</span></div>
67
+ <h3>IMERG: NASA's satellite rain map</h3>
68
+ <p>IMERG (Integrated Multi-satellitE Retrievals for GPM) is NASA's standard global rain map, every 30 minutes on
69
+ a 10 km grid. It merges the rain seen by a constellation of microwave satellites, anchored by the GPM Core
70
+ Observatory's radar, and fills the gaps between their passes with infrared images from geostationary satellites.
71
+ Shown here is the Late run, available about 14 hours after real time. It has no reliable rain over snow and ice,
72
+ so high latitudes are often left blank.</p>
73
+ </section>
74
+ <section>
75
+ <div class="kicker"><span class="tag tag-map">Satellites + AI</span></div>
76
  <h3>PARDIG: a new satellite-based reconstruction</h3>
77
  <p>PARDIG (Precipitation AI Reanalysis, Densely Inferred GPM) is a precipitation dataset recently released by
78
  Google DeepMind and Google Research. It estimates the rain over the whole planet every 15 minutes, on a 10 km
79
  grid. An AI model converts geostationary satellite images and weather
80
  analyses into rain. The dataset is openly available under a CC BY 4.0 license.</p>
81
  </section>
82
+ <section class="caveat">
83
+ <div class="kicker"><span class="tag tag-diff">Read with care</span></div>
84
+ <h3>IMERG and PARDIG are not independent</h3>
85
+ <p>PARDIG learns from GPM, the same satellite mission IMERG is built on. Where the two agree, part of the
86
+ agreement comes from sharing that source, so agreement does not prove that both are right. ERA5, built from a
87
+ physics model, is the more independent comparison.</p>
88
+ </section>
89
  </div>
90
  """
91
 
92
  FOOTER = ("Data: [`EmmaScharfmann/era5-pardig-scores`](https://huggingface.co/datasets/EmmaScharfmann/era5-pardig-scores) · "
93
+ "IMERG: NASA GES DISC, doi:10.5067/GPM/IMERG/3B-HH-L/07 · "
94
  "Basemap © OpenStreetMap contributors © CARTO.")
95
 
96
  COMPONENT_HTML = """
97
  <div class="rm">
98
  <div class="rm-maps">
99
  <div class="rm-panel">
100
+ <div class="rm-title">IMERG · 10 km</div>
101
+ <div class="rm-map" data-map="left"></div>
102
  </div>
103
  <div class="rm-panel">
104
  <div class="rm-title">PARDIG · 10 km</div>
105
+ <div class="rm-map" data-map="right"></div>
106
  </div>
107
  <div class="rm-panel">
108
+ <div class="rm-title">IMERG minus PARDIG, both averaged to the 28 km grid</div>
109
  <div class="rm-map" data-map="diff"></div>
110
  </div>
111
  <div class="rm-legend rm-legend-rain" data-for="rain"></div>
 
213
  return None
214
 
215
 
216
+ def _pair(left, right) -> tuple[str, str]:
217
+ return DATASETS.get(left, "imerg"), DATASETS.get(right, "pardig")
218
+
219
+
220
+ def _nearest_day(value, days) -> str:
221
  wanted = _day(value)
222
  if wanted is None:
223
  return days[-1]
 
226
  return days[int(np.abs((pd.DatetimeIndex(days) - pd.Timestamp(wanted)).days).argmin())]
227
 
228
 
229
+ def coverage(days) -> str:
 
230
  return f"Maps from {days[0]} to {days[-1]}" if days else "No maps yet"
231
 
232
 
233
+ def show(region, day, left, right):
234
+ """Rain over a region for 48 hours from a day: two datasets side by side and their difference.
 
235
 
236
  Args:
237
  region: a region name from the list.
238
  day: first day, YYYY-MM-DD.
239
+ left: dataset on the left map (IMERG, PARDIG or ERA5, as in the dropdown).
240
+ right: dataset on the right map.
241
  """
242
  maps.DAYS.refresh()
243
+ a, b = _pair(left, right)
244
+ if a == b:
245
+ raise gr.Error("Pick two different datasets.")
246
+ days = maps.DAYS.for_sources(a, b)
247
+ if not days:
248
+ raise gr.Error(f"No maps stored yet for {left} and {right}.")
249
  box = REGIONS.get(region, REGIONS[FEATURED])[0]
250
+ picked, start = _day(day), _nearest_day(day, days)
251
  if picked and picked != start:
252
+ gr.Info(f"No maps of both for {picked} yet: showing {start}. {coverage(days)}.")
253
+ return maps.payload(start, N_DAYS, tuple(float(v) for v in box), a, b)
254
 
255
 
256
  def choose_region(region, day):
 
259
  return gr.update(value=featured_day) if featured_day else gr.update(value=day)
260
 
261
 
262
+ def step_day(day, step, left, right):
263
+ days = maps.DAYS.for_sources(*_pair(left, right))
264
  if not days:
265
  return gr.update()
266
+ i = days.index(_nearest_day(day, days))
267
  return gr.update(value=days[min(max(i + step, 0), len(days) - 1)])
268
 
269
 
 
276
  gr.HTML(INTRO, css_template=HERO_CSS, apply_default_css=False, head=GLOBAL_STYLE)
277
  gr.HTML(PROBLEM, css_template=STORY_CSS, apply_default_css=False)
278
  with gr.Row(equal_height=True):
279
+ left = gr.Dropdown(list(DATASETS), value=DEFAULT_LEFT, label="Left map", scale=3, min_width=220)
280
+ right = gr.Dropdown(list(DATASETS), value=DEFAULT_RIGHT, label="Right map", scale=3, min_width=220)
281
  region = gr.Dropdown(list(REGIONS), value=FEATURED, label="Region", scale=4, min_width=260)
282
  day = gr.DateTime(value=REGIONS[FEATURED][1], include_time=False, type="string",
283
  label="Start day · plays 48 hours", scale=3, min_width=200, elem_id="start-day")
 
291
  gr.Markdown((HERE / "ABOUT.md").read_text())
292
  gr.Markdown(FOOTER)
293
 
294
+ inputs = [region, day, left, right]
295
  region.input(choose_region, [region, day], day, api_name=False).then(
296
+ show, inputs, [rain, totals], api_name=False)
297
+ day.change(show, inputs, [rain, totals], api_name="maps")
298
+ for pick in (left, right):
299
+ pick.input(show, inputs, [rain, totals], api_name=False)
300
+ prev_day.click(lambda d, a, b: step_day(d, -1, a, b), [day, left, right], day, api_name=False)
301
+ next_day.click(lambda d, a, b: step_day(d, 1, a, b), [day, left, right], day, api_name=False)
302
+ demo.load(on_load, None, day, api_name=False).then(show, inputs, [rain, totals], api_name=False)
303
 
304
  if __name__ == "__main__":
305
  demo.launch(mcp_server=True)
maps.py CHANGED
@@ -1,9 +1,12 @@
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
@@ -62,38 +65,62 @@ LEVELS = {
62
  "total": [0.5, 1, 2, 5, 10, 20, 50, 100, 200], # mm over the span
63
  }
64
 
 
 
 
 
 
 
 
65
 
66
  # ---------------------------------------------------------------------------
67
  # data
68
  # ---------------------------------------------------------------------------
69
  class Days:
70
- """Days whose hourly fields are stored, refreshed from the Hub every REFRESH_S seconds."""
 
71
 
72
  def __init__(self):
73
  self.lock = threading.Lock()
74
  self.days: list[str] = []
 
75
  self.checked = 0.0
76
  self.refresh(force=True)
77
 
 
 
 
 
 
 
78
  def refresh(self, force=False):
79
  if not force and time.time() - self.checked < REFRESH_S:
80
  return
81
  with self.lock:
82
  self.checked = time.time()
83
  try:
84
- if DATA_DIR:
85
- names = [p.name for p in Path(DATA_DIR).glob("fields/*/*/*.zarr.zip")]
86
- else:
87
- from huggingface_hub import HfApi
88
-
89
- names = [Path(f.path).name for f in HfApi().list_repo_tree(
90
- DATA_REPO, path_in_repo="fields", repo_type="dataset", recursive=True)
91
- if f.path.endswith(".zarr.zip")]
92
  except Exception as exc: # keep serving what we have
93
  logger.warning("could not list days: %s", exc)
94
  return
95
- self.days = sorted(n[:10] for n in names)
96
- logger.info("%d day(s) of maps", len(self.days))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
 
99
  DAYS = Days()
@@ -146,30 +173,48 @@ class Events:
146
  EVENTS = Events()
147
 
148
 
149
- @functools.lru_cache(maxsize=6)
150
- def open_day(day: str) -> xr.Dataset:
 
151
  if DATA_DIR:
152
- path = Path(DATA_DIR) / fields.path_for(day)
153
  else:
154
  from huggingface_hub import hf_hub_download
155
 
156
- path = hf_hub_download(DATA_REPO, fields.path_for(day), repo_type="dataset")
157
  return fields.open_fields(path)
158
 
159
 
160
- def _pardig_on_era5_grid(fine: xr.DataArray, lat_min: float, lat_max: float) -> xr.DataArray:
161
  """Conservative 0.1° -> 0.25° for the ERA5 rows of a latitude band only (all longitudes)."""
162
- lat_m, lon_m = regrid.matrices()
163
  rows = np.flatnonzero((grid.LAT >= lat_min - 0.3) & (grid.LAT <= lat_max + 0.3))
164
  band = lat_m[rows]
165
  needed = np.unique(band.indices)
166
  band = band[:, needed]
167
- values = fine.isel(lat_pardig=needed).values # (time, rows, 3600)
168
  out = np.stack([(lon_m @ (band @ v.astype(np.float64)).T).T for v in values]).astype(np.float32)
169
  return xr.DataArray(out, dims=("time", "lat_era5", "lon_era5"),
170
  coords={"time": fine["time"].values, "lat_era5": grid.LAT[rows], "lon_era5": grid.LON})
171
 
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  def load_span(start: str, n_days: int, box, pardig_on_era5_grid: bool) -> tuple[xr.DataArray, xr.DataArray]:
174
  """Hourly ERA5 and PARDIG over the box for ``n_days`` stored days from ``start``."""
175
  days = [d for d in DAYS.days if d >= start][:n_days]
@@ -259,11 +304,12 @@ DIFF_CLASS_COLORS = ["#7f3b08", "#b35806", "#e08214", "#fdb863", "#bdbcb5",
259
  "#b2abd2", "#8073ac", "#542788", "#2d004b"]
260
 
261
 
262
- def difference_classes(era5: np.ndarray, pardig: np.ndarray) -> np.ndarray:
263
- """0 where both are dry, else 1 + the class of ERA5 - PARDIG in DIFF_BOUNDS."""
264
- e, p = np.nan_to_num(era5), np.nan_to_num(pardig)
265
- codes = 1 + np.digitize(e - p, DIFF_BOUNDS)
266
- return np.where((e < WET) & (p < WET), 0, codes).astype(np.float32)
 
267
 
268
 
269
  def agreement(era5: np.ndarray, pardig: np.ndarray) -> np.ndarray:
@@ -278,54 +324,67 @@ def agreement(era5: np.ndarray, pardig: np.ndarray) -> np.ndarray:
278
  return out
279
 
280
 
281
- def summary(era5: xr.DataArray, pardig: xr.DataArray) -> str:
282
- """One plain-language line comparing the two over the hours shown."""
283
  def stats(da):
284
  v = np.asarray(da.values, dtype=float) # (hours, lat, lon)
285
- w = _weights(da)
 
 
286
  total = float((w * np.nansum(v, axis=0)).sum() / w.sum())
287
  wet = float((w[None] * (np.nan_to_num(v) >= 0.1)).sum() / (w.sum() * v.shape[0]))
288
- return total, wet, float(np.nanmax(v)), v.shape[0]
 
 
 
 
 
 
289
 
290
- e, p = stats(era5), stats(pardig)
291
- return (f"Over these {e[3]} hours: on average it rained over **{e[1]:.0%}** of the area in the standard "
292
- f"reconstruction, **{p[1]:.0%}** in the satellite map; the heaviest hour in one spot was "
293
- f"**{e[2]:.0f} mm** in the standard reconstruction, **{p[2]:.0f} mm** in the satellite map.")
294
 
295
 
296
  @functools.lru_cache(maxsize=16)
297
- def payload(start: str, n_days: int, box: tuple) -> tuple[str, str]:
298
- """(JSON for the three-panel map component, one-line summary) for ``n_days`` from ``start``, hourly."""
299
- era5, pardig = load_span(start, n_days, box, False)
300
- _, pardig_coarse = load_span(start, n_days, box, True)
301
- diff = difference_classes(era5.values, pardig_coarse.values)
302
- times = pd.DatetimeIndex(era5["time"].values)
303
- re, rp = Raster(era5), Raster(pardig)
 
 
304
  rain = [lower for _, lower, _ in RAIN_CLASSES]
305
  rain_colors = [None, *RAIN_CLASS_COLORS]
306
  diff_levels = [i + 0.5 for i in range(len(DIFF_CLASS_COLORS))]
307
  diff_colors = [None, *DIFF_CLASS_COLORS]
 
 
308
  data = {
309
  "key": f"{box}",
310
  "view": view(box),
311
  "labels": [_label(t) for t in times],
312
  "panels": [
313
- {"key": "era5", "corners": re.corners, "frames": [re.png(v, rain, rain_colors) for v in era5.values]},
314
- {"key": "pardig", "corners": rp.corners, "frames": [rp.png(v, rain, rain_colors) for v in pardig.values]},
315
- {"key": "diff", "corners": re.corners, "frames": [re.png(v, diff_levels, diff_colors) for v in diff]},
 
 
 
316
  ],
317
  "legends": [
318
- {"target": "rain", "style": "classes", "title": "Rain in the hour, mm · clear: dry",
319
  "names": [name for name, _, _ in RAIN_CLASSES], "labels": [r for _, _, r in RAIN_CLASSES],
320
  "colors": RAIN_CLASS_COLORS},
321
  # Bar drawn wettest first (purple on the left); ticks are the class boundaries, as sizes in mm.
322
- {"target": "diff", "style": "bar", "title": "ERA5 minus PARDIG, mm in the hour · clear: both dry",
323
  "colors": DIFF_CLASS_COLORS[::-1],
324
- "ticks": [f"{abs(b):g}" for b in DIFF_BOUNDS[::-1]],
325
- "ends": ["ERA5 wetter", "about the same", "ERA5 drier"]},
326
  ],
327
  }
328
- return json.dumps(data), summary(era5, pardig)
329
 
330
 
331
  # ---------------------------------------------------------------------------
 
1
+ """Two rain maps over a region (any two of ERA5, PARDIG and IMERG), hour by hour, as frames for the animated
2
+ map component, with their difference.
3
 
4
  Each frame of each source is a small paletted PNG, resampled onto Web-Mercator rows by nearest
5
  neighbour (so 0.25° ERA5 cells stay square and line up with the basemap at any latitude). The
6
  browser component (``rainmaps.js``) preloads the frames and plays them on two synchronised
7
  MapLibre maps.
8
+
9
+ ERA5 and PARDIG come from ``fields/YYYY/MM/DD.zarr.zip`` in the dataset, IMERG from ``imerg/YYYY/MM/DD.zarr.zip``.
10
  """
11
 
12
  from __future__ import annotations
 
65
  "total": [0.5, 1, 2, 5, 10, 20, 50, 100, 200], # mm over the span
66
  }
67
 
68
+ #: Map sources: label, resolution, folder in the dataset, variable, fine grid name in pardig_eval.regrid.
69
+ SOURCES = {
70
+ "imerg": {"label": "IMERG", "res": "10 km", "folder": "imerg", "var": "imerg", "fine": "imerg"},
71
+ "pardig": {"label": "PARDIG", "res": "10 km", "folder": "fields", "var": "pardig", "fine": "pardig"},
72
+ "era5": {"label": "ERA5", "res": "28 km", "folder": "fields", "var": "era5", "fine": None},
73
+ }
74
+
75
 
76
  # ---------------------------------------------------------------------------
77
  # data
78
  # ---------------------------------------------------------------------------
79
  class Days:
80
+ """Days whose hourly fields are stored, per folder (``fields``, ``imerg``), refreshed from the Hub every
81
+ REFRESH_S seconds. ``days`` are those of ``fields`` (ERA5 and PARDIG)."""
82
 
83
  def __init__(self):
84
  self.lock = threading.Lock()
85
  self.days: list[str] = []
86
+ self.by_folder: dict[str, set[str]] = {}
87
  self.checked = 0.0
88
  self.refresh(force=True)
89
 
90
+ def for_sources(self, *sources: str) -> list[str]:
91
+ """Days every one of the sources has maps for."""
92
+ folders = {SOURCES[s]["folder"] for s in sources}
93
+ sets = [self.by_folder.get(f, set()) for f in folders]
94
+ return sorted(set.intersection(*sets)) if sets else []
95
+
96
  def refresh(self, force=False):
97
  if not force and time.time() - self.checked < REFRESH_S:
98
  return
99
  with self.lock:
100
  self.checked = time.time()
101
  try:
102
+ by_folder = {}
103
+ for folder in sorted({v["folder"] for v in SOURCES.values()}):
104
+ by_folder[folder] = {n[:10] for n in self._names(folder)}
 
 
 
 
 
105
  except Exception as exc: # keep serving what we have
106
  logger.warning("could not list days: %s", exc)
107
  return
108
+ self.by_folder = by_folder
109
+ self.days = sorted(by_folder.get("fields", ()))
110
+ logger.info("days of maps: %s", {k: len(v) for k, v in by_folder.items()})
111
+
112
+ @staticmethod
113
+ def _names(folder: str) -> list[str]:
114
+ if DATA_DIR:
115
+ return [p.name for p in Path(DATA_DIR).glob(f"{folder}/*/*/*.zarr.zip")]
116
+ from huggingface_hub import HfApi
117
+ from huggingface_hub.errors import EntryNotFoundError
118
+
119
+ try:
120
+ return [Path(f.path).name for f in HfApi().list_repo_tree(
121
+ DATA_REPO, path_in_repo=folder, repo_type="dataset", recursive=True) if f.path.endswith(".zarr.zip")]
122
+ except EntryNotFoundError: # folder not created yet
123
+ return []
124
 
125
 
126
  DAYS = Days()
 
173
  EVENTS = Events()
174
 
175
 
176
+ @functools.lru_cache(maxsize=8)
177
+ def open_day(day: str, folder: str = "fields") -> xr.Dataset:
178
+ rel = fields.path_for(day, folder)
179
  if DATA_DIR:
180
+ path = Path(DATA_DIR) / rel
181
  else:
182
  from huggingface_hub import hf_hub_download
183
 
184
+ path = hf_hub_download(DATA_REPO, rel, repo_type="dataset")
185
  return fields.open_fields(path)
186
 
187
 
188
+ def _fine_on_era5_grid(fine: xr.DataArray, lat_min: float, lat_max: float, source: str = "pardig") -> xr.DataArray:
189
  """Conservative 0.1° -> 0.25° for the ERA5 rows of a latitude band only (all longitudes)."""
190
+ lat_m, lon_m = regrid.matrices(source)
191
  rows = np.flatnonzero((grid.LAT >= lat_min - 0.3) & (grid.LAT <= lat_max + 0.3))
192
  band = lat_m[rows]
193
  needed = np.unique(band.indices)
194
  band = band[:, needed]
195
+ values = fine.isel({fine.dims[1]: needed}).values # (time, rows, 3600)
196
  out = np.stack([(lon_m @ (band @ v.astype(np.float64)).T).T for v in values]).astype(np.float32)
197
  return xr.DataArray(out, dims=("time", "lat_era5", "lon_era5"),
198
  coords={"time": fine["time"].values, "lat_era5": grid.LAT[rows], "lon_era5": grid.LON})
199
 
200
 
201
+ def _pardig_on_era5_grid(fine: xr.DataArray, lat_min: float, lat_max: float) -> xr.DataArray:
202
+ return _fine_on_era5_grid(fine, lat_min, lat_max, "pardig")
203
+
204
+
205
+ def load_source(source: str, days: list[str], box, on_era5_grid: bool) -> xr.DataArray:
206
+ """Hourly rain of one source over the box for the given days, at its own resolution or on ERA5's grid."""
207
+ meta = SOURCES[source]
208
+ parts = []
209
+ for day in days:
210
+ da = open_day(day, meta["folder"])[meta["var"]]
211
+ if on_era5_grid and meta["fine"]:
212
+ parts.append(fields.crop(_fine_on_era5_grid(da, box[0], box[1], meta["fine"]), *box))
213
+ else:
214
+ parts.append(fields.crop(da, *box).load())
215
+ return xr.concat(parts, "time")
216
+
217
+
218
  def load_span(start: str, n_days: int, box, pardig_on_era5_grid: bool) -> tuple[xr.DataArray, xr.DataArray]:
219
  """Hourly ERA5 and PARDIG over the box for ``n_days`` stored days from ``start``."""
220
  days = [d for d in DAYS.days if d >= start][:n_days]
 
304
  "#b2abd2", "#8073ac", "#542788", "#2d004b"]
305
 
306
 
307
+ def difference_classes(a: np.ndarray, b: np.ndarray) -> np.ndarray:
308
+ """0 where both are dry or either has no data, else 1 + the class of a - b in DIFF_BOUNDS."""
309
+ missing = np.isnan(a) | np.isnan(b)
310
+ a, b = np.nan_to_num(a), np.nan_to_num(b)
311
+ codes = 1 + np.digitize(a - b, DIFF_BOUNDS)
312
+ return np.where(((a < WET) & (b < WET)) | missing, 0, codes).astype(np.float32)
313
 
314
 
315
  def agreement(era5: np.ndarray, pardig: np.ndarray) -> np.ndarray:
 
324
  return out
325
 
326
 
327
+ def summary(left: xr.DataArray, right: xr.DataArray, names=("ERA5", "PARDIG")) -> str:
328
+ """One plain-language line comparing the two over the hours shown (each over the cells it has data for)."""
329
  def stats(da):
330
  v = np.asarray(da.values, dtype=float) # (hours, lat, lon)
331
+ w = _weights(da) * np.isfinite(v).all(0)
332
+ if not w.sum():
333
+ return 0.0, 0.0, 0.0, v.shape[0]
334
  total = float((w * np.nansum(v, axis=0)).sum() / w.sum())
335
  wet = float((w[None] * (np.nan_to_num(v) >= 0.1)).sum() / (w.sum() * v.shape[0]))
336
+ return total, wet, float(np.nanmax(np.where(w[None] > 0, v, np.nan))), v.shape[0]
337
+
338
+ a, b = stats(left), stats(right)
339
+ return (f"Over these {a[3]} hours: on average it rained over **{a[1]:.0%}** of the area in {names[0]}, "
340
+ f"**{b[1]:.0%}** in {names[1]}; the heaviest hour in one spot was **{a[2]:.0f} mm** in {names[0]}, "
341
+ f"**{b[2]:.0f} mm** in {names[1]}.")
342
+
343
 
344
+ def _title(source: str) -> str:
345
+ return f"{SOURCES[source]['label']} · {SOURCES[source]['res']}"
 
 
346
 
347
 
348
  @functools.lru_cache(maxsize=16)
349
+ def payload(start: str, n_days: int, box: tuple, left: str = "imerg", right: str = "pardig") -> tuple[str, str]:
350
+ """(JSON for the three-panel map component, one-line summary) for ``n_days`` from ``start``, hourly:
351
+ ``left`` and ``right`` at their own resolution, and left minus right with both on ERA5's 0.25° grid."""
352
+ days = [d for d in DAYS.for_sources(left, right) if d >= start][:n_days]
353
+ a, b = load_source(left, days, box, False), load_source(right, days, box, False)
354
+ a_c, b_c = load_source(left, days, box, True), load_source(right, days, box, True)
355
+ diff = difference_classes(a_c.values, b_c.values)
356
+ times = pd.DatetimeIndex(a["time"].values)
357
+ ra, rb, rc = Raster(a), Raster(b), Raster(a_c)
358
  rain = [lower for _, lower, _ in RAIN_CLASSES]
359
  rain_colors = [None, *RAIN_CLASS_COLORS]
360
  diff_levels = [i + 0.5 for i in range(len(DIFF_CLASS_COLORS))]
361
  diff_colors = [None, *DIFF_CLASS_COLORS]
362
+ la, lb = SOURCES[left]["label"], SOURCES[right]["label"]
363
+ both_fine = SOURCES[left]["fine"] and SOURCES[right]["fine"]
364
  data = {
365
  "key": f"{box}",
366
  "view": view(box),
367
  "labels": [_label(t) for t in times],
368
  "panels": [
369
+ {"key": "left", "title": _title(left), "corners": ra.corners,
370
+ "frames": [ra.png(v, rain, rain_colors) for v in a.values]},
371
+ {"key": "right", "title": _title(right), "corners": rb.corners,
372
+ "frames": [rb.png(v, rain, rain_colors) for v in b.values]},
373
+ {"key": "diff", "title": f"{la} minus {lb}, both {'averaged to' if both_fine else 'on'} the 28 km grid",
374
+ "corners": rc.corners, "frames": [rc.png(v, diff_levels, diff_colors) for v in diff]},
375
  ],
376
  "legends": [
377
+ {"target": "rain", "style": "classes", "title": "Rain in the hour, mm · clear: dry or no data",
378
  "names": [name for name, _, _ in RAIN_CLASSES], "labels": [r for _, _, r in RAIN_CLASSES],
379
  "colors": RAIN_CLASS_COLORS},
380
  # Bar drawn wettest first (purple on the left); ticks are the class boundaries, as sizes in mm.
381
+ {"target": "diff", "style": "bar", "title": f"{la} minus {lb}, mm in the hour · clear: both dry",
382
  "colors": DIFF_CLASS_COLORS[::-1],
383
+ "ticks": [f"{abs(v):g}" for v in DIFF_BOUNDS[::-1]],
384
+ "ends": [f"{la} wetter", "about the same", f"{la} drier"]},
385
  ],
386
  }
387
+ return json.dumps(data), summary(a, b, (la, lb))
388
 
389
 
390
  # ---------------------------------------------------------------------------
rainmaps.js CHANGED
@@ -137,6 +137,10 @@ async function show() {
137
  const loaded = await Promise.all(data.panels.map((p) => loadImages(p.frames)));
138
  if (token !== state.token) return; // a newer request arrived meanwhile
139
  state.images = {};
 
 
 
 
140
  data.panels.forEach((p, k) => {
141
  state.images[p.key] = loaded[k];
142
  if (state.maps[p.key]) rainLayer(p.key, loaded[k][0].width, loaded[k][0].height, p.corners);
 
137
  const loaded = await Promise.all(data.panels.map((p) => loadImages(p.frames)));
138
  if (token !== state.token) return; // a newer request arrived meanwhile
139
  state.images = {};
140
+ for (const p of data.panels) {
141
+ const title = $(`.rm-map[data-map="${p.key}"]`)?.parentElement.querySelector(".rm-title");
142
+ if (title && p.title) title.textContent = p.title;
143
+ }
144
  data.panels.forEach((p, k) => {
145
  state.images[p.key] = loaded[k];
146
  if (state.maps[p.key]) rainLayer(p.key, loaded[k][0].width, loaded[k][0].height, p.corners);