Maps tab: ERA5 and PARDIG side by side on a basemap
Browse files- app.py +119 -56
- maps.py +247 -0
- requirements.txt +2 -0
app.py
CHANGED
|
@@ -19,6 +19,7 @@ import pandas as pd
|
|
| 19 |
import plotly.graph_objects as go
|
| 20 |
import xarray as xr
|
| 21 |
|
|
|
|
| 22 |
from pardig_eval import grid, scores, sums
|
| 23 |
|
| 24 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -451,76 +452,138 @@ def evaluate(region, lat0, lat1, lon0, lon1, first, last, window_label, map_metr
|
|
| 451 |
)
|
| 452 |
|
| 453 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
# ---------------------------------------------------------------------------
|
| 455 |
# interface
|
| 456 |
# ---------------------------------------------------------------------------
|
| 457 |
ABOUT = (HERE / "ABOUT.md").read_text()
|
|
|
|
| 458 |
|
| 459 |
-
with gr.Blocks(title="ERA5 vs PARDIG") as demo:
|
| 460 |
gr.Markdown(
|
| 461 |
-
"# ERA5 vs PARDIG
|
| 462 |
-
"
|
| 463 |
-
"
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
with gr.Row():
|
|
|
|
| 477 |
first = gr.Dropdown(months, value=months[0] if months else None, label="From month")
|
| 478 |
last = gr.Dropdown(months, value=months[-1] if months else None, label="To month")
|
| 479 |
-
|
| 480 |
-
run = gr.Button("Evaluate", variant="primary")
|
| 481 |
-
with gr.Column(scale=3):
|
| 482 |
summary = gr.Markdown()
|
| 483 |
card = gr.Dataframe(label="Amounts (area-weighted)", interactive=False)
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
da_amount = gr.Plot(show_label=False)
|
| 509 |
-
da_skill = gr.Plot(show_label=False)
|
| 510 |
with gr.Tab("About"):
|
| 511 |
gr.Markdown(ABOUT)
|
| 512 |
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
|
| 525 |
if __name__ == "__main__":
|
| 526 |
demo.launch(mcp_server=True)
|
|
|
|
| 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)
|
|
|
|
| 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):
|
| 484 |
+
maps.DAYS.refresh()
|
| 485 |
+
days = maps.DAYS.days
|
| 486 |
+
return gr.update(choices=days, value=day if day in days else (days[-1] if days else None))
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def step_day(day, step):
|
| 490 |
+
days = maps.DAYS.days
|
| 491 |
+
if day not in days:
|
| 492 |
+
return gr.update()
|
| 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)
|
maps.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 9 |
+
|
| 10 |
+
import base64
|
| 11 |
+
import functools
|
| 12 |
+
import io
|
| 13 |
+
import logging
|
| 14 |
+
import os
|
| 15 |
+
import threading
|
| 16 |
+
import time
|
| 17 |
+
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
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger("maps")
|
| 27 |
+
|
| 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()
|
| 52 |
+
self.days: list[str] = []
|
| 53 |
+
self.checked = 0.0
|
| 54 |
+
self.refresh(force=True)
|
| 55 |
+
|
| 56 |
+
def refresh(self, force=False):
|
| 57 |
+
if not force and time.time() - self.checked < REFRESH_S:
|
| 58 |
+
return
|
| 59 |
+
with self.lock:
|
| 60 |
+
self.checked = time.time()
|
| 61 |
+
try:
|
| 62 |
+
if DATA_DIR:
|
| 63 |
+
names = [p.name for p in Path(DATA_DIR).glob("fields/*/*/*.zarr.zip")]
|
| 64 |
+
else:
|
| 65 |
+
from huggingface_hub import HfApi
|
| 66 |
+
|
| 67 |
+
names = [Path(f.path).name for f in HfApi().list_repo_tree(
|
| 68 |
+
DATA_REPO, path_in_repo="fields", repo_type="dataset", recursive=True)
|
| 69 |
+
if f.path.endswith(".zarr.zip")]
|
| 70 |
+
except Exception as exc: # keep serving what we have
|
| 71 |
+
logger.warning("could not list days: %s", exc)
|
| 72 |
+
return
|
| 73 |
+
self.days = sorted(n[:10] for n in names)
|
| 74 |
+
logger.info("%d day(s) of maps", len(self.days))
|
| 75 |
+
|
| 76 |
+
|
| 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:
|
| 85 |
+
from huggingface_hub import hf_hub_download
|
| 86 |
+
|
| 87 |
+
path = hf_hub_download(DATA_REPO, fields.path_for(day), repo_type="dataset")
|
| 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 |
+
)
|
requirements.txt
CHANGED
|
@@ -5,3 +5,5 @@ xarray
|
|
| 5 |
h5netcdf
|
| 6 |
h5py
|
| 7 |
plotly
|
|
|
|
|
|
|
|
|
| 5 |
h5netcdf
|
| 6 |
h5py
|
| 7 |
plotly
|
| 8 |
+
pillow
|
| 9 |
+
zarr>=3
|