#!/usr/bin/env python3
"""Build the weather evidence page from the saved station and reanalysis files.

Every number on the page is read from weather/knmi-hourly.json or
deliverables/2026-11-28-delft-ihe-pilot/data/era5-hourly.json. Missing station
values stay missing; nothing is interpolated, filled or invented.
"""
from pathlib import Path
import hashlib
import html
import json

HERE = Path(__file__).resolve().parent
PILOT = HERE.parents[1] / 'deliverables' / '2026-11-28-delft-ihe-pilot'
OUT = HERE.parents[1] / 'deliverables' / '2026-11-28-delft-urban-climate-site'
PUB = HERE / 'publication'
ERA5 = PILOT / 'data' / 'era5-hourly.json'
KNMI = HERE / 'weather' / 'knmi-hourly.json'
KNMI_RAW = HERE / 'weather' / 'knmi-344-20250910.txt'

SELECTED = '2025-09-10T23:00'


def sha256(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def esc(value):
    return html.escape(str(value), quote=True)


def fmt(value, unit, digits=1):
    if value is None:
        return '<span class="na">not reported</span>'
    return f'{value:.{digits}f}&nbsp;{unit}'


def compass(degrees):
    if degrees is None:
        return 'not reported'
    points = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
    return f'{degrees:.0f}° ({points[int((degrees % 360) / 22.5 + 0.5) % 16]})'


def direction_text(record):
    code = record.get('wind_direction_code')
    if code == 0:
        return 'calm'
    if code == 990:
        return 'variable'
    return compass(record.get('wind_direction_degrees'))


def rain_text(record, key='precipitation_mm'):
    if record.get('precipitation_trace'):
        return 'trace (&lt;0.05&nbsp;mm)'
    return fmt(record.get(key), 'mm', 2)


def chart_wind(rows):
    """Hourly mean wind and gust from the station, ERA5 wind at 10 m above it."""
    width, height = 820, 260
    pad_l, pad_r, pad_t, pad_b = 46, 18, 20, 46
    plot_w, plot_h = width - pad_l - pad_r, height - pad_t - pad_b
    top = max([r['knmi'].get('gust_ms') or 0 for r in rows] + [r['era5']['wind_speed_10m'] for r in rows])
    top = max(2.0, (int(top * 2) + 2) / 2)
    step_x = plot_w / (len(rows) - 1)

    def y(value):
        return pad_t + plot_h - (value / top) * plot_h

    def x(i):
        return pad_l + i * step_x

    bar = plot_w / len(rows) * 0.52
    parts = [f'<svg class="chart" viewBox="0 0 {width} {height}" role="img" aria-label="Hourly wind at KNMI station 344 and ERA5 wind speed for 10 September 2025">']
    for tick in range(0, int(top) + 1):
        gy = y(tick)
        parts.append(f'<line class="grid" x1="{pad_l}" x2="{width - pad_r}" y1="{gy:.1f}" y2="{gy:.1f}"/>')
        parts.append(f'<text class="axis" x="{pad_l - 8}" y="{gy + 4:.1f}" text-anchor="end">{tick}</text>')
    parts.append(f'<text class="axis-title" x="{pad_l - 30}" y="{pad_t + 4}" text-anchor="middle" transform="rotate(-90 {pad_l - 30} {pad_t + plot_h / 2})" dy="{plot_h / 2}">m/s</text>')
    for i, row in enumerate(rows):
        gust = row['knmi'].get('gust_ms')
        if gust is not None:
            parts.append(f'<rect class="gust" x="{x(i) - bar / 2:.1f}" y="{y(gust):.1f}" width="{bar:.1f}" height="{y(0) - y(gust):.1f}" rx="2"><title>{row["time"]} UTC gust {gust:.1f} m/s</title></rect>')
    path = []
    for i, row in enumerate(rows):
        value = row['knmi'].get('wind_speed_ms')
        if value is None:
            continue
        path.append(('M' if not path else 'L') + f'{x(i):.1f} {y(value):.1f}')
    parts.append(f'<path class="series-station" d="{" ".join(path)}"/>')
    path = [f'{"M" if i == 0 else "L"}{x(i):.1f} {y(row["era5"]["wind_speed_10m"]):.1f}' for i, row in enumerate(rows)]
    parts.append(f'<path class="series-era5" d="{" ".join(path)}"/>')
    for i, row in enumerate(rows):
        if i % 3 == 0 or i == len(rows) - 1:
            parts.append(f'<text class="axis" x="{x(i):.1f}" y="{height - pad_b + 20}" text-anchor="middle">{row["time"][11:16]}</text>')
    parts.append(f'<text class="axis" x="{width / 2}" y="{height - 6}" text-anchor="middle">hour ending (UTC), 10 September 2025</text>')
    parts.append('</svg>')
    return ''.join(parts)


def chart_rain(rows):
    width, height = 820, 220
    pad_l, pad_r, pad_t, pad_b = 46, 18, 18, 46
    plot_w, plot_h = width - pad_l - pad_r, height - pad_t - pad_b
    top = max([r['knmi']['precipitation_mm'] or 0 for r in rows] + [r['era5']['rain'] for r in rows])
    top = max(0.5, (int(top * 4) + 1) / 4)
    slot = plot_w / len(rows)
    bar = slot * 0.34

    def y(value):
        return pad_t + plot_h - (value / top) * plot_h

    parts = [f'<svg class="chart" viewBox="0 0 {width} {height}" role="img" aria-label="Hourly precipitation at KNMI station 344 compared with ERA5 rain for 10 September 2025">']
    ticks = 4
    for k in range(ticks + 1):
        value = top * k / ticks
        gy = y(value)
        parts.append(f'<line class="grid" x1="{pad_l}" x2="{width - pad_r}" y1="{gy:.1f}" y2="{gy:.1f}"/>')
        parts.append(f'<text class="axis" x="{pad_l - 8}" y="{gy + 4:.1f}" text-anchor="end">{value:.2f}</text>')
    for i, row in enumerate(rows):
        cx = pad_l + slot * (i + 0.5)
        station = row['knmi']['precipitation_mm']
        if station is not None and station > 0:
            parts.append(f'<rect class="rain-station" x="{cx - bar - 1:.1f}" y="{y(station):.1f}" width="{bar:.1f}" height="{y(0) - y(station):.1f}" rx="1.5"><title>{row["time"]} UTC station {station:.2f} mm</title></rect>')
        elif row['knmi']['precipitation_trace']:
            parts.append(f'<circle class="rain-trace" cx="{cx - bar / 2 - 1:.1f}" cy="{y(0) - 4:.1f}" r="2"><title>{row["time"]} UTC trace only, less than 0.05 mm</title></circle>')
        era = row['era5']['rain']
        if era > 0:
            parts.append(f'<rect class="rain-era5" x="{cx + 1:.1f}" y="{y(era):.1f}" width="{bar:.1f}" height="{y(0) - y(era):.1f}" rx="1.5"><title>{row["time"]} UTC ERA5 {era:.2f} mm</title></rect>')
        if i % 3 == 0 or i == len(rows) - 1:
            parts.append(f'<text class="axis" x="{cx:.1f}" y="{height - pad_b + 20}" text-anchor="middle">{row["time"][11:16]}</text>')
    parts.append(f'<text class="axis-title" x="{pad_l - 30}" y="{pad_t + 4}" text-anchor="middle" transform="rotate(-90 {pad_l - 30} {pad_t + plot_h / 2})" dy="{plot_h / 2}">mm</text>')
    parts.append(f'<text class="axis" x="{width / 2}" y="{height - 6}" text-anchor="middle">hour ending (UTC), 10 September 2025</text>')
    parts.append('</svg>')
    return ''.join(parts)


def build():
    knmi = json.loads(KNMI.read_text())
    era5 = json.loads(ERA5.read_text())
    records = knmi['records']
    assert len(records) == 24, 'Station snapshot must hold 24 hours'
    assert [r['time'] for r in records] == era5['hourly']['time'], 'Station and ERA5 timestamps must align'
    station = knmi['station']

    rows = []
    for i, record in enumerate(records):
        rows.append({'time': record['time'], 'knmi': record,
                     'era5': {'rain': era5['hourly']['rain'][i], 'wind_speed_10m': era5['hourly']['wind_speed_10m'][i]}})
    selected = next(r for r in rows if r['time'] == SELECTED)
    station_rain_total = sum(r['knmi']['precipitation_mm'] or 0 for r in rows)
    era5_rain_total = sum(r['era5']['rain'] for r in rows)
    gusts = [r['knmi']['gust_ms'] for r in rows if r['knmi'].get('gust_ms') is not None]
    winds = [r['knmi']['wind_speed_ms'] for r in rows if r['knmi'].get('wind_speed_ms') is not None]
    temps = [r['knmi']['temperature_c'] for r in rows if r['knmi'].get('temperature_c') is not None]
    trace_hours = sum(1 for r in rows if r['knmi']['precipitation_trace'])
    missing = sum(1 for r in rows for key, value in r['knmi'].items() if value is None and key != 'wind_direction_degrees')

    table_rows = ''.join(
        '<tr' + (' class="selected"' if r['time'] == SELECTED else '') + '>'
        f'<th scope="row">{r["time"][11:16]}</th>'
        f'<td>{fmt(r["knmi"].get("temperature_c"), "°C")}</td>'
        f'<td>{fmt(r["knmi"].get("wind_speed_ms"), "")}</td>'
        f'<td>{fmt(r["knmi"].get("gust_ms"), "")}</td>'
        f'<td>{esc(direction_text(r["knmi"]))}</td>'
        f'<td>{rain_text(r["knmi"])}</td>'
        f'<td>{fmt(r["era5"]["rain"], "", 2)}</td>'
        f'<td>{fmt(r["era5"]["wind_speed_10m"], "")}</td>'
        '</tr>'
        for r in rows)

    knmi_sha = sha256(KNMI)
    raw_sha = sha256(KNMI_RAW)
    era5_sha = sha256(ERA5)
    params = knmi['source']['parameters']

    def row(label, value, note=''):
        note_html = f'<p class="note">{note}</p>' if note else ''
        return f'<div class="stat"><dt>{label}</dt><dd>{value}</dd>{note_html}</div>'

    page = f'''<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Weather evidence for 10 September 2025 | IHE Delft urban wind pilot</title>
<meta name="description" content="Measured KNMI station observations and ERA5 reanalysis for the 10 September 2025 IHE Delft urban wind pilot: 24 hourly values, provenance, downloads and stated limits.">
<meta name="author" content="Gerald Augusto Corzo Perez">
<link rel="canonical" href="https://hydroinformatics.org/delft-urban-climate/weather.html">
<meta property="og:type" content="article">
<meta property="og:title" content="Weather evidence for 10 September 2025">
<meta property="og:url" content="https://hydroinformatics.org/delft-urban-climate/weather.html">
<link rel="stylesheet" href="editorial.css">
<link rel="stylesheet" href="weather.css">
</head>
<body>
<header class="masthead"><nav aria-label="Site navigation"><a class="brand" href="/">Hydroinformatics</a><a href="index.html">Feature article</a><a href="explorer.html">Interactive explorer</a><a href="article.html">Methods &amp; data</a><a href="weather.html" aria-current="page">Weather evidence</a><a href="integration.html">WRF integration</a></nav></header>
<main>
<article>
<div class="eyebrow">WEATHER EVIDENCE / OBSERVED AND REANALYSED</div>
<h1>What the weather did while the street was modelled</h1>
<p class="byline">Gerald Augusto Corzo Perez · IHE Delft Institute for Water Education · 10 September 2025, 00:00–23:00 UTC<br>KNMI station 344 (Rotterdam The Hague Airport) and ERA5 reanalysis, documented, downloadable and bounded.</p>

<p>The wind animation is one steady calculation at 20&nbsp;m with a fixed inlet. This page records the weather that the calculation and the rainfall layer were built around, so that a reader can check the boundary conditions instead of taking them on trust. Nothing here validates the model: the station measures at one point on an airport runway, and the CFD slice describes a street in a different place and at a different height.</p>

<h2 id="the-moment-used">The moment used in the animation</h2>
<dl class="stats">
{row('Station air temperature', fmt(selected['knmi'].get('temperature_c'), '°C'), 'Measured at 1.50&nbsp;m above ground. One point, not a city temperature field.')}
{row('Hourly mean wind', fmt(selected['knmi'].get('wind_speed_ms'), 'm/s'), 'Mean over the preceding hour, 10&nbsp;m above open terrain.')}
{row('Maximum gust in the hour', fmt(selected['knmi'].get('gust_ms'), 'm/s'), 'Highest short-duration gust within the same hour.')}
{row('Wind direction', esc(direction_text(selected['knmi'])), 'Last-10-minute mean direction, from which the wind blows.')}
{row('Station precipitation', rain_text(selected['knmi']), 'Depth in the preceding hour. A dash means less than 0.05&nbsp;mm.')}
{row('ERA5 rain, same hour', fmt(selected['era5']['rain'], 'mm', 2), 'One reanalysis grid cell of roughly 0.25°, centred away from the station.')}
</dl>
<p class="note">ERA5 wind at the same hour is {fmt(selected['era5']['wind_speed_10m'], 'm/s')} at 10&nbsp;m. The OpenFOAM inlet uses 5.63&nbsp;m/s from 186° as recorded in the earlier method note; the station and reanalysis values above are documentation of the day, not the inlet that was applied.</p>

<h2 id="the-whole-day">The whole day, hour by hour</h2>
<figure>
{chart_wind(rows)}
<figcaption><strong>Wind.</strong> Bars: station gusts. Solid line: station hourly mean wind. Dashed line: ERA5 wind speed at 10&nbsp;m. All three describe different sampling and different footprints, so agreement is not expected to be exact.</figcaption>
</figure>
<figure>
{chart_rain(rows)}
<figcaption><strong>Rain.</strong> Left bar in each pair: KNMI station total for the preceding hour. Right bar: ERA5 rain for the same hour. Dots mark trace hours below 0.05&nbsp;mm, drawn rather than counted as measured zeros.</figcaption>
</figure>
<div class="tablewrap">
<table>
<caption>10 September 2025, UTC. Hour labels are interval ends, following the KNMI convention. Blank cells are unreported values, never filled.</caption>
<thead><tr><th scope="col">Hour</th><th scope="col">Temp<br>°C</th><th scope="col">Wind<br>m/s</th><th scope="col">Gust<br>m/s</th><th scope="col">From</th><th scope="col">Station rain<br>mm</th><th scope="col">ERA5 rain<br>mm</th><th scope="col">ERA5 wind<br>m/s</th></tr></thead>
<tbody>{table_rows}</tbody>
</table>
</div>
<p class="note">Day totals: station {station_rain_total:.2f}&nbsp;mm in {len(rows)} hours, with {trace_hours} trace hour(s); ERA5 {era5_rain_total:.2f}&nbsp;mm. Station wind range {min(winds):.1f}–{max(winds):.1f}&nbsp;m/s, gusts up to {max(gusts):.1f}&nbsp;m/s, temperature {min(temps):.1f}–{max(temps):.1f}&nbsp;°C. {missing} value(s) are missing across the day and are left missing.</p>

<h2 id="provenance">Where these numbers come from</h2>
<h3>Station observations</h3>
<dl class="provenance">
<dt>Provider and product</dt><dd>Royal Netherlands Meteorological Institute (KNMI), historical hourly station observations, <code>uurgegevens</code>. Open data under CC&nbsp;BY&nbsp;4.0.</dd>
<dt>Station</dt><dd>{esc(station['name'])} (id {station['id']}), {station['latitude']:.5f}°&nbsp;N, {station['longitude']:.5f}°&nbsp;E, {station['altitude_m']:.0f}&nbsp;m above mean sea level, {station['distance_to_ihe_km']:.2f}&nbsp;km from the modelled address.</dd>
<dt>Request</dt><dd>HTTP POST to <code>{esc(knmi['source']['url'])}</code> with <code>{esc('&amp;'.join(f'{k}={v}' for k, v in params.items()))}</code>. Documentation: <a href="{esc(knmi['source']['documentation'])}">KNMI hourly observations</a>.</dd>
<dt>Units and conventions</dt><dd>{esc('; '.join(f'{k}: {v}' for k, v in knmi['units'].items()))}.</dd>
<dt>Timestamp convention</dt><dd>{esc(knmi['timestamp_convention'])}</dd>
<dt>Traces and gaps</dt><dd>{esc(knmi['trace_policy'])}</dd>
<dt>Files</dt><dd><code>knmi-hourly.json</code> sha256 <code>{knmi_sha}</code>; raw response <code>knmi-344-20250910.txt</code> sha256 <code>{raw_sha}</code>. Request executed once; both files are stored with the repository so the page can be rebuilt offline.</dd>
</dl>

<h3>Reanalysis</h3>
<dl class="provenance">
<dt>Provider and product</dt><dd>ERA5 via the Open-Meteo historical archive API, Copernicus Climate Change Service. Weather data by Open-Meteo, CC&nbsp;BY&nbsp;4.0.</dd>
<dt>Grid</dt><dd>Requested at 52.00885°&nbsp;N, 4.35677°&nbsp;E; the archive returned the cell centred at {era5['latitude']}, {era5['longitude']}, about 0.25° or roughly 25&nbsp;km wide.</dd>
<dt>Variables</dt><dd>Hourly rain accumulated over the preceding hour, precipitation, wind speed and direction at 10&nbsp;m; UTC.</dd>
<dt>File</dt><dd><code>data/era5-hourly.json</code> sha256 <code>{era5_sha}</code>.</dd>
</dl>

<h2 id="limits">What this evidence cannot support</h2>
<ul>
{''.join(f'<li>{esc(item)}</li>' for item in knmi['limitations'])}
<li>The station sits on an airfield {station['distance_to_ihe_km']:.2f}&nbsp;km away, with an open, flat footprint; a courtyard, a facade or a canal bank in the neighbourhood can differ sharply, and this pilot has no measurement there.</li>
<li>The two rainfall columns are not a comparison of accuracy. They describe a point gauge and a grid-cell average, and a single day cannot rank either of them.</li>
<li>No radar rainfall field, no temperature simulation and no new OpenFOAM run were added for this page. The CFD animation and its inlet remain as published in the method note.</li>
</ul>

<h2 id="downloads">Download the evidence</h2>
<ul class="downloads">
<li><a href="data/knmi-hourly.json">knmi-hourly.json</a> — 24 normalised station hours with units, flags and provenance.</li>
<li><a href="data/knmi-344-20250910.txt">knmi-344-20250910.txt</a> — the unmodified KNMI response.</li>
<li><a href="data/era5-hourly.json">era5-hourly.json</a> — ERA5 hourly values used by the explorer.</li>
<li><a href="data/weather-provenance.json">weather-provenance.json</a> — request URLs, returned grid cell and file hashes.</li>
<li><a href="fetch_knmi.py">fetch_knmi.py</a> and <a href="build_weather_page.py">build_weather_page.py</a> — the scripts that produced this page.</li>
</ul>
<p class="note">To reproduce: <code>python3 fetch_knmi.py</code> (network), then <code>python3 build_weather_page.py</code> and <code>node check_weather_evidence.mjs</code>. The check fails if a value is missing from the table, if a timestamp is misaligned with ERA5, or if a provenance field is absent.</p>

<div class="callout"><p><strong>Status.</strong> Observations and reanalysis are complete for this one day and clearly separated from model output. The next weather step is a second station or a radar field, so that spatial variation can be discussed at all.</p></div>
</article>
</main>
<footer>Gerald Augusto Corzo Perez · IHE Delft Institute for Water Education · <a href="https://orcid.org/0000-0002-2773-7817">ORCID</a> · <a href="index.html">Feature article</a> · <a href="/">Hydroinformatics home</a><br>Station data: KNMI (CC&nbsp;BY&nbsp;4.0). Reanalysis: ERA5 / Copernicus Climate Change Service via Open-Meteo (CC&nbsp;BY&nbsp;4.0).</footer>
</body>
</html>
'''

    css = '''.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;margin:28px 0;padding:0}
.stats .stat{margin:0;padding:16px 18px;border:1px solid #cbd8d0;border-radius:6px;background:#fff}
.stats dt{font:12px/1.4 system-ui,sans-serif;letter-spacing:1.2px;text-transform:uppercase;color:#567065}
.stats dd{margin:6px 0 0;font:26px/1.25 system-ui,sans-serif;font-weight:650;color:#12332c}
.stats .note{margin:8px 0 0;font:12px/1.5 system-ui,sans-serif;color:#5b6f68}
.na{font-size:15px;font-weight:500;color:#8a6a2a;font-style:italic}
.chart{width:100%;height:auto;display:block;background:#fff;border:1px solid #cbd8d0;border-radius:6px}
.chart .grid{stroke:#e4ece7;stroke-width:1}
.chart .axis{font:11px system-ui,sans-serif;fill:#5b6f68}
.chart .axis-title{font:11px system-ui,sans-serif;fill:#5b6f68;letter-spacing:1px;text-transform:uppercase}
.chart .gust{fill:#cfe3d8}
.chart .series-station{fill:none;stroke:#126359;stroke-width:2.2;stroke-linejoin:round}
.chart .series-era5{fill:none;stroke:#a8552c;stroke-width:1.8;stroke-dasharray:5 4}
.chart .rain-station{fill:#2f6f8f}
.chart .rain-era5{fill:#c98a4b}
.chart .rain-trace{fill:#2f6f8f;opacity:.55}
.tablewrap{overflow-x:auto;margin:26px 0}
table{border-collapse:collapse;width:100%;font:13px/1.45 system-ui,sans-serif}
table caption{caption-side:top;text-align:left;font:12px/1.5 system-ui,sans-serif;color:#5b6f68;padding-bottom:10px}
th,td{padding:6px 8px;border-bottom:1px solid #e4ece7;text-align:right;white-space:nowrap}
thead th{position:sticky;top:0;background:#f4f7f4;font-weight:650;color:#173e36;border-bottom:1px solid #cbd8d0;vertical-align:bottom}
tbody th{text-align:left;font-weight:600;font-variant-numeric:tabular-nums}
tbody tr:nth-child(even) td,tbody tr:nth-child(even) th{background:#fbfcfa}
tbody tr.selected td,tbody tr.selected th{background:#f2f8ef;box-shadow:inset 0 0 0 1px #b7e7cd;font-weight:650}
tbody tr.selected th::after{content:" · used";font-weight:500;color:#567065}
.provenance{font:14px/1.6 system-ui,sans-serif;margin:22px 0;padding:0}
.provenance dt{font-weight:650;color:#173e36;margin-top:12px}
.provenance dd{margin:3px 0 0;color:#31443f}
code{font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;background:#f2f5f2;padding:1px 5px;border-radius:3px;overflow-wrap:anywhere}
.downloads{font:15px/1.7 system-ui,sans-serif;padding-left:20px}
.callout{margin:38px 0 0;padding:18px 20px;border-left:3px solid #126359;background:#f2f8ef;border-radius:0 6px 6px 0;font-size:17px}
@media(max-width:600px){.stats dd{font-size:22px}th,td{padding:5px 6px;font-size:12px}}
'''

    PUB.mkdir(exist_ok=True)
    (PUB / 'weather.html').write_text(page)
    (PUB / 'weather.css').write_text(css)

    data = OUT / 'data'
    data.mkdir(parents=True, exist_ok=True)
    for source, name in [(KNMI, 'knmi-hourly.json'), (KNMI_RAW, 'knmi-344-20250910.txt'),
                         (ERA5, 'era5-hourly.json'), (PILOT / 'data' / 'weather-provenance.json', 'weather-provenance.json')]:
        (data / name).write_bytes(source.read_bytes())
    for name in ['fetch_knmi.py', 'build_weather_page.py', 'check_weather_evidence.mjs']:
        if (HERE / name).exists():
            (OUT / name).write_bytes((HERE / name).read_bytes())
    (OUT / 'weather.html').write_text(page)
    (OUT / 'weather.css').write_text(css)
    print(json.dumps({'page': str(OUT / 'weather.html'), 'hours': len(rows), 'selected': selected['time'],
                      'station_rain_total': round(station_rain_total, 2), 'era5_rain_total': round(era5_rain_total, 2),
                      'missing_values': missing, 'trace_hours': trace_hours}, indent=2))


if __name__ == '__main__':
    build()
