-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3035 lines (2813 loc) · 112 KB
/
Copy pathapp.py
File metadata and controls
3035 lines (2813 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Wai — Streamlit control panel for coastal water-level estimates.
Run:
streamlit run app.py
Tabs
----
Control Center — estimate, uncertainty, accuracy, and operational status
Overview — station summary stats and location map
Forecasts — time series with forecast overlay and conformal intervals
Model Comparison — metrics table for all pipeline models
Alerts — configurable high-water alert detection
Uncertainty — conformal prediction interval details
Benchmark Results — prototype model RMSE on tidecast data
Scientific protocol shown to users
----------------------------------
- Persistence baseline is rolling 1-step: pred[t] = observed[t-1]
(matches scripts/train_baseline.rolling_persistence_1step). The previous
constant-last-train baseline is retained only as a reference floor.
- Alert thresholds are fit on the *training* window for the selected station
(75 % temporal split). The displayed date range is for visualisation only —
the threshold never moves with the date filter.
- "Forecast" labels make the protocol explicit: 1-step forecasts use the most
recent observed value as input ("online 1-step"); longer horizons come
from the direct multi-horizon evaluation (separate model per horizon).
"""
from __future__ import annotations
import json
from html import escape
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import numpy as np
import pandas as pd
import streamlit as st
st.set_page_config(
page_title="Wai",
page_icon="🌊",
layout="wide",
initial_sidebar_state="expanded",
)
METRICS_PATH = Path("reports/model_metrics.json")
HORIZON_PATH = Path("reports/horizon_metrics.json")
BENCHMARK_PATH = Path("reports/benchmark_results.md")
SUMMARY_PATH = Path("reports/summary.json")
DEMO_DATA_PATH = Path("data/demo/demo_water_levels.csv")
PALETTE = {
"ink": "#172033",
"muted": "#64748B",
"grid": "#E2E8F0",
"surface": "#FFFFFF",
"blue": "#2563EB",
"blue_light": "rgba(37, 99, 235, 0.13)",
"gold": "#D08B18",
"gold_light": "rgba(208, 139, 24, 0.16)",
"orange": "#C45D24",
"slate": "#8B98AA",
"terrain": "#68783F",
"sand": "#B9872F",
"water": "rgba(37, 99, 235, 0.48)",
"water_range": "rgba(111, 165, 255, 0.28)",
}
MODEL_VIEW = {
"harmonic_ridge": {
"label": "Harmonic Ridge",
"prediction": "harmonic_pred",
"lower": "harmonic_lower",
"upper": "harmonic_upper",
"coverage": "harmonic_coverage",
"interval": "harmonic_ci",
"color": PALETTE["gold"],
"fill": PALETTE["gold_light"],
},
"grad_boost": {
"label": "Gradient Boost",
"prediction": "gradboost_pred",
"lower": "gradboost_lower",
"upper": "gradboost_upper",
"coverage": "gradboost_coverage",
"interval": "gradboost_ci",
"color": PALETTE["blue"],
"fill": PALETTE["blue_light"],
},
}
DASHBOARD_MODEL_LABELS = {
"persistence": "Persistence",
"persistence_constant": "Constant holdout",
"harmonic_ridge": "Harmonic Ridge",
"grad_boost": "Gradient Boost",
"wave_gru": "Fast Wave Adapter",
}
PLOTLY_CONFIG = {
"displayModeBar": False,
"displaylogo": False,
"scrollZoom": False,
"responsive": True,
}
# The original schematic used the full 0–100 horizontal span for its coastal
# slope. Compressing that profile into 0–50 makes the visible land footprint
# half as wide, then extends a shallow offshore bed through the remaining span.
SHORELINE_PROFILE_X = (0, 6, 12, 17.5, 22.5, 28, 34, 41, 50, 75, 100)
SHORELINE_DEPTH_FRACTIONS = (
0.04,
0.08,
0.14,
0.22,
0.34,
0.50,
0.68,
0.82,
0.93,
0.96,
0.98,
)
SHORELINE_TICK_VALUES = (5, 28, 78)
TIDE_FRAME_DURATION_MS = 110
TIDE_TRANSITION_MS = 45
try:
import plotly.graph_objects as go
_HAS_PLOTLY = True
except ImportError:
_HAS_PLOTLY = False
# ── Cached data loaders ───────────────────────────────────────────────────────
@st.cache_data
def load_data() -> pd.DataFrame:
from src.data.loader import load_demo_data
return load_demo_data()
@st.cache_data
def load_metrics() -> dict:
if METRICS_PATH.exists():
with open(METRICS_PATH) as f:
return json.load(f)
return {}
@st.cache_data
def load_horizon_metrics() -> dict:
if HORIZON_PATH.exists():
with open(HORIZON_PATH) as f:
return json.load(f)
return {}
@st.cache_data
def load_summary() -> dict:
if SUMMARY_PATH.exists():
with open(SUMMARY_PATH) as f:
return json.load(f)
return {}
@st.cache_data(ttl=60)
def load_evidence_status() -> dict:
"""Return a live freshness verdict instead of trusting a static report flag."""
try:
from scripts.check_report_freshness import check_report_freshness
verdict = check_report_freshness()
return {
"fresh": True,
"fingerprint": verdict["current_source_fingerprint"],
"message": "Evidence matches the current source",
}
except Exception as error:
return {
"fresh": False,
"fingerprint": None,
"message": str(error),
}
@st.cache_data(ttl=300, show_spinner=False)
def load_live_noaa_snapshot(
station,
lookback_hours: int,
datum: str,
include_tide_predictions: bool,
):
"""Fetch a five-minute cached NOAA monitor snapshot with no mock fallback."""
from src.data.noaa_live import fetch_live_noaa_snapshot
return fetch_live_noaa_snapshot(
station.station_id,
lookback_hours=lookback_hours,
datum=datum,
include_tide_predictions=include_tide_predictions,
station=station,
)
@st.cache_data(ttl=300, show_spinner=False)
def load_live_noaa_guidance(
station,
history_hours: int,
datum: str,
):
"""Fetch a five-minute cached NOAA OFS guidance window when supported."""
from src.data.noaa_live import fetch_live_noaa_operational_guidance
return fetch_live_noaa_operational_guidance(
station.station_id,
history_hours=history_hours,
forecast_hours=48,
datum=datum,
station=station,
)
@st.cache_data(ttl=6 * 60 * 60, show_spinner=False)
def load_live_noaa_station_catalog():
"""Discover all active NOAA water-level stations with a bundled fallback."""
from src.data.noaa_catalog import load_noaa_station_catalog
return load_noaa_station_catalog()
@st.cache_data
def run_forecast(station_id: str, train_frac: float = 0.75):
"""Run the dashboard's online 1-step forecast pipeline.
Returns
-------
dict with aligned timestamps, actual values, model predictions, conformal
intervals, and coverage summaries. All plotted arrays are aligned to the
same feature-valid test timestamps.
`persistence_pred` is the rolling 1-step persistence (matches
`scripts/train_baseline.rolling_persistence_1step`) sampled at the same
timestamps as the supervised models. `train_threshold` is mean + 2σ fit on
the training window only — never on the displayed date range.
"""
from src.models.baseline import HarmonicRidgeModel
from src.models.gradient_boost import GradBoostModel
from src.models.conformal import ConformalIntervals
df = load_data()
sub = df[df["station_id"] == station_id].sort_values("timestamp").reset_index(drop=True)
n = len(sub)
n_train = int(n * train_frac)
n_cal = int(n_train * 0.15) # last 15% of train for conformal calibration
train_fit = sub.iloc[:n_train - n_cal]
train_cal = sub.iloc[n_train - n_cal:n_train]
test = sub.iloc[n_train:]
# Rolling 1-step persistence (matches scripts/train_baseline.py).
# pred[0] = last value of full train; pred[t] = test[t-1] thereafter.
test_vals = test["water_level"].values
train_full = sub.iloc[:n_train]
last_train = float(train_full["water_level"].dropna().iloc[-1])
persist_pred = np.empty(len(test_vals))
if len(test_vals):
persist_pred[0] = last_train
persist_pred[1:] = test_vals[:-1]
harmonic = HarmonicRidgeModel(alpha=1.0).fit(train_fit)
harmonic_cal = harmonic.predict_aligned(train_cal)
harmonic_test = harmonic.predict_aligned(test)
gradboost = GradBoostModel().fit(train_fit)
gradboost_cal = gradboost.predict_aligned(train_cal)
gradboost_test = gradboost.predict_aligned(test)
if not harmonic_test["timestamp"].equals(gradboost_test["timestamp"]):
raise RuntimeError("HarmonicRidge and GradBoost test timestamps are not aligned")
if not harmonic_cal["timestamp"].equals(gradboost_cal["timestamp"]):
raise RuntimeError("HarmonicRidge and GradBoost calibration timestamps are not aligned")
# Conformal calibration on each model's already-aligned calibration rows.
harmonic_ci = ConformalIntervals(coverage=0.90)
harmonic_ci.calibrate(
harmonic_cal["actual"].to_numpy(dtype=float),
harmonic_cal["prediction"].to_numpy(dtype=float),
)
gb_ci = ConformalIntervals(coverage=0.90)
gb_ci.calibrate(
gradboost_cal["actual"].to_numpy(dtype=float),
gradboost_cal["prediction"].to_numpy(dtype=float),
)
# Train-window-only alert threshold.
train_wl = train_full["water_level"].dropna()
train_threshold = float(train_wl.mean() + 2.0 * train_wl.std())
rows = harmonic_test["_source_row"].to_numpy(dtype=int)
timestamps = harmonic_test["timestamp"].reset_index(drop=True)
actual = harmonic_test["actual"].to_numpy(dtype=float)
harmonic_pred = harmonic_test["prediction"].to_numpy(dtype=float)
gradboost_pred = gradboost_test["prediction"].to_numpy(dtype=float)
persist_aligned = persist_pred[rows]
h_lo, h_hi = harmonic_ci.intervals(harmonic_pred)
gb_lo, gb_hi = gb_ci.intervals(gradboost_pred)
return {
"train_fit": train_fit,
"train_cal": train_cal,
"test": test,
"timestamps": timestamps,
"actual": actual,
"persistence_pred": persist_aligned,
"harmonic_pred": harmonic_pred,
"gradboost_pred": gradboost_pred,
"harmonic_lower": h_lo,
"harmonic_upper": h_hi,
"gradboost_lower": gb_lo,
"gradboost_upper": gb_hi,
"harmonic_ci": harmonic_ci,
"gradboost_ci": gb_ci,
"harmonic_coverage": harmonic_ci.stratified_coverage(
actual, harmonic_pred, event_threshold=train_threshold,
),
"gradboost_coverage": gb_ci.stratified_coverage(
actual, gradboost_pred, event_threshold=train_threshold,
),
"train_threshold": train_threshold,
}
def build_estimate_frame(forecast: dict, model_key: str) -> pd.DataFrame:
"""Return one aligned, chart-ready estimate table for the control panel."""
if model_key not in MODEL_VIEW:
raise ValueError(f"Unsupported dashboard model: {model_key}")
spec = MODEL_VIEW[model_key]
frame = pd.DataFrame({
"timestamp": pd.to_datetime(forecast["timestamps"], utc=True),
"actual": np.asarray(forecast["actual"], dtype=float),
"estimate": np.asarray(forecast[spec["prediction"]], dtype=float),
"lower": np.asarray(forecast[spec["lower"]], dtype=float),
"upper": np.asarray(forecast[spec["upper"]], dtype=float),
"persistence": np.asarray(forecast["persistence_pred"], dtype=float),
})
frame["error"] = frame["estimate"] - frame["actual"]
frame["absolute_error"] = frame["error"].abs()
frame["inside_interval"] = frame["actual"].between(frame["lower"], frame["upper"])
# Six hours at the demo's six-minute cadence. min_periods keeps the leading
# edge honest instead of silently dropping it.
frame["rolling_mae_6h"] = frame["absolute_error"].rolling(
60, min_periods=1
).mean()
return frame
def summarize_estimates(forecast: dict, model_key: str) -> dict:
"""Compute held-out accuracy and the latest replay estimate."""
frame = build_estimate_frame(forecast, model_key)
spec = MODEL_VIEW[model_key]
persistence_mae = float(np.mean(np.abs(frame["persistence"] - frame["actual"])))
mae = float(frame["absolute_error"].mean())
rmse = float(np.sqrt(np.mean(np.square(frame["error"]))))
coverage = float(frame["inside_interval"].mean())
latest = frame.iloc[-1]
return {
"model_label": spec["label"],
"n_samples": int(len(frame)),
"mae": mae,
"rmse": rmse,
"persistence_mae": persistence_mae,
"skill_vs_persistence": (
(persistence_mae - mae) / persistence_mae
if persistence_mae > 0
else float("nan")
),
"coverage": coverage,
"interval_half_width": float(forecast[spec["interval"]].qhat),
"latest_timestamp": latest["timestamp"],
"latest_actual": float(latest["actual"]),
"latest_estimate": float(latest["estimate"]),
"latest_lower": float(latest["lower"]),
"latest_upper": float(latest["upper"]),
"latest_absolute_error": float(latest["absolute_error"]),
}
def window_estimates(frame: pd.DataFrame, hours: int | None) -> pd.DataFrame:
"""Apply a recent-window filter without changing any fitted metric."""
if hours is None or frame.empty:
return frame.copy()
cutoff = frame["timestamp"].max() - pd.Timedelta(hours=hours)
return frame.loc[frame["timestamp"] >= cutoff].copy()
def model_accuracy_frame(metrics: dict, station_id: str) -> pd.DataFrame:
"""Shape model metrics for a lower-is-better ranked comparison."""
rows = []
for model_key, values in metrics.get(station_id, {}).items():
if not isinstance(values, dict) or "mae" not in values:
continue
rows.append({
"model_key": model_key,
"model": DASHBOARD_MODEL_LABELS.get(
model_key, model_key.replace("_", " ").title()
),
"mae": float(values["mae"]),
"rmse": float(values["rmse"]),
"r2": float(values["r2"]),
})
if not rows:
return pd.DataFrame(columns=["model_key", "model", "mae", "rmse", "r2"])
return pd.DataFrame(rows).sort_values("mae", ascending=True).reset_index(drop=True)
def horizon_accuracy_frame(horizon_metrics: dict, station_id: str) -> pd.DataFrame:
"""Shape the four discrete forecast horizons for grouped RMSE bars."""
horizon_order = {"1step_6min": 0, "6h": 1, "12h": 2, "24h": 3}
rows = []
for horizon, models in horizon_metrics.get(station_id, {}).items():
if horizon.startswith("_") or not isinstance(models, dict):
continue
for model_key, values in models.items():
if model_key.startswith("_") or not isinstance(values, dict) or "rmse" not in values:
continue
rows.append({
"horizon": horizon,
"horizon_order": horizon_order.get(horizon, 99),
"model_key": model_key,
"model": DASHBOARD_MODEL_LABELS.get(
model_key, model_key.replace("_", " ").title()
),
"rmse": float(values["rmse"]),
"mae": float(values["mae"]),
})
if not rows:
return pd.DataFrame(
columns=["horizon", "horizon_order", "model_key", "model", "rmse", "mae"]
)
return pd.DataFrame(rows).sort_values(
["horizon_order", "model"]
).reset_index(drop=True)
@st.cache_data(show_spinner=False, max_entries=16)
def build_tide_motion_figure(
frame: pd.DataFrame,
*,
model_key: str,
alert_threshold: float,
max_frames: int = 72,
):
"""Build an animated shoreline cross-section linked to the estimate series.
The shoreline profile is deliberately schematic. Its vertical axis shares
the model's water-level datum so the moving surface, uncertainty band, and
reference levels remain quantitatively meaningful.
"""
if not _HAS_PLOTLY:
raise RuntimeError("Plotly is required for the tide-motion explorer")
if model_key not in MODEL_VIEW:
raise ValueError(f"Unsupported dashboard model: {model_key}")
if max_frames < 1:
raise ValueError("max_frames must be at least 1")
if not np.isfinite(alert_threshold):
raise ValueError("alert_threshold must be finite")
required = ["timestamp", "actual", "estimate", "lower", "upper"]
missing = [column for column in required if column not in frame]
if missing:
raise ValueError(f"Tide-motion frame is missing columns: {missing}")
work = frame[required].copy()
work["timestamp"] = pd.to_datetime(work["timestamp"], utc=True)
for column in required[1:]:
work[column] = pd.to_numeric(work[column], errors="coerce")
work = work.dropna().sort_values("timestamp").reset_index(drop=True)
if work.empty:
raise ValueError("Tide-motion frame has no complete observations")
from plotly.subplots import make_subplots
spec = MODEL_VIEW[model_key]
frame_count = min(max_frames, len(work))
sample_indices = np.unique(
np.linspace(0, len(work) - 1, frame_count, dtype=int)
)
time_hours = (
(work["timestamp"] - work["timestamp"].iloc[0])
.dt.total_seconds()
.to_numpy(dtype=float)
/ 3600
)
if len(work) > 1:
raw_rate = np.gradient(work["estimate"].to_numpy(dtype=float), time_hours)
work["rate_cm_hour"] = (
pd.Series(raw_rate).rolling(5, center=True, min_periods=1).mean() * 100
)
else:
work["rate_cm_hour"] = 0.0
all_levels = np.concatenate([
work["lower"].to_numpy(dtype=float),
work["upper"].to_numpy(dtype=float),
work["actual"].to_numpy(dtype=float),
np.array([float(alert_threshold)]),
])
data_min = float(np.min(all_levels))
data_max = float(np.max(all_levels))
level_span = max(data_max - data_min, 0.5)
scene_min = data_min - 0.22 * level_span
scene_max = data_max + 0.18 * level_span
scene_span = scene_max - scene_min
status_y = scene_max + 0.10 * scene_span
display_scene_max = scene_max + 0.20 * scene_span
series_min = scene_min
series_max = scene_max
terrain_x = np.array(SHORELINE_PROFILE_X, dtype=float)
terrain_y = scene_max - scene_span * np.array(
SHORELINE_DEPTH_FRACTIONS, dtype=float
)
high_reference = float(work["actual"].quantile(0.90))
low_reference = float(work["actual"].quantile(0.10))
def shore_position(level: float) -> float:
"""Interpolate where the schematic terrain crosses a water level."""
if level >= terrain_y[0]:
return float(terrain_x[0])
if level <= terrain_y[-1]:
return float(terrain_x[-1])
crossing = int(np.flatnonzero(terrain_y <= level)[0])
left = crossing - 1
fraction = (terrain_y[left] - level) / (
terrain_y[left] - terrain_y[crossing]
)
return float(
terrain_x[left] + fraction * (terrain_x[crossing] - terrain_x[left])
)
def water_polygon(level: float) -> tuple[list[float], list[float]]:
return [0.0, 100.0, 100.0, 0.0], [level, level, scene_min, scene_min]
def range_polygon(lower: float, upper: float) -> tuple[list[float], list[float]]:
return [0.0, 100.0, 100.0, 0.0], [upper, upper, lower, lower]
def phase_label(rate: float) -> str:
if rate > 0.2:
return "RISING"
if rate < -0.2:
return "FALLING"
return "NEAR SLACK"
def status_text(row: pd.Series) -> str:
headroom = float(alert_threshold - row["estimate"])
return (
f"<b>{row['timestamp']:%b %d %H:%M} UTC · "
f"{phase_label(float(row['rate_cm_hour']))} "
f"{float(row['rate_cm_hour']):+.1f} cm/h</b><br>"
f"Est {float(row['estimate']):.3f} · "
f"Obs {float(row['actual']):.3f} · "
f"90% {float(row['lower']):.3f}–{float(row['upper']):.3f} m · "
f"Error {abs(float(row['estimate'] - row['actual'])):.3f} · "
f"headroom {headroom:+.3f} m"
)
first = work.iloc[int(sample_indices[0])]
first_water_x, first_water_y = water_polygon(float(first["estimate"]))
first_range_x, first_range_y = range_polygon(
float(first["lower"]), float(first["upper"])
)
first_shore = shore_position(float(first["estimate"]))
fig = make_subplots(
rows=2,
cols=1,
row_heights=[0.53, 0.47],
vertical_spacing=0.18,
subplot_titles=(
"Animated shoreline cross-section",
"History: observed solid · estimate dashed · 90% band",
),
)
fig.add_trace(go.Scatter(
x=first_water_x,
y=first_water_y,
mode="lines",
fill="toself",
fillcolor=PALETTE["water"],
line=dict(color="rgba(37, 99, 235, 0)"),
hoverinfo="skip",
showlegend=False,
name="Estimated water volume",
), row=1, col=1)
fig.add_trace(go.Scatter(
x=first_range_x,
y=first_range_y,
mode="lines",
fill="toself",
fillcolor=PALETTE["water_range"],
line=dict(color="rgba(111, 165, 255, 0)"),
hoverinfo="skip",
showlegend=False,
name="Moving 90% range",
), row=1, col=1)
fig.add_trace(go.Scatter(
x=np.concatenate([terrain_x, [100, 0]]),
y=np.concatenate([terrain_y, [scene_min, scene_min]]),
mode="lines",
fill="toself",
fillcolor=PALETTE["terrain"],
line=dict(color=PALETTE["terrain"], width=1),
hoverinfo="skip",
showlegend=False,
name="Schematic terrain",
), row=1, col=1)
fig.add_trace(go.Scatter(
x=terrain_x,
y=terrain_y,
mode="lines",
line=dict(color=PALETTE["sand"], width=3),
hoverinfo="skip",
showlegend=False,
name="Schematic shoreline",
), row=1, col=1)
fig.add_trace(go.Scatter(
x=[first_shore, 100],
y=[float(first["estimate"]), float(first["estimate"])],
mode="lines",
line=dict(color=PALETTE["blue"], width=3),
hovertemplate="Estimated surface %{y:.3f} m<extra></extra>",
showlegend=False,
name="Estimated surface",
), row=1, col=1)
fig.add_trace(go.Scatter(
x=[58, 100],
y=[high_reference, high_reference],
mode="lines+text",
text=[None, "display high (90th pct.)"],
textposition="top left",
textfont=dict(color=PALETTE["muted"], size=11),
line=dict(color=PALETTE["muted"], width=1, dash="dot"),
hovertemplate=f"90th percentile {high_reference:.3f} m<extra></extra>",
showlegend=False,
name="Display high reference",
), row=1, col=1)
fig.add_trace(go.Scatter(
x=[58, 100],
y=[low_reference, low_reference],
mode="lines+text",
text=[None, "display low (10th pct.)"],
textposition="bottom left",
textfont=dict(color=PALETTE["muted"], size=11),
line=dict(color=PALETTE["muted"], width=1, dash="dot"),
hovertemplate=f"10th percentile {low_reference:.3f} m<extra></extra>",
showlegend=False,
name="Display low reference",
), row=1, col=1)
fig.add_trace(go.Scatter(
x=[58, 100],
y=[alert_threshold, alert_threshold],
mode="lines+text",
text=[None, "training alert threshold"],
textposition="top left",
textfont=dict(color=PALETTE["orange"], size=11),
line=dict(color=PALETTE["orange"], width=1.5, dash="dash"),
hovertemplate=f"Training threshold {alert_threshold:.3f} m<extra></extra>",
showlegend=False,
name="Training alert threshold",
), row=1, col=1)
fig.add_trace(go.Scatter(
x=[2],
y=[status_y],
mode="text",
text=[status_text(first)],
textposition="middle right",
textfont=dict(color=PALETTE["ink"], size=10),
hoverinfo="skip",
showlegend=False,
name="Current state",
), row=1, col=1)
interval_x = pd.concat([work["timestamp"], work["timestamp"][::-1]])
interval_y = pd.concat([work["upper"], work["lower"][::-1]])
fig.add_trace(go.Scatter(
x=interval_x,
y=interval_y,
fill="toself",
fillcolor=spec["fill"],
line=dict(color="rgba(255,255,255,0)"),
name="90% interval",
hoverinfo="skip",
showlegend=False,
), row=2, col=1)
fig.add_trace(go.Scatter(
x=work["timestamp"],
y=work["actual"],
name="Observed outcome",
line=dict(color=PALETTE["ink"], width=1.6),
hovertemplate="%{x|%b %d %H:%M}<br>Observed %{y:.3f} m<extra></extra>",
showlegend=False,
), row=2, col=1)
fig.add_trace(go.Scatter(
x=work["timestamp"],
y=work["estimate"],
name=f"{spec['label']} estimate",
line=dict(color=spec["color"], width=2, dash="dash"),
hovertemplate="%{x|%b %d %H:%M}<br>Estimate %{y:.3f} m<extra></extra>",
showlegend=False,
), row=2, col=1)
fig.add_trace(go.Scatter(
x=[first["timestamp"], first["timestamp"]],
y=[series_min, series_max],
mode="lines",
line=dict(color=PALETTE["orange"], width=1.5),
hoverinfo="skip",
showlegend=False,
name="Selected time",
), row=2, col=1)
fig.add_trace(go.Scatter(
x=[first["timestamp"]],
y=[first["actual"]],
mode="markers",
marker=dict(color=PALETTE["ink"], size=9, line=dict(color="#FFFFFF", width=2)),
hovertemplate="Observed %{y:.3f} m<extra></extra>",
showlegend=False,
name="Selected observed",
), row=2, col=1)
fig.add_trace(go.Scatter(
x=[first["timestamp"]],
y=[first["estimate"]],
mode="markers",
marker=dict(color=spec["color"], size=9, line=dict(color="#FFFFFF", width=2)),
hovertemplate="Estimate %{y:.3f} m<extra></extra>",
showlegend=False,
name="Selected estimate",
), row=2, col=1)
animation_frames = []
slider_steps = []
for sequence, work_index in enumerate(sample_indices):
row = work.iloc[int(work_index)]
estimate = float(row["estimate"])
water_x, water_y = water_polygon(estimate)
range_x, range_y = range_polygon(float(row["lower"]), float(row["upper"]))
shore = shore_position(estimate)
frame_name = f"tide-{sequence:03d}"
animation_frames.append(go.Frame(
name=frame_name,
traces=[0, 1, 4, 8, 12, 13, 14],
data=[
go.Scatter(x=water_x, y=water_y),
go.Scatter(x=range_x, y=range_y),
go.Scatter(x=[shore, 100], y=[estimate, estimate]),
go.Scatter(
x=[2],
y=[status_y],
text=[status_text(row)],
),
go.Scatter(
x=[row["timestamp"], row["timestamp"]],
y=[series_min, series_max],
),
go.Scatter(x=[row["timestamp"]], y=[row["actual"]]),
go.Scatter(x=[row["timestamp"]], y=[row["estimate"]]),
],
))
slider_steps.append({
"args": [
[frame_name],
{
"frame": {"duration": 0, "redraw": False},
"mode": "immediate",
"transition": {"duration": 0},
},
],
"label": f"{row['timestamp']:%b %d %H:%M}",
"method": "animate",
})
fig.frames = animation_frames
style_figure(
fig,
title="Tide motion explorer",
subtitle=(
f"{len(work):,} six-minute samples · "
f"{len(animation_frames)} motion states · model datum"
),
height=760,
)
fig.update_layout(
margin=dict(t=94, r=24, b=112, l=62),
showlegend=False,
updatemenus=[{
"buttons": [
{
"args": [
None,
{
"frame": {
"duration": TIDE_FRAME_DURATION_MS,
"redraw": False,
},
"fromcurrent": True,
"mode": "immediate",
"transition": {"duration": TIDE_TRANSITION_MS},
},
],
"label": "▶ Play",
"method": "animate",
},
{
"args": [
[None],
{
"frame": {"duration": 0, "redraw": False},
"mode": "immediate",
"transition": {"duration": 0},
},
],
"label": "Ⅱ Pause",
"method": "animate",
},
],
"direction": "left",
"pad": {"r": 10, "t": 48},
"showactive": False,
"type": "buttons",
"x": 0,
"xanchor": "left",
"y": -0.08,
"yanchor": "top",
}],
sliders=[{
"active": 0,
"currentvalue": {
"font": {"color": PALETTE["ink"], "size": 12},
"prefix": "Selected: ",
"visible": True,
"xanchor": "left",
},
"font": {"color": PALETTE["muted"], "size": 10},
"len": 0.82,
"pad": {"b": 0, "t": 48},
"steps": slider_steps,
"x": 0.18,
"xanchor": "left",
"y": -0.08,
"yanchor": "top",
}],
)
fig.update_xaxes(
row=1,
col=1,
range=[0, 100],
tickmode="array",
tickvals=list(SHORELINE_TICK_VALUES),
ticktext=["Land", "Shore", "Offshore"],
title_text=None,
fixedrange=True,
)
fig.update_yaxes(
row=1,
col=1,
range=[scene_min, display_scene_max],
title_text="Water level (m, model datum)",
fixedrange=True,
)
fig.update_xaxes(row=2, col=1, title_text="Held-out time (UTC)")
fig.update_yaxes(
row=2,
col=1,
range=[series_min, series_max],
title_text="Water level (m)",
fixedrange=True,
)
for annotation in fig.layout.annotations:
annotation.font = dict(color=PALETTE["ink"], size=12)
return fig
@st.cache_data(show_spinner=False, max_entries=16)
def build_live_noaa_tide_figure(
frame: pd.DataFrame,
*,
datum: str,
max_frames: int = 24,
):
"""Animate the measured NOAA level against its astronomical tide prediction."""
if not _HAS_PLOTLY:
raise RuntimeError("Plotly is required for the NOAA tide-motion explorer")
required = ["timestamp", "observed_m", "predicted_m"]
missing = [column for column in required if column not in frame]
if missing:
raise ValueError(f"Live tide frame is missing columns: {missing}")
work = frame[required].copy()
work["timestamp"] = pd.to_datetime(work["timestamp"], utc=True)
work["observed_m"] = pd.to_numeric(work["observed_m"], errors="coerce")
work["predicted_m"] = pd.to_numeric(work["predicted_m"], errors="coerce")
work = work.dropna().sort_values("timestamp").reset_index(drop=True)
if work.empty:
raise ValueError("Live tide frame has no aligned NOAA samples")
from plotly.subplots import make_subplots
frame_count = min(max_frames, len(work))
sample_indices = np.unique(np.linspace(0, len(work) - 1, frame_count, dtype=int))
hours = (
(work["timestamp"] - work["timestamp"].iloc[0])
.dt.total_seconds()
.to_numpy(dtype=float)
/ 3600
)
if len(work) > 1:
rate = np.gradient(work["observed_m"].to_numpy(dtype=float), hours)
work["rate_cm_hour"] = (
pd.Series(rate).rolling(5, center=True, min_periods=1).mean() * 100
)
else:
work["rate_cm_hour"] = 0.0
work["residual_m"] = work["observed_m"] - work["predicted_m"]
all_levels = np.concatenate([
work["observed_m"].to_numpy(dtype=float),
work["predicted_m"].to_numpy(dtype=float),
])
data_min = float(np.min(all_levels))
data_max = float(np.max(all_levels))
level_span = max(data_max - data_min, 0.5)
scene_min = data_min - 0.22 * level_span
scene_max = data_max + 0.18 * level_span
scene_span = scene_max - scene_min
status_y = scene_max + 0.10 * scene_span
display_scene_max = scene_max + 0.20 * scene_span
terrain_x = np.array(SHORELINE_PROFILE_X, dtype=float)
terrain_y = scene_max - scene_span * np.array(
SHORELINE_DEPTH_FRACTIONS, dtype=float
)
high_reference = float(work["observed_m"].quantile(0.90))
low_reference = float(work["observed_m"].quantile(0.10))
def shore_position(level: float) -> float:
if level >= terrain_y[0]:
return float(terrain_x[0])
if level <= terrain_y[-1]:
return float(terrain_x[-1])
crossing = int(np.flatnonzero(terrain_y <= level)[0])
left = crossing - 1
fraction = (terrain_y[left] - level) / (
terrain_y[left] - terrain_y[crossing]
)
return float(
terrain_x[left] + fraction * (terrain_x[crossing] - terrain_x[left])
)
def water_polygon(level: float) -> tuple[list[float], list[float]]:
return [0.0, 100.0, 100.0, 0.0], [level, level, scene_min, scene_min]
def phase_label(rate: float) -> str:
if rate > 0.2:
return "RISING"
if rate < -0.2:
return "FALLING"
return "NEAR SLACK"
def status_text(row: pd.Series) -> str:
residual = float(row["residual_m"])
return (
f"<b>{row['timestamp']:%b %d %H:%M} UTC · "
f"{phase_label(float(row['rate_cm_hour']))} "
f"{float(row['rate_cm_hour']):+.1f} cm/h</b><br>"
f"Obs {float(row['observed_m']):.3f} · "
f"Tide {float(row['predicted_m']):.3f} · "
f"Residual {residual:+.3f} m · {datum}"
)
first = work.iloc[int(sample_indices[0])]
water_x, water_y = water_polygon(float(first["observed_m"]))
first_shore = shore_position(float(first["observed_m"]))
fig = make_subplots(
rows=2,