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).")