Pacific Northwest Modeled Streamflow Change in H3 Cells

python
geospatial
hydrology
streamflow
National Water Model
h3
hexagons
MapLibre
30 Day Map Challenge
Author

Marc Weber

Published

November 20, 2026

Pacific Northwest Modeled Streamflow Change

I’ve been wanting to do something using H3 hexagons and have also been using National Water Model data recently, so this seemed like a fun excuse for the 30 Day Map Challenge. I created this using some AI assistance after a recent PNW atmospheric river, and this exploratory view shows how NOAA National Water Model (NWM) channel-routing flow changed during Nov 9–14, 2026. Each hexagon represents one selected modeled river reach, not every stream or the land area inside the cell. Values are relative to that reach’s median flow on Nov 9 (the first four 6-hourly frames); this is not a historical anomaly, observed-flow map, or measure of flood severity.

Press play or drag the slider to step through Nov 9–14, 2026. Color shows the per-reach flow ratio relative to the Nov 9 median (capped at 10×); height shows the rise in modeled flow in m³/s. Gray hexagons are likely regulated (dam-influenced) reaches. Click a hexagon for its reach ID, flows and hydrograph.

Tech Stack

• Data Access: xarray + fsspec + s3fs (with zarr and h5netcdf) to stream NWM data directly from AWS S3 without downloading large archives. • Spatial Indexing: h3 (v4+) and pandas. Hexagon polygons are built directly from H3 boundaries, so no geopandas or shapely is needed. • Web Display: a hand-written MapLibre GL JS page (no Python mapping library) that animates 3D fill-extrusions.

Step-By-Step Python Workflow

Step 1: Build a Spatial Hex-Lookup (reach coordinates → H3)

• Why: Operational NWM streamflow files only contain river reach IDs (feature_id), not coordinates. • What the script does: It reads each reach’s latitude and longitude from the NWM v3.0 retrospective Zarr store (chrtout.zarr), filters to the Pacific Northwest (42°N–49°N, -124.8°W to -116.5°W), assigns each reach to an H3 Resolution 6 hexagon (~36 km²), and caches the lookup as pnw_routelink.parquet so later runs are fast. (The RouteLink_CONUS.nc file is not hosted in this bucket, so the Zarr store is used for coordinates only.)

Step 2: Stream Recent Atmospheric River Data from AWS S3

• Why: NOAA publishes hourly NWM analysis_assim (assimilated streamflow) files on AWS Open Data (s3://noaa-nwm-pds), but only for a rolling window of about four weeks. • What the script does: It streams 6-hourly snapshots for Nov 9–14, 2026 (24 frames) with fsspec and xarray, keeping only the PNW reaches in memory instead of downloading the full national files. Export stops with an explicit error if any expected snapshot is unavailable, rather than silently shifting the baseline or animation timeline.

Step 3: Select Reaches & Compute Baseline Ratios

• Why: Raw discharge varies greatly among rivers, so color shows within-reach change rather than comparing absolute flow values. A single snapshot can also be unrepresentative, so the baseline is the median of the first day. • What the script does: Reaches missing any frame are excluded. Repeated >10× step changes are flagged for review. Reaches with at least four large up/down reversals (each larger than 20% of the reach’s mean flow) are flagged as likely regulated, a pattern typical of dam operations, and so are cells on the Columbia mainstem with a baseline above 1,000 m³/s (identified with an approximate hand-drawn path). No flag removes a reach. Each cell selects the reach with the highest mean flow over the window. The baseline is the median of that reach’s first four frames (Nov 9, 00:00–18:00 UTC); cells with a baseline at or below 5 m³/s are excluded (MIN_BASELINE_CMS). Every frame is divided by the baseline. The uncapped ratio is retained to three decimal places, while the map’s color is capped at 10×.

Step 4: Export GeoJSON & JS Data File

• Why: A static data file plus a single HTML page can be hosted on GitHub Pages with no server-side code. • What the script does: It writes the hexagon polygons, capped display ratios, uncapped ratios, selected reach IDs, jump and regulated flags (with the reason), and model/metric metadata to a minified pnw_hex_surge.geojson and pnw_hex_data.js (window.HEX_DATA = ...). map.html uses these fields for the animation and the click popup. The script-tag data load works on a server, GitHub Pages, or a double-click.

Step 5: GPU-Accelerated MapLibre Animation

• How the web map works: The whole time series is stored in each hexagon’s properties. Because MapLibre turns array properties into strings, the page first copies each frame’s values into their own properties (s0, s1, … and h0, h1, …). Each frame, it updates fill-extrusion-color from the capped ratio (gray for likely regulated reaches) and fill-extrusion-height from the rise in flow, so the geometry is never reloaded.

import os
import json
import h3
import fsspec
import numpy as np
import xarray as xr
import pandas as pd

MIN_BASELINE_CMS = 5.0    # exclude cells whose representative reach has a baseline at or below this flow (m³/s)
BASELINE_FRAMES = 4       # baseline = median of the first 4 frames (Nov 9, 00:00–18:00 UTC)
SURGE_CAP = 10.0          # display cap; uncapped ratios are retained in the export
JUMP_FACTOR = 10.0        # a step-to-step change larger than this (up or down) is a "jump"
MAX_JUMPS = 2             # repeated jumps trigger a review flag, not automatic exclusion
OSC_REL = 0.20            # a swing counts as large if it exceeds 20% of the reach's mean flow
OSC_MIN_REVERSALS = 4     # this many large up/down reversals flags a likely regulated reach
LARGE_RIVER_CMS = 1000.0  # Columbia mainstem cells above this baseline are treated as regulated
COLUMBIA_TOL_DEG = 0.35   # max distance (degrees) from the approximate mainstem path below
# Approximate Columbia mainstem path (lat, lon), from the Canadian border to the mouth.
COLUMBIA_PATH = [
    (49.00, -117.63), (48.60, -118.10), (48.20, -118.20), (47.96, -118.98), (47.99, -119.64),
    (47.95, -119.86), (47.53, -120.30), (47.30, -120.20), (47.00, -119.97), (46.64, -119.92),
    (46.60, -119.35), (46.28, -119.27), (46.05, -118.95), (45.92, -119.30), (45.70, -120.30),
    (45.62, -121.17), (45.70, -121.60), (45.62, -122.50), (45.65, -122.78), (46.10, -123.10),
    (46.20, -123.80),
]


def distance_to_columbia_deg(lat, lon):
    """Approximate distance (degrees) from a point to the Columbia mainstem polyline."""
    k = np.cos(np.radians(lat))
    best = np.inf
    for (a1, o1), (a2, o2) in zip(COLUMBIA_PATH[:-1], COLUMBIA_PATH[1:]):
        x, y = (lon - o1) * k, lat - a1
        dx, dy = (o2 - o1) * k, a2 - a1
        t = max(0.0, min(1.0, (x * dx + y * dy) / (dx * dx + dy * dy)))
        best = min(best, float(np.hypot(x - t * dx, y - t * dy)))
    return best


# ==========================================
# 1. FETCH & CACHE PNW COORDINATE LOOKUP
# ==========================================
ROUTELINK_CACHE = "pnw_routelink.parquet"

if os.path.exists(ROUTELINK_CACHE):
    meta = pd.read_parquet(ROUTELINK_CACHE)
else:
    print("Reading NWM reach coordinates from the retrospective Zarr (one-time)...")
    # RouteLink_CONUS.nc is not hosted in this bucket; the Zarr store carries
    # per-reach latitude/longitude keyed by feature_id.
    zarr_url = "s3://noaa-nwm-retrospective-3-0-pds/CONUS/zarr/chrtout.zarr"
    ds_rl = xr.open_zarr(zarr_url, storage_options={"anon": True})
    meta = pd.DataFrame({
        "feature_id": ds_rl["feature_id"].values,
        "lat": ds_rl["latitude"].values,
        "lon": ds_rl["longitude"].values,
    })

    # Filter to Pacific Northwest bounding box (OR, WA, parts of ID)
    meta = meta[
        (meta["lat"].between(42.0, 49.0)) &
        (meta["lon"].between(-124.8, -116.5))
    ].copy()

    # Assign H3 Resolution 6 hexagons (~36 km² cells)
    meta["h3_cell"] = [
        h3.latlng_to_cell(la, lo, 6) for la, lo in zip(meta["lat"], meta["lon"])
    ]
    meta.to_parquet(ROUTELINK_CACHE, index=False)

pnw_ids = set(meta["feature_id"])
print(f"Tracking {len(pnw_ids):,} PNW river reaches across {meta['h3_cell'].nunique():,} hexagons.")

# ==========================================
# 2. STREAM THIS WEEK'S NWM DATA (NOV 9–14, 2026)
# ==========================================
dates = pd.date_range("2026-11-09 00:00", "2026-11-14 18:00", freq="6h")
ts_dict = {}

for dt in dates:
    d_str = dt.strftime("%Y%m%d")
    h_str = dt.strftime("%H")
    url = f"s3://noaa-nwm-pds/nwm.{d_str}/analysis_assim/nwm.t{h_str}z.analysis_assim.channel_rt.tm00.conus.nc"

    try:
        with fsspec.open(url, anon=True) as f:
            ds = xr.open_dataset(f, engine="h5netcdf")
            mask = pd.Series(ds["feature_id"].values).isin(pnw_ids).values
            ids = ds["feature_id"].values[mask]
            flow = ds["streamflow"].values[mask]
            ts_dict[dt] = pd.Series(flow, index=ids)
    except Exception as e:
        print(f"Skipped {dt.strftime('%Y-%m-%d %H:%M UTC')}: {e}")
print(f"Loaded {len(ts_dict)} of {len(dates)} time steps.")
missing_dates = [dt for dt in dates if dt not in ts_dict]
if missing_dates:
    missing_text = ", ".join(dt.strftime("%Y-%m-%d %H:%M UTC") for dt in missing_dates)
    raise RuntimeError(f"Cannot export an evenly spaced animation; missing NWM snapshots: {missing_text}")

# ==========================================
# 3. SELECT REACHES & COMPUTE BASELINE RATIOS
# ==========================================
q_df = pd.DataFrame(ts_dict)
flow_cols = [c for c in q_df.columns if c != "h3_cell"]
complete = q_df[flow_cols].notna().all(axis=1)
dropped_incomplete = int((~complete).sum())
q_df = q_df.loc[complete].copy()
print(f"Skipping {dropped_incomplete:,} reaches with incomplete time series.")
if q_df.empty:
    raise RuntimeError("No reaches have a complete time series for all expected snapshots.")
q_df["h3_cell"] = meta.set_index("feature_id")["h3_cell"]

# Flag repeated large changes between 6-hourly steps for review. These can reflect
# regulation, model behavior, or real events; the flag is not a quality verdict.
# Flows are floored at 1 m³/s for jump detection so near-zero values do not dominate.
arr = q_df[flow_cols].clip(lower=1.0).to_numpy()
step = arr[:, 1:] / arr[:, :-1]
q_df["_jumps"] = ((step > JUMP_FACTOR) | (step < 1 / JUMP_FACTOR)).sum(axis=1)
q_df["_jump_flag"] = q_df["_jumps"] > MAX_JUMPS
print(f"Flagging {int(q_df['_jump_flag'].sum()):,} reaches with more than {MAX_JUMPS} jumps of {JUMP_FACTOR:g}x for review.")

# Flag likely regulated reaches: repeated large up/down swings (relative to mean flow),
# as produced by dam operations. A storm hydrograph reverses direction about once.
# This is a heuristic, not a confirmed regulation list.
vals = q_df[flow_cols].to_numpy()
mean_flow = np.maximum(vals.mean(axis=1), 1.0)
delta = np.diff(vals, axis=1)
big = np.abs(delta) > OSC_REL * mean_flow[:, None]
reversal = (np.sign(delta[:, 1:]) * np.sign(delta[:, :-1]) < 0) & big[:, 1:] & big[:, :-1]
q_df["_reversals"] = reversal.sum(axis=1)
q_df["_reg_flag"] = q_df["_reversals"] >= OSC_MIN_REVERSALS
print(f"Flagging {int(q_df['_reg_flag'].sum()):,} reaches as likely regulated (>= {OSC_MIN_REVERSALS} large reversals).")

# Use the highest-mean-flow reach in each hexagon as its representative series.
# Flags are retained rather than used as automatic exclusion rules.
q_df["_mean"] = q_df[flow_cols].mean(axis=1)
main_reach = q_df.sort_values("_mean", ascending=False).groupby("h3_cell").head(1).copy()
main_reach["feature_id"] = main_reach.index
hex_ts = main_reach.set_index("h3_cell")[flow_cols]
reach_by_cell = main_reach.set_index("h3_cell")["feature_id"]
jump_flag_by_cell = main_reach.set_index("h3_cell")["_jump_flag"]
osc_flag_by_cell = main_reach.set_index("h3_cell")["_reg_flag"]

# Baseline = median of the first day (4 frames), so one odd first snapshot cannot
# distort a reach's ratios. Exclude cells whose baseline is at or below MIN_BASELINE_CMS,
# where tiny starting flows make ratios unstable.
baseline = hex_ts.iloc[:, :BASELINE_FRAMES].median(axis=1)
eligible = baseline > MIN_BASELINE_CMS
hex_ts = hex_ts.loc[eligible].copy()
reach_by_cell = reach_by_cell.loc[eligible]
jump_flag_by_cell = jump_flag_by_cell.loc[eligible]
osc_flag_by_cell = osc_flag_by_cell.loc[eligible]
if hex_ts.empty:
    raise RuntimeError("No representative reaches remain after applying the minimum baseline threshold.")
baseline = baseline.loc[eligible]
peak_flow = hex_ts.max(axis=1)

# Large-river rule: cells on the Columbia mainstem with a baseline above LARGE_RIVER_CMS are
# treated as regulated (a chain of dams controls the river), even if the oscillation test misses them.
cell_centers = {c: h3.cell_to_latlng(c) for c in hex_ts.index}
near_columbia = pd.Series(
    {c: distance_to_columbia_deg(*cell_centers[c]) <= COLUMBIA_TOL_DEG for c in hex_ts.index}
)
mainstem_flag_by_cell = (baseline > LARGE_RIVER_CMS) & near_columbia
reg_flag_by_cell = osc_flag_by_cell | mainstem_flag_by_cell
reason_by_cell = pd.Series("", index=hex_ts.index)
reason_by_cell[osc_flag_by_cell] = "oscillation"
reason_by_cell[mainstem_flag_by_cell] = "columbia_mainstem"
reason_by_cell[osc_flag_by_cell & mainstem_flag_by_cell] = "oscillation+columbia_mainstem"

# Preserve the true per-reach ratio; only the animated display series is capped.
surge_raw = hex_ts.div(baseline, axis=0).round(3)
surge_display = surge_raw.clip(upper=SURGE_CAP).round(2)
timestamps = [t.strftime("%b %d, %H:%M UTC") for t in surge_display.columns]
print(
    f"Kept {len(hex_ts):,} hexagons; {int(reg_flag_by_cell.sum()):,} flagged as likely regulated "
    f"({int(osc_flag_by_cell.sum())} by oscillation, {int(mainstem_flag_by_cell.sum())} by the Columbia mainstem rule)."
)

# ==========================================
# 4. EXPORT GEOJSON & JS DATA FILE
# ==========================================
features = []
for cell_id, row in surge_display.iterrows():
    raw_row = surge_raw.loc[cell_id]
    boundary = h3.cell_to_boundary(cell_id)
    coords = [[round(lon, 4), round(lat, 4)] for lat, lon in boundary]
    coords.append(coords[0])  # Close polygon ring

    features.append({
        "type": "Feature",
        "geometry": {"type": "Polygon", "coordinates": [coords]},
        "properties": {
            "h3": cell_id,
            "feature_id": int(reach_by_cell.loc[cell_id]),
            "jump_flag": bool(jump_flag_by_cell.loc[cell_id]),
            "regulated_flag": bool(reg_flag_by_cell.loc[cell_id]),
            "regulated_reason": str(reason_by_cell.loc[cell_id]),
            "base_cms": round(float(baseline.loc[cell_id]), 1),
            "peak_cms": round(float(peak_flow.loc[cell_id]), 1),
            "max_surge": round(float(row.max()), 2),
            "max_surge_raw": round(float(raw_row.max()), 3),
            "surge": row.values.tolist(),
            "surge_raw": raw_row.values.tolist(),
        }
    })

geojson_out = {
    "type": "FeatureCollection",
    "metadata": {
        "model": "NOAA National Water Model v3.0 analysis_assim",
        "baseline": f"median of the first {BASELINE_FRAMES} frames ({dates[0]:%Y-%m-%d %H:%M} to {dates[BASELINE_FRAMES - 1]:%H:%M} UTC)",
        "h3_resolution": 6,
        "minimum_baseline_exclusive_cms": MIN_BASELINE_CMS,
        "display_cap": SURGE_CAP,
        "metric": "streamflow divided by baseline streamflow",
        "representative_reach": "highest mean flow in each H3 cell",
        "regulated_flag": (
            f">= {OSC_MIN_REVERSALS} up/down reversals larger than {OSC_REL:.0%} of mean flow, or "
            f"Columbia mainstem cell with baseline > {LARGE_RIVER_CMS:g} m3/s (heuristics)"
        ),
    },
    "timestamps": timestamps,
    "features": features
}
payload = json.dumps(geojson_out, separators=(",", ":"))

# Plain GeoJSON for reuse in other tools
with open("pnw_hex_surge.geojson", "w") as f:
    f.write(payload)
print(f"Saved pnw_hex_surge.geojson ({len(features)} hexagons, {len(timestamps)} frames).")

# Same data as a script that map.html loads with a <script> tag. Unlike fetch(),
# this works from a web server, GitHub Pages, and when opened from file://.
with open("pnw_hex_data.js", "w", encoding="utf-8") as f:
    f.write(f"window.HEX_DATA = {payload};\n")
print("Saved pnw_hex_data.js (loaded by map.html).")
Tracking 139,004 PNW river reaches across 12,840 hexagons.
Loaded 24 of 24 time steps.
Skipping 2,560 reaches with incomplete time series.
Flagging 4 reaches with more than 2 jumps of 10x for review.
Flagging 1,883 reaches as likely regulated (>= 4 large reversals).
Kept 1,770 hexagons; 291 flagged as likely regulated (85 by oscillation, 213 by the Columbia mainstem rule).
Saved pnw_hex_surge.geojson (1770 hexagons, 24 frames).
Saved pnw_hex_data.js (loaded by map.html).

Caveats

This map shows modeled NOAA National Water Model v3.0 analysis flows, not observations. It describes change during one event; it is not a historical anomaly, flood extent, flood probability, or flood-severity map.

• Metric and eligibility: each retained reach is divided by its median flow over the first four frames (Nov 9, 00:00–18:00 UTC). That is a reference period, not a “normal” flow, and a storm already under way on Nov 9 would raise it. Cells whose representative reach has a baseline at or below 5 m³/s are excluded, because ratios from very small flows are unstable; this removes many small streams. Color is capped at 10×, while the exported surge_raw series retains uncapped ratios.

• Low-baseline effect and height: a small stream that rises modestly can show a large ratio, so a color near 10× does not mean a large or dangerous flow. To keep small streams from dominating, the map’s default height shows the rise in modeled flow (current minus baseline, in m³/s, on a square-root scale), while color shows the ratio. The height menu can switch to the ratio or to a flat 2D view. Rise in flow naturally favors large rivers.

• Regulated reaches: rivers below dams show up-and-down swings in the model that come from operations rather than weather. Two heuristics mark reaches in gray: (1) at least four large reversals (each over 20% of mean flow) in the six-hourly series, and (2) any cell on the Columbia mainstem, approximated by a hand-drawn path, with a baseline above 1,000 m³/s. Gray hexagons should not be read as storm response. Neither rule is a confirmed list of regulated reaches, so some regulated reaches may be missed and some natural ones flagged.

• Columbia check: the Columbia downstream of Priest Rapids Dam was checked against the one USGS gauge available in that stretch (12472800, below Priest Rapids Dam). The model’s first cell below the dam tracks that gauge closely (correlation about 0.97), and both show strong daily dam-driven peaks. Cells farther downstream have no gauge in that area, so their behavior is unchecked, which is why the mainstem rule marks them as regulated.

• Representative reach: each cell shows one modeled reach (the highest-mean-flow reach assigned to that H3 cell), not all tributaries, a basin total, or conditions throughout the cell. Clicking a hexagon shows its feature_id, H3 cell, modeled flow now and at baseline, the uncapped ratio, the peak, and a small hydrograph. The flows in the popup are derived from the ratio and the peak, so they are approximate.

• Jump flags: repeated >10× step changes are flagged for review and noted in the popup. This is a heuristic, not proof of bad data.

• Approximate gauge spot-check: nearest NWM reaches and provisional USGS gauges for Nov 9–14 gave the following values. This small, approximate comparison is not an independent or basin-wide model validation:

River USGS, first → peak (m³/s) NWM, first → peak (m³/s)
Chetco near Brookings 3.8 → 85 13.5 → 386
Sixes at Sixes 2.0 → 32 3.5 → 159
South Fork Coquille at Powers 0.5 → 19 1.2 → 42

These station comparisons are approximate because they use nearest reaches and 6-hourly model snapshots. Check an observed source such as the USGS National Water Dashboard for current station conditions.

• Completeness: all 24 expected snapshots are required. If a file is missing or cannot be read, the workflow reports the missing times and stops rather than exporting a misleading equally spaced animation.

Part 2: Animated MapLibre HTML Map (map.html)

Instead of reloading geometries on every frame, the HTML page flattens each hexagon’s per-frame values into properties (s0, s1, … for the capped ratio and h0, h1, … for the square root of the rise in flow) and updates MapLibre’s fill-extrusion-color and fill-extrusion-height expressions with ["get", "s" + frameIndex] and ["get", "h" + frameIndex]. Hexagons flagged as likely regulated get a muted gray color instead.

The page has a play/pause button, a time slider, a playback-speed menu, a legend generated from the same color stops as the map, and a menu to set height to the rise in flow (default), the flow ratio, or flat 2D. A note on the map states that values are modeled, not observed, and are not a flood-severity measure. Clicking a hexagon opens a popup with the reach ID, modeled flow now and at baseline, the ratio, the peak, regulated and jump-flag warnings where relevant, and a small hydrograph. The data comes from pnw_hex_data.js, loaded with a script tag rather than fetch, so the page works on a web server, on GitHub Pages, and when opened directly from disk (it still needs an internet connection for MapLibre and the basemap).

The collapsed section below shows the current map.html from this folder, so it always matches the file on disk.

Show the map.html source
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Pacific Northwest Modeled Streamflow Change — 30DayMapChallenge</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <script src="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script>
  <link href="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css" rel="stylesheet" />
  <!-- Data is loaded with a script tag (not fetch) so the page also works from file:// -->
  <script src="pnw_hex_data.js"></script>
  <style>
    body { margin: 0; padding: 0; overflow: hidden; background: #0b0f19; font-family: system-ui, sans-serif; color: #f8fafc; }
    #map { position: absolute; top: 0; bottom: 0; width: 100%; }
    .panel {
      background: rgba(15, 23, 42, 0.88); backdrop-filter: blur(8px);
      border: 1px solid rgba(148, 163, 184, 0.2); border-radius: 10px;
    }
    .hud {
      position: absolute; bottom: 28px; left: 50%; transform: translateX(-50%);
      padding: 12px 18px; border-radius: 12px;
      display: flex; align-items: center; gap: 12px; z-index: 10; min-width: 460px;
    }
    button, select {
      background: #0ea5e9; color: #0f172a; border: none; border-radius: 6px;
      padding: 6px 12px; font-weight: 700; cursor: pointer; font-size: 0.85rem;
    }
    select { background: #1e293b; color: #e2e8f0; font-weight: 500; border: 1px solid #334155; padding: 4px 6px; }
    input[type="range"] { flex: 1; accent-color: #38bdf8; cursor: pointer; }
    #timestamp { font-variant-numeric: tabular-nums; font-size: 0.9rem; color: #cbd5e1; min-width: 140px; }

    .title-card { position: absolute; top: 20px; left: 20px; padding: 12px 16px; max-width: min(350px, calc(100% - 40px)); z-index: 10; }
    .title-card h1 { margin: 0 0 4px 0; font-size: 1rem; letter-spacing: 0.02em; }
    .title-card p { margin: 0; font-size: 0.78rem; color: #94a3b8; line-height: 1.35; }
    .title-card .note { color: #fbbf24; font-weight: 600; }
    .title-card label { font-size: 0.75rem; color: #94a3b8; }
    .legend { position: relative; margin-top: 8px; height: 10px; border-radius: 5px; }
    .ticks { position: relative; height: 16px; font-size: 0.68rem; color: #94a3b8; }
    .ticks span { position: absolute; transform: translateX(-50%); white-space: nowrap; }
    .ticks span.neutral { color: #e2e8f0; font-weight: 700; }
    .legend-tick { position: absolute; top: -2px; width: 2px; height: 14px; background: #f8fafc; }

    .maplibregl-popup { z-index: 30; }  /* above the title card (10) and controls bar (10) */
    .height-help { margin-top: 4px; color: #cbd5e1; }
    .maplibregl-popup-content { background: rgba(15, 23, 42, 0.96); color: #e2e8f0; border: 1px solid #334155; border-radius: 10px; padding: 10px 12px; font-size: 0.78rem; }
    .maplibregl-popup-anchor-top .maplibregl-popup-tip { border-bottom-color: rgba(15, 23, 42, 0.96); }
    .maplibregl-popup-anchor-bottom .maplibregl-popup-tip { border-top-color: rgba(15, 23, 42, 0.96); }
    .maplibregl-popup-anchor-left .maplibregl-popup-tip { border-right-color: rgba(15, 23, 42, 0.96); }
    .maplibregl-popup-anchor-right .maplibregl-popup-tip { border-left-color: rgba(15, 23, 42, 0.96); }
    .maplibregl-popup-close-button { color: #94a3b8; }
    .pop { min-width: 210px; }
    .pop h2 { margin: 0 0 6px 0; font-size: 0.85rem; }
    .pop table { border-collapse: collapse; width: 100%; }
    .pop td { padding: 1px 0; }
    .pop td:last-child { text-align: right; font-variant-numeric: tabular-nums; }
    .pop .muted { color: #94a3b8; font-size: 0.7rem; margin-top: 6px; line-height: 1.3; }
    .pop .warn { color: #fbbf24; font-size: 0.72rem; margin-top: 6px; }

    /* Narrow embeds (e.g. a small iframe or phone) */
    @media (max-width: 560px) {
      .hud { left: 10px; right: 10px; bottom: 10px; transform: none; min-width: 0; padding: 8px 10px; gap: 8px; border-radius: 10px; }
      button { padding: 5px 10px; }
      input[type="range"] { min-width: 0; width: 0; }
      #timestamp { min-width: 0; flex: none; font-size: 0.68rem; white-space: nowrap; }
      #speed { display: none; }
      .title-card { top: 10px; left: 10px; padding: 8px 10px; border-radius: 8px; max-width: calc(100% - 20px); }
      .title-card h1 { font-size: 0.85rem; }
      .title-card p { font-size: 0.66rem; }
      .title-card .detail { display: none; }
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <div class="title-card panel">
    <h1>Pacific Northwest Modeled Streamflow Change</h1>
    <p class="note">Modeled values, not observations. Not a measure of flood severity.</p>
    <p class="detail" style="margin-top:6px">Each hexagon shows one modeled river reach (its largest). Color = flow divided by that reach's median flow on Nov 9 (first four frames; 1x = unchanged). Click a hexagon for details.</p>
    <div id="legend" class="legend"></div>
    <div id="ticks" class="ticks"></div>
    <p style="margin-top:2px"><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:#64748b;vertical-align:-1px;margin-right:5px"></span>Gray = likely regulated (dam-influenced) reach</p>
    <p class="detail" style="margin-top:2px">
      <label for="heightMode">Height:</label>
      <select id="heightMode">
        <option value="rise" selected>Rise in flow (m³/s)</option>
        <option value="ratio">Flow ratio</option>
        <option value="flat">Flat (2D)</option>
      </select>
    </p>
    <p id="heightHelp" class="detail height-help"></p>
    <p style="margin-top:4px">Source: NOAA National Water Model v3.0 analysis</p>
  </div>
  <div class="hud panel">
    <button id="playBtn">Pause</button>
    <input id="slider" type="range" min="0" max="20" value="0" aria-label="Time step" />
    <span id="timestamp">Loading...</span>
    <select id="speed" aria-label="Playback speed">
      <option value="1200">0.5x</option>
      <option value="600" selected>1x</option>
      <option value="300">2x</option>
    </select>
  </div>

  <script>
    // Color scale: linear between stops; the legend below is generated from the same stops.
    const COLOR_STOPS = [
      [0.5, '#1e293b'],  // well below start (slate)
      [1.0, '#0284c7'],  // unchanged (blue)
      [2.5, '#06b6d4'],  // rising (cyan)
      [5.0, '#facc15'],  // large relative rise (amber)
      [10.0, '#f43f5e']  // 10x or more (coral); display is capped here
    ];
    const REGULATED_COLOR = '#64748b';  // muted gray for likely regulated reaches
    const RISE_HEIGHT_M = 1200;   // meters of extrusion per sqrt(m3/s) of rise
    const RATIO_HEIGHT_M = 6500;  // meters of extrusion per 1x of ratio above 0.8

    const lo = COLOR_STOPS[0][0], hi = COLOR_STOPS[COLOR_STOPS.length - 1][0];
    const pos = (v) => ((v - lo) / (hi - lo)) * 100;
    document.getElementById('legend').style.background =
      'linear-gradient(90deg,' + COLOR_STOPS.map(([v, c]) => c + ' ' + pos(v).toFixed(1) + '%').join(',') + ')';
    document.getElementById('legend').innerHTML = '<div class="legend-tick" style="left:' + pos(1).toFixed(1) + '%"></div>';
    document.getElementById('ticks').innerHTML = [[1, '1x'], [2.5, '2.5x'], [5, '5x'], [10, '10x+']]
      .map(([v, t]) => '<span class="' + (v === 1 ? 'neutral' : '') + '" style="left:' + pos(v).toFixed(1) + '%' +
        (v === hi ? ';transform:translateX(-100%)' : '') + '">' + t + '</span>').join('');

    const map = new maplibregl.Map({
      container: 'map',
      style: 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json',
      center: [-121.8, 45.8],
      zoom: 6.2,
      pitch: 50,
      bearing: -15
    });
    map.addControl(new maplibregl.NavigationControl({ visualizePitch: true }), 'top-right');

    let timestamps = [];
    let byId = {};
    let frame = 0;
    let playing = true;
    let timer = null;
    let selectedId = null;
    let popup = null;

    const HEIGHT_HELP = {
      rise: 'Rise in flow: column height = how many m³/s of water were added since the Nov 9 baseline (square-root scale). Favors large rivers; small streams stay short.',
      ratio: 'Flow ratio: column height = how many times higher flow is than baseline, the same quantity as color. Small streams with big relative rises look tall.',
      flat: 'Flat (2D): no extrusion. Only color shows the flow ratio, so nothing hides neighboring cells.'
    };
    function updateHeightHelp() {
      document.getElementById('heightHelp').textContent = HEIGHT_HELP[document.getElementById('heightMode').value];
    }

    function paint(idx) {
      const mode = document.getElementById('heightMode').value;
      const ratio = ['get', 's' + idx];
      let height;
      if (mode === 'rise') height = ['*', ['get', 'h' + idx], RISE_HEIGHT_M];
      else if (mode === 'ratio') height = ['*', ['max', 0, ['-', ratio, 0.8]], RATIO_HEIGHT_M];
      else height = 0;
      return {
        // Likely regulated reaches are muted so dam-driven swings don't read as storm response.
        color: ['case', ['==', ['get', 'regulated_flag'], true], REGULATED_COLOR,
          ['interpolate', ['linear'], ratio].concat(COLOR_STOPS.flat())],
        height
      };
    }

    function fmt(v, d) { return Number(v).toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d }); }

    function popupHtml(id) {
      const p = byId[id];
      if (!p) return '';
      const flow = p.surge_raw.map((r) => r * p.base_est);
      const cur = flow[frame];
      const W = 220, H = 56, n = flow.length;
      const max = Math.max.apply(null, flow) || 1;
      const x = (i) => (i / (n - 1)) * W;
      const y = (v) => H - 4 - (v / max) * (H - 8);
      const line = flow.map((v, i) => x(i).toFixed(1) + ',' + y(v).toFixed(1)).join(' ');
      const spark = '<svg width="' + W + '" height="' + H + '" viewBox="0 0 ' + W + ' ' + H + '" style="display:block;margin-top:6px">' +
        '<polyline points="' + line + '" fill="none" stroke="#38bdf8" stroke-width="1.5"/>' +
        '<line x1="' + x(frame).toFixed(1) + '" x2="' + x(frame).toFixed(1) + '" y1="0" y2="' + H + '" stroke="#f8fafc" stroke-width="1" stroke-dasharray="2 2"/>' +
        '<circle cx="' + x(frame).toFixed(1) + '" cy="' + y(cur).toFixed(1) + '" r="3" fill="#f8fafc"/></svg>';
      return '<div class="pop"><h2>' + timestamps[frame] + '</h2><table>' +
        '<tr><td>Modeled flow now</td><td>' + fmt(cur, 1) + ' m³/s</td></tr>' +
        '<tr><td>Baseline (Nov 9 median)</td><td>' + fmt(p.base_est, 1) + ' m³/s</td></tr>' +
        '<tr><td>Ratio now (uncapped)</td><td>' + fmt(p.surge_raw[frame], 2) + 'x</td></tr>' +
        '<tr><td>Peak in window</td><td>' + fmt(p.peak_cms, 1) + ' m³/s (' + fmt(p.max_surge_raw, 1) + 'x)</td></tr>' +
        '<tr><td>NWM reach ID</td><td>' + p.feature_id + '</td></tr>' +
        '<tr><td>H3 cell</td><td>' + p.h3 + '</td></tr></table>' + spark +
        (p.regulated_flag ? '<div class="warn" style="color:#94a3b8">Likely regulated: ' +
          (p.regulated_reason === 'oscillation'
            ? 'this reach swings up and down repeatedly, a pattern typical of dam operations'
            : 'this is on the dam-controlled Columbia mainstem' + (p.regulated_reason.indexOf('oscillation') >= 0 ? ' and also swings up and down repeatedly' : '')) +
          ', so its changes may not reflect storm response. This is a heuristic.</div>' : '') +
        (p.jump_flag ? '<div class="warn">Flagged: this reach shows repeated large step changes (possible regulation or model behavior). Treat with caution.</div>' : '') +
        '<div class="muted">Modeled NWM analysis for the largest reach in this hexagon, not an observation. Flow values are derived from the ratio and are approximate.</div></div>';
    }

    function setFrame(idx) {
      frame = idx;
      document.getElementById('slider').value = idx;
      document.getElementById('timestamp').textContent = timestamps[idx] || '';
      const expr = paint(idx);
      map.setPaintProperty('hex-surge', 'fill-extrusion-color', expr.color);
      map.setPaintProperty('hex-surge', 'fill-extrusion-height', expr.height);
      if (popup && selectedId) popup.setHTML(popupHtml(selectedId));
    }

    function schedule() {
      clearTimeout(timer);
      timer = setTimeout(() => {
        if (playing) setFrame((frame + 1) % timestamps.length);
        schedule();
      }, Number(document.getElementById('speed').value));
    }

    function setPlaying(on) {
      playing = on;
      document.getElementById('playBtn').textContent = on ? 'Pause' : 'Play';
    }

    map.on('load', () => {
      const data = window.HEX_DATA;
      if (!data) {
        document.getElementById('timestamp').textContent = 'Data file pnw_hex_data.js not found';
        return;
      }
      timestamps = data.timestamps;

      // MapLibre stringifies array properties, so flatten per-frame values (s = capped ratio,
      // h = sqrt of rise in flow) and keep full records in byId for the popup.
      data.features.forEach((f) => {
        const p = f.properties;
        p.base_est = p.max_surge_raw > 0 ? p.peak_cms / p.max_surge_raw : p.base_cms;
        p.surge.forEach((v, i) => { p['s' + i] = v; });
        p.surge_raw.forEach((r, i) => { p['h' + i] = Math.sqrt(Math.max(0, (r - 1) * p.base_est)); });
        byId[p.h3] = p;
      });

      const slider = document.getElementById('slider');
      slider.max = timestamps.length - 1;
      map.addSource('pnw-hex', { type: 'geojson', data });

      const init = paint(0);
      map.addLayer({
        id: 'hex-surge',
        type: 'fill-extrusion',
        source: 'pnw-hex',
        paint: {
          'fill-extrusion-color': init.color,
          'fill-extrusion-height': init.height,
          'fill-extrusion-opacity': 0.88,
          'fill-extrusion-height-transition': { duration: 250, delay: 0 },
          'fill-extrusion-color-transition': { duration: 250, delay: 0 }
        }
      });

      setFrame(0);
      schedule();

      map.on('click', 'hex-surge', (e) => {
        selectedId = e.features[0].properties.h3;
        if (popup) popup.remove();
        popup = new maplibregl.Popup({ maxWidth: '280px' }).setLngLat(e.lngLat).setHTML(popupHtml(selectedId)).addTo(map);
        popup.on('close', () => { selectedId = null; });
      });
      map.on('mouseenter', 'hex-surge', () => { map.getCanvas().style.cursor = 'pointer'; });
      map.on('mouseleave', 'hex-surge', () => { map.getCanvas().style.cursor = ''; });

      slider.addEventListener('input', (e) => { setPlaying(false); setFrame(Number(e.target.value)); });
      document.getElementById('playBtn').addEventListener('click', () => setPlaying(!playing));
      document.getElementById('speed').addEventListener('change', schedule);
      document.getElementById('heightMode').addEventListener('change', () => { updateHeightHelp(); setFrame(frame); });
      updateHeightHelp();
    });
  </script>
</body>
</html>