forked from DavidBraun777/WeatherForge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·3987 lines (3507 loc) · 174 KB
/
Copy pathapp.py
File metadata and controls
executable file
·3987 lines (3507 loc) · 174 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
# ═══════════════════════════════════════════════════════════════════════════════
# IMPORTS
# Standard library → third-party packages → local geo utility helpers.
# All imports are at the top level; nothing is imported inside functions.
# ═══════════════════════════════════════════════════════════════════════════════
import json
import logging
import re
from datetime import datetime, timedelta, timezone
from pathlib import Path
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import requests
from shiny import App, reactive, render, ui
from shinywidgets import output_widget, render_widget
from geo_utils import (
get_begin_date_column,
get_damage_crops_column,
get_damage_property_column,
get_deaths_column,
get_event_id_column,
get_event_type_column,
get_geo_fips_column,
get_geo_group_column,
get_injuries_column,
get_max_temperature_column,
get_precipitation_column,
get_snow_depth_column,
get_snowfall_column,
get_wind_speed_column,
normalize_dataframe_columns,
resolve_column,
to_county_fips,
filter_summary_for_storms,
)
logger = logging.getLogger(__name__)
if not logging.getLogger().handlers:
logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(name)s:%(message)s")
# ═══════════════════════════════════════════════════════════════════════════════
# STYLING & BRAND CONFIGURATION
# Plotly theme defaults, brand color palette, and shared axis/font styles
# applied consistently across every chart in the dashboard.
#
# To change the visual identity of all charts at once, edit BRAND_PALETTE,
# _CHART_FONT, or _AXIS_STYLE here — do not hardcode colors in chart builders.
# ═══════════════════════════════════════════════════════════════════════════════
px.defaults.template = "plotly_white"
# ═══════════════════════════════════════════════════════════════════════════════
# STATE CONFIGURATION
# This final submission is Minnesota-focused. These values are isolated to make
# future state adaptation easier, but a real state change also requires swapping
# the bundled data, county boundaries, and population inputs.
# state_name – full state name used in UI text
# state_abbr – two-letter abbreviation used in the NWS alerts API
# state_fips_prefix – two-digit state FIPS code used to normalise county FIPS
# ═══════════════════════════════════════════════════════════════════════════════
STATE_CONFIG: dict[str, str] = {
"state_name": "Minnesota",
"state_abbr": "MN",
"state_fips_prefix": "27",
}
# ── Brand palette applied consistently across all charts ──────────────────────
BRAND_PALETTE = [
"#0d6efd", # Blue (primary)
"#e63946", # Red
"#2a9d8f", # Teal
"#f4a261", # Orange
"#7b2d8b", # Purple
"#06d6a0", # Mint
"#ef476f", # Rose
"#118ab2", # Sky
]
px.defaults.color_discrete_sequence = BRAND_PALETTE
_CHART_FONT = {"family": "system-ui, -apple-system, 'Segoe UI', sans-serif", "color": "#212529"}
_AXIS_STYLE = {"gridcolor": "#f0f0f2", "linecolor": "#e9ecef", "tickfont": {"color": "#6c757d", "size": 11}}
# ═══════════════════════════════════════════════════════════════════════════════
# APP-LEVEL CONSTANTS & METRIC DEFINITIONS
#
# FILE PATHS
# DATA_DIR – local data directory under the app root
# COUNTY_GEOJSON_PATH – local GeoJSON cache; fetched from Plotly CDN if absent
#
# SENTINEL VALUES
# ALL_HAZARDS – the "no filter" option label used in every dropdown
# HAZARD_DISPLAY_COLUMN – synthetic column name added to both DataFrames
#
# METRIC DICTIONARIES (used to populate UI dropdowns)
# COUNTY_METRIC_CHOICES – metrics available on the County Impacts map
# SPATIAL_METRIC_CHOICES – metrics available on the Weather Context map
# ANIMATION_METRIC_CHOICES – metrics available on the Time Progression map
# METRIC_META – label, colorscale, and number-format per metric key
#
# TREND / CORRELATION TUNING
# TREND_LOOKBACK_FRAMES – how many recent frames the slope classifier uses
# TREND_MIN_FRAMES – minimum frames required before classifying a trend
# TREND_SLOPE_THRESHOLD – normalized slope boundary: > +X → Increasing, < -X → Decreasing
# CORRELATION_MIN_POINTS – minimum county-period pairs required for a Pearson r value
# ═══════════════════════════════════════════════════════════════════════════════
DATA_DIR = Path(__file__).resolve().parent / "data"
COUNTY_GEOJSON_PATH = DATA_DIR / "mn_counties.geojson" # swap this file when redeploying for a new state
ALL_HAZARDS = "All hazards"
HAZARD_DISPLAY_COLUMN = "__hazard_display"
COUNTY_SCOPE_NOTE = f'County-compatible {STATE_CONFIG["state_name"]} county FIPS only'
STATEWIDE_SCOPE_NOTE = "All filtered statewide records"
TREND_LOOKBACK_FRAMES = 15
TREND_MIN_FRAMES = 8
TREND_SLOPE_THRESHOLD = 0.03
CORRELATION_MIN_POINTS = 24
COUNTY_METRIC_CHOICES = {
"risk_score": "Risk Score (0–100)",
"event_count": "Storm Event",
"property_damage": "Property Damage",
"crop_damage": "Crop Damage",
"total_damage": "Total Damage",
"injuries_direct": "Direct Injuries",
"deaths_direct": "Direct Deaths",
}
SPATIAL_METRIC_CHOICES = {
"event_count": "Storm Event",
"avg_precip": "Precipitation",
"avg_snow": "Snowfall",
"avg_wind": "Wind Speed",
"avg_tmax": "Max Temperature",
"avg_tmin": "Min Temperature",
}
ANIMATION_METRIC_CHOICES = {
"event_count": "Storm Event",
"risk_score": "Risk Score (0–100)",
"property_damage": "Property Damage",
"injuries_direct": "Direct Injuries",
}
METRIC_META = {
"risk_score": {"label": "Risk Score (0–100)", "colorscale": "Reds", "format": "score"},
"event_count": {"label": "Storm Event", "colorscale": "OrRd", "format": "count"},
"property_damage": {"label": "Property Damage ($)", "colorscale": "Reds", "format": "currency"},
"injuries_direct": {"label": "Direct Injuries", "colorscale": "Magma", "format": "count"},
"deaths_direct": {"label": "Direct Deaths", "colorscale": "Purples", "format": "count"},
"avg_precip": {"label": "Precipitation (mm)", "colorscale": "Blues", "format": "float1"},
"avg_tmax": {"label": "Max Temp (°C)", "colorscale": "YlOrRd", "format": "float1"},
"avg_tmin": {"label": "Min Temp (°C)", "colorscale": "Blues_r", "format": "float1"},
"avg_wind": {"label": "Wind Speed (m/s)", "colorscale": "Viridis", "format": "float2"},
"avg_snow": {"label": "Snowfall (mm)", "colorscale": "PuBu", "format": "float1"},
"crop_damage": {"label": "Crop Damage", "colorscale": "YlOrBr", "format": "currency"},
"total_damage": {"label": "Total Damage", "colorscale": "Reds", "format": "currency"},
}
# Single-hue blue gradient used for all county choropleth maps.
# Anchored to the site's brand blue (#0d6efd) so the map reads as part of
# the same visual language as the cards, tabs, and accent lines.
COUNTY_MAP_COLORSCALE = [
[0.0, "#e8f2ff"], # near-white blue (low values)
[0.3, "#93c5fd"], # light blue
[0.6, "#3b82f6"], # medium blue
[1.0, "#0d6efd"], # brand blue (high values)
]
# ── Risk Score formula ─────────────────────────────────────────────────────────
# Single source of truth used by aggregate_county_metrics, build_animation_dataset,
# and the KPI box. Change weights here and all 3 sites update automatically.
#
# events × 2 frequency signal
# sqrt(damage/$1M) × 30 financial impact — sqrt-scaled so one catastrophic
# event doesn't erase all other signals
# e.g. $10M → 95 pts, $1B → 949 pts
# injuries × 8 human cost
# deaths × 80 10× injury weight — fatalities are the worst outcome
#
# After compute_risk_score() the pipeline in aggregate_county_metrics applies:
# ÷ years_in_window → annualized (comparable across time filters)
# ÷ avg_population×10k → per 10,000 residents (comparable across counties)
# ÷ dynamic_ceiling×100 → 0–100 scale (ceiling = 99th pct of current window)
#
# KPI thresholds (0–100 scale, annualized statewide):
# Green < 25 → calm / below-average
# Yellow < 60 → active / above-average
# Red >= 60 → severe
# ──────────────────────────────────────────────────────────────────────────────
RISK_SCORE_THRESHOLDS = (25, 60) # (green→yellow, yellow→red) on 0–100 scale
def compute_risk_score(event_count, total_damage_dollars, injuries, deaths):
"""Composite risk score. Vectorised-safe: accepts scalars or pandas Series.
Raw output is then annualized, per-capita normalized, and scaled 0–100
by the calling aggregation function — do not compare raw values directly.
At a "bad but not catastrophic" county-year (50 events, $50M, 10 injuries, 1 death):
events 100 | damage 212 | injuries 80 | deaths 80 → total 472 pts
"""
damage_m = total_damage_dollars / 1_000_000
sqrt_damage = np.sqrt(np.maximum(damage_m, 0))
return (
event_count * 2
+ sqrt_damage * 30
+ injuries * 8
+ deaths * 80
)
# ── Census populations by county FIPS, loaded from county_populations.csv ────
# Columns: fips, 1950, 1960, 1970, 1980, 1990, 2000, 2010, 2020
# Swap this file when redeploying for a new state (or use a national file).
# Source: U.S. Census Bureau decennial census, 8 anchor years per county.
# Values are interpolated/extrapolated by get_county_population() for any year.
# Used to normalise the risk score to per-10,000-residents so that high-
# population counties don't automatically dominate the rankings.
# ──────────────────────────────────────────────────────────────────────────────
_POPULATION_FILE = DATA_DIR / "county_populations.csv"
def _load_county_populations() -> dict[str, dict[int, int]]:
"""Load county populations from CSV into the same dict structure the
interpolation logic expects: {fips_str: {year_int: population_int}}.
Only rows whose FIPS code starts with STATE_CONFIG["state_fips_prefix"]
are loaded, so a single national CSV works for any state deployment.
"""
if not _POPULATION_FILE.exists():
logger.warning("county_populations.csv not found — per-capita risk scores will use neutral denominator.")
return {}
import csv as _csv
prefix = STATE_CONFIG["state_fips_prefix"]
populations: dict[str, dict[int, int]] = {}
with open(_POPULATION_FILE, newline="") as f:
reader = _csv.DictReader(f)
for row in reader:
fips = str(row["fips"]).zfill(5)
if not fips.startswith(prefix):
continue
populations[fips] = {
int(yr): int(row[yr])
for yr in reader.fieldnames
if yr != "fips" and row[yr] not in ("", None)
}
return populations
COUNTY_POPULATIONS: dict[str, dict[int, int]] = _load_county_populations()
_CENSUS_YEARS = sorted({yr for d in COUNTY_POPULATIONS.values() for yr in d})
def get_county_population(fips: str, year: int) -> float:
"""Return an estimated population for a county in a given year.
Strategy:
• Exact census year → return as-is
• Between 1990–2020 → linear interpolation between surrounding decades
• Before 1990 → linear extrapolation using the 1990→2000 slope
• After 2020 → linear extrapolation using the 2010→2020 slope
• Unknown FIPS → return 10,000 (neutral denominator, no distortion)
"""
data = COUNTY_POPULATIONS.get(str(fips).zfill(5))
if data is None:
return 10_000.0
if year in data:
return float(data[year])
years = sorted(data.keys())
# Extrapolate before first census year
if year < years[0]:
y0, y1 = years[0], years[1]
slope = (data[y1] - data[y0]) / (y1 - y0)
return max(1.0, data[y0] + slope * (year - y0))
# Extrapolate after last census year
if year > years[-1]:
y0, y1 = years[-2], years[-1]
slope = (data[y1] - data[y0]) / (y1 - y0)
return max(1.0, data[y1] + slope * (year - y1))
# Interpolate between two surrounding census years
for i in range(len(years) - 1):
y0, y1 = years[i], years[i + 1]
if y0 <= year <= y1:
t = (year - y0) / (y1 - y0)
return max(1.0, data[y0] + t * (data[y1] - data[y0]))
return float(data[years[-1]]) # fallback
def get_avg_population_for_range(fips: str, start_year: int, end_year: int) -> float:
"""Average population across a year range — used to normalise multi-year aggregations."""
years = range(start_year, end_year + 1)
return sum(get_county_population(fips, y) for y in years) / max(len(years), 1)
# Forward declaration — replaced by _compute_risk_ceiling() after data loads
RISK_SCORE_CEILING: float = 1_000.0
def _compute_risk_ceiling() -> float:
"""99th-percentile per-capita risk score computed from the storms dataset —
the same source that drives damage/injuries/deaths in the displayed scores.
Groups by county across the full dataset so the ceiling matches the same
temporal aggregate scale as the map."""
try:
# Use storms (not summary) — summary_to_use() overwrites damage/injuries/deaths
# with values from storms, so this is the correct source for the ceiling
mapped = prepare_county_dataset(storms)
if mapped.empty:
return 1_000.0
count_src = get_event_id_column(mapped) or "FIPS"
prop_col = get_damage_property_column(mapped)
crop_col = get_damage_crops_column(mapped)
inj_col = get_injuries_column(mapped)
dth_col = get_deaths_column(mapped)
is_sig = pd.Series(False, index=mapped.index)
if prop_col is not None: is_sig = is_sig | (mapped[prop_col].fillna(0) > 0)
if crop_col is not None: is_sig = is_sig | (mapped[crop_col].fillna(0) > 0)
if inj_col is not None: is_sig = is_sig | (mapped[inj_col].fillna(0) > 0)
if dth_col is not None: is_sig = is_sig | (mapped[dth_col].fillna(0) > 0)
mapped['is_significant'] = is_sig.astype(int)
agg = {"event_count": ("is_significant", "sum")}
if prop_col: agg["property_damage"] = (prop_col, "sum")
if crop_col: agg["crop_damage"] = (crop_col, "sum")
if inj_col: agg["injuries_direct"] = (inj_col, "sum")
if dth_col: agg["deaths_direct"] = (dth_col, "sum")
# Group by county only — same as aggregate_county_metrics
cy = mapped.groupby("FIPS", dropna=False).agg(**agg).reset_index()
for col in ("property_damage", "crop_damage", "injuries_direct", "deaths_direct"):
if col not in cy.columns:
cy[col] = 0.0
cy["total_damage"] = cy["property_damage"] + cy["crop_damage"]
# Annualize over the actual data span — derived from the storms dataset
# rather than hardcoded, so this stays correct if the data is ever updated
date_col = get_begin_date_column(mapped)
if date_col is not None:
years = pd.to_datetime(mapped[date_col], errors="coerce").dt.year.dropna()
data_min_year = int(years.min())
data_max_year = int(years.max())
data_span = max(data_max_year - data_min_year + 1, 1)
else:
data_min_year, data_max_year, data_span = 1950, 2025, 75
# Use the same year range for population lookup so ceiling and displayed
# scores use a consistent denominator
cy["avg_population"] = cy["FIPS"].apply(
lambda f: get_avg_population_for_range(str(f), data_min_year, data_max_year)
).clip(lower=1)
cy["raw"] = compute_risk_score(
cy["event_count"], cy["total_damage"],
cy["injuries_direct"], cy["deaths_direct"],
)
cy["annualized"] = cy["raw"] / data_span
cy["per_capita"] = cy["annualized"] / cy["avg_population"] * 10_000
ceiling = float(cy["per_capita"].quantile(0.99))
logger.info(
"Risk ceiling from storms dataset — "
"min=%.1f median=%.1f 99pct=%.1f max=%.1f",
cy["per_capita"].min(), cy["per_capita"].median(),
ceiling, cy["per_capita"].max(),
)
return max(ceiling, 1.0)
except Exception as exc:
logger.warning("Could not compute risk ceiling: %s", exc)
return 1_000.0
def compute_dynamic_ceiling(df: pd.DataFrame, start_year: int, end_year: int) -> float:
"""Compute the 99th-percentile per-capita annualized risk score from the
currently filtered data. Called reactively so the ceiling always matches
the selected time window — a 2000-2025 filter is normalised against
2000-2025 data, not the full 1950-2025 history.
Returns the static RISK_SCORE_CEILING as a fallback if the data is too
sparse to compute a meaningful percentile (fewer than 10 counties with data).
"""
try:
mapped = prepare_county_dataset(df)
if mapped.empty:
return RISK_SCORE_CEILING
count_src = get_event_id_column(mapped) or "FIPS"
prop_col = get_damage_property_column(mapped)
crop_col = get_damage_crops_column(mapped)
inj_col = get_injuries_column(mapped)
dth_col = get_deaths_column(mapped)
is_sig = pd.Series(False, index=mapped.index)
if prop_col is not None: is_sig = is_sig | (mapped[prop_col].fillna(0) > 0)
if crop_col is not None: is_sig = is_sig | (mapped[crop_col].fillna(0) > 0)
if inj_col is not None: is_sig = is_sig | (mapped[inj_col].fillna(0) > 0)
if dth_col is not None: is_sig = is_sig | (mapped[dth_col].fillna(0) > 0)
mapped['is_significant'] = is_sig.astype(int)
agg = {"event_count": ("is_significant", "sum")}
if prop_col: agg["property_damage"] = (prop_col, "sum")
if crop_col: agg["crop_damage"] = (crop_col, "sum")
if inj_col: agg["injuries_direct"] = (inj_col, "sum")
if dth_col: agg["deaths_direct"] = (dth_col, "sum")
cy = mapped.groupby("FIPS", dropna=False).agg(**agg).reset_index()
if len(cy) < 10:
return RISK_SCORE_CEILING # too sparse — fall back to static ceiling
for col in ("property_damage", "crop_damage", "injuries_direct", "deaths_direct"):
if col not in cy.columns:
cy[col] = 0.0
cy["total_damage"] = cy["property_damage"] + cy["crop_damage"]
years_in_window = max(end_year - start_year + 1, 1)
cy["avg_population"] = cy["FIPS"].apply(
lambda f: get_avg_population_for_range(str(f), start_year, end_year)
).clip(lower=1)
cy["raw"] = compute_risk_score(
cy["event_count"], cy["total_damage"],
cy["injuries_direct"], cy["deaths_direct"],
)
cy["per_capita"] = (cy["raw"] / years_in_window) / cy["avg_population"] * 10_000
return max(float(cy["per_capita"].quantile(0.99)), 1.0)
except Exception as exc:
logger.warning("Could not compute dynamic ceiling: %s", exc)
return RISK_SCORE_CEILING
HAZARD_DISPLAY_OVERRIDES = {
"Cold/Wind Chill": "Cold and Wind Chill",
"Extreme Cold/Wind Chill": "Extreme Cold and Wind Chill",
"Frost/Freeze": "Frost and Freeze",
}
# ═══════════════════════════════════════════════════════════════════════════════
# GEOJSON LOADING
# Loads county boundaries from the geojson file in the local data directory.
# If that file is missing, the geometry is fetched from the Plotly
# CDN and cached locally for all future runs.
#
# Produces two globals used throughout the chart builders:
# COUNTY_GEOJSON – FeatureCollection passed directly to go.Choropleth
# COUNTY_NAME_MAP – {fips_str: county_name} lookup dict
# COUNTY_FIPS – sorted tuple of all valid county FIPS codes
# ═══════════════════════════════════════════════════════════════════════════════
def load_county_geojson():
if COUNTY_GEOJSON_PATH.exists():
geojson = json.loads(COUNTY_GEOJSON_PATH.read_text())
else:
response = requests.get(
"https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json",
timeout=20,
)
response.raise_for_status()
raw_geojson = response.json()
geojson = {
"type": "FeatureCollection",
"features": [feature for feature in raw_geojson["features"] if feature["id"].startswith(STATE_CONFIG["state_fips_prefix"])],
}
COUNTY_GEOJSON_PATH.write_text(json.dumps(geojson))
county_name_map = {
feature["id"]: feature["properties"].get("NAME", feature["id"])
for feature in geojson["features"]
}
# Derive map bounds by walking every coordinate in every feature's geometry.
# Supports both Polygon and MultiPolygon so any county shape works correctly.
all_lons: list[float] = []
all_lats: list[float] = []
for feature in geojson["features"]:
geometry = feature.get("geometry", {})
coords = geometry.get("coordinates", [])
geom_type = geometry.get("type", "")
# MultiPolygon → list of polygons → list of rings → list of [lon, lat]
# Polygon → list of rings → list of [lon, lat]
rings = []
if geom_type == "MultiPolygon":
for polygon in coords:
rings.extend(polygon)
elif geom_type == "Polygon":
rings = coords
for ring in rings:
for lon, lat in ring:
all_lons.append(lon)
all_lats.append(lat)
if all_lats and all_lons:
padding = 0.5 # degrees of breathing room around the state edge
bounds = {
"lat_min": min(all_lats) - padding,
"lat_max": max(all_lats) + padding,
"lon_min": min(all_lons) - padding,
"lon_max": max(all_lons) + padding,
}
else:
bounds = {"lat_min": 24.0, "lat_max": 50.0, "lon_min": -125.0, "lon_max": -66.0}
return geojson, county_name_map, bounds
try:
COUNTY_GEOJSON, COUNTY_NAME_MAP, COUNTY_MAP_BOUNDS = load_county_geojson()
except Exception as error:
logger.exception("Could not load county geojson: %s", error)
COUNTY_GEOJSON, COUNTY_NAME_MAP = None, {}
COUNTY_MAP_BOUNDS = {"lat_min": 24.0, "lat_max": 50.0, "lon_min": -125.0, "lon_max": -66.0}
COUNTY_FIPS = tuple(sorted(COUNTY_NAME_MAP))
# ═══════════════════════════════════════════════════════════════════════════════
# CHART UTILITY HELPERS
#
# empty_figure – placeholder figure shown when a chart has no data
# polish_figure – applies brand font/bgcolor/hoverlabel to any figure
# normalize_hazard_label – canonicalizes raw EVENT_TYPE strings (e.g. "Cold/Wind
# Chill" → "Cold and Wind Chill") via HAZARD_DISPLAY_OVERRIDES
# add_hazard_display_column – adds the synthetic HAZARD_DISPLAY_COLUMN to a df
# get_hazard_display_column – resolves that column (or falls back to EVENT_TYPE)
# build_chart_title – assembles a "Title<br><sup>subtitle</sup>" string
# format_metric_value – formats a numeric value using the METRIC_META spec
# selected_hazard_label – human-readable label for the current hazard selection
# filter_by_hazard – filters a df to rows matching a hazard dropdown choice
# ═══════════════════════════════════════════════════════════════════════════════
def empty_figure(title: str, message: str):
fig = px.scatter(title=title)
fig.update_xaxes(visible=False)
fig.update_yaxes(visible=False)
fig.update_layout(showlegend=False, height=480)
fig.add_annotation(text=message, showarrow=False, x=0.5, y=0.5, xref="paper", yref="paper")
return fig
def polish_figure(fig):
"""Apply consistent layout polish to any Plotly figure."""
fig.update_layout(
font=_CHART_FONT,
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
title_font={"size": 15, "color": "#212529", "family": "system-ui, -apple-system, 'Segoe UI', sans-serif"},
hoverlabel=dict(
bgcolor="white",
bordercolor="#dee2e6",
font_size=13,
font_family="system-ui, -apple-system, 'Segoe UI', sans-serif",
align="left",
),
)
fig.update_xaxes(**_AXIS_STYLE)
fig.update_yaxes(**_AXIS_STYLE)
return fig
def normalize_hazard_label(value: object) -> str:
label = " ".join(str(value).strip().split()) if pd.notna(value) else "Unknown"
if not label:
label = "Unknown"
return HAZARD_DISPLAY_OVERRIDES.get(label, label)
def add_hazard_display_column(df: pd.DataFrame, event_type_column: str | None) -> pd.DataFrame:
working = df.copy()
if event_type_column is None:
working[HAZARD_DISPLAY_COLUMN] = "Unknown"
return working
working[HAZARD_DISPLAY_COLUMN] = working[event_type_column].map(normalize_hazard_label)
return working
def get_hazard_display_column(df: pd.DataFrame) -> str | None:
if HAZARD_DISPLAY_COLUMN in df.columns:
return HAZARD_DISPLAY_COLUMN
return get_event_type_column(df)
def build_chart_title(title: str, subtitle: str | None = None) -> str:
if not subtitle:
return title
return f"{title}<br><sup>{subtitle}</sup>"
def format_metric_value(value, metric_key: str) -> str:
if pd.isna(value):
return "N/A"
meta = METRIC_META.get(metric_key, {})
fmt = meta.get("format", "float1")
label = meta.get("label", "")
# Extract unit suffix from label, e.g. "(mm)" → " mm", "(°C)" → " °C"
unit_match = re.search(r'\((.*?)\)', label)
unit = f" {unit_match.group(1)}" if unit_match else ""
if fmt == "currency":
return f"${value:,.0f}"
if fmt == "count":
return f"{int(round(value)):,}"
if fmt == "score":
return f"{value:,.1f}"
# For weather metrics, append the unit (e.g., "12.4 mm")
return f"{value:,.1f}{unit}"
def selected_hazard_label(hazard_choice: str) -> str:
return hazard_choice if hazard_choice != ALL_HAZARDS else "All hazards"
def filter_by_hazard(df: pd.DataFrame, hazard_choice: str) -> pd.DataFrame:
hazard_column = get_hazard_display_column(df)
if hazard_choice == ALL_HAZARDS or hazard_column is None:
return df.copy()
hazard_values = df[hazard_column].astype("string").fillna("").str.strip()
if hazard_choice in HAZARD_MAP:
# Translation: Find any row that matches one of the items in our list
categories_to_find = HAZARD_MAP[hazard_choice]
return df[hazard_values.isin(categories_to_find)].copy()
return df[hazard_values.eq(hazard_choice)].copy()
# ═══════════════════════════════════════════════════════════════════════════════
# DATA LOADING & HAZARD TAXONOMY
#
# Both Parquet files are read once at startup into module-level DataFrames:
# storms – storm_events_mn.parquet (one row per event, 1950-2025)
# summary – storm_weather_summary_mn.parquet (events joined with daily weather)
#
# Column names are resolved via geo_utils helpers and stored as STORM_*/SUMMARY_*
# constants so the rest of the app never hard-codes column strings directly.
#
# HAZARD TAXONOMY
# EVENT_TYPE_CHOICES – the labels shown in every hazard dropdown
# HAZARD_MAP – maps each UI label to one or more raw EVENT_TYPE values
# in the Parquet data (the "translation layer")
# ═══════════════════════════════════════════════════════════════════════════════
# Load data once after schema helpers are defined.
storms = normalize_dataframe_columns(pd.read_parquet(DATA_DIR / "storm_events_mn.parquet"))
summary = normalize_dataframe_columns(pd.read_parquet(DATA_DIR / "storm_weather_summary_mn.parquet"))
STORM_DATE_COLUMN = get_begin_date_column(storms)
STORM_GEO_COLUMN = get_geo_group_column(storms)
STORM_FIPS_COLUMN = get_geo_fips_column(storms)
STORM_EVENT_COLUMN = get_event_id_column(storms)
STORM_EVENT_TYPE_COLUMN = get_event_type_column(storms)
STORM_DAMAGE_COLUMN = get_damage_property_column(storms)
STORM_CROP_DAMAGE_COLUMN = get_damage_crops_column(storms)
STORM_INJURIES_COLUMN = get_injuries_column(storms)
STORM_DEATHS_COLUMN = get_deaths_column(storms)
SUMMARY_DATE_COLUMN = get_begin_date_column(summary)
SUMMARY_GEO_COLUMN = get_geo_group_column(summary)
SUMMARY_FIPS_COLUMN = get_geo_fips_column(summary)
SUMMARY_EVENT_COLUMN = get_event_id_column(summary)
SUMMARY_EVENT_TYPE_COLUMN = get_event_type_column(summary)
SUMMARY_DAMAGE_COLUMN = get_damage_property_column(summary)
SUMMARY_CROP_DAMAGE_COLUMN = get_damage_crops_column(summary)
SUMMARY_INJURIES_COLUMN = get_injuries_column(summary)
SUMMARY_DEATHS_COLUMN = get_deaths_column(summary)
SUMMARY_PRECIP_COLUMN = get_precipitation_column(summary)
SUMMARY_TMAX_COLUMN = get_max_temperature_column(summary)
SUMMARY_TMIN_COLUMN = resolve_column(summary, ("daily_tmin_avg", "tmin", "min_temperature"))
SUMMARY_SNOW_COLUMN = get_snowfall_column(summary)
SUMMARY_SNOW_DEPTH_COLUMN = get_snow_depth_column(summary)
SUMMARY_WIND_COLUMN = get_wind_speed_column(summary)
storms = add_hazard_display_column(storms, STORM_EVENT_TYPE_COLUMN)
summary = add_hazard_display_column(summary, SUMMARY_EVENT_TYPE_COLUMN)
# The labels shown in the dropdown UI
EVENT_TYPE_CHOICES = [
"All hazards",
"Winter Storms",
"Extreme Cold",
"Flooding",
"Severe Wind & Tornado",
"Hail",
"Heat Emergencies",
"Drought",
"Ice & Freeze"
]
# The "Translation Key" that connects UI labels to Parquet data values
HAZARD_MAP = {
"Winter Storms": ["Winter Storm", "Winter Weather", "Heavy Snow", "Blizzard"],
"Extreme Cold": ["Cold and Wind Chill", "Extreme Cold and Wind Chill"],
"Flooding": ["Flood", "Flash Flood"],
"Severe Wind & Tornado": ["High Wind", "Thunderstorm Wind", "Tornado", "Strong Wind"],
"Heat Emergencies": ["Heat", "Excessive Heat"],
"Ice & Freeze": ["Ice Storm", "Frost and Freeze"],
"Hail": ["Hail"],
"Drought": ["Drought"]
}
# ═══════════════════════════════════════════════════════════════════════════════
# SCHEMA VALIDATION
# Logs a WARNING at startup for any expected column that could not be resolved
# in either dataset. Issues surface here rather than silently producing empty
# charts when the app first loads. All checks are non-fatal — the app will
# continue running with degraded output.
# ═══════════════════════════════════════════════════════════════════════════════
for dataset_name, required_columns in {
"storms": {
"date": STORM_DATE_COLUMN,
"geo_group": STORM_GEO_COLUMN,
"event_id": STORM_EVENT_COLUMN,
"event_type": STORM_EVENT_TYPE_COLUMN,
"damage": STORM_DAMAGE_COLUMN,
"injuries": STORM_INJURIES_COLUMN,
},
"summary": {
"date": SUMMARY_DATE_COLUMN,
"geo_group": SUMMARY_GEO_COLUMN,
"event_id": SUMMARY_EVENT_COLUMN,
"event_type": SUMMARY_EVENT_TYPE_COLUMN,
"precipitation": SUMMARY_PRECIP_COLUMN,
"max_temperature": SUMMARY_TMAX_COLUMN,
"wind_speed": SUMMARY_WIND_COLUMN,
},
}.items():
missing = [label for label, column in required_columns.items() if column is None]
if missing:
columns = list(storms.columns if dataset_name == "storms" else summary.columns)
logger.warning("%s is missing %s. Available columns: %s", dataset_name, missing, columns)
# ═══════════════════════════════════════════════════════════════════════════════
# DATA PROCESSING & AGGREGATION
# Pure transformation functions — no Shiny inputs, no reactive context.
# Each function takes a filtered DataFrame and returns a ready-to-plot aggregate.
# Keeping these separate from chart builders means they can be tested
# independently and reused across multiple tabs without re-querying raw data.
#
# prepare_county_dataset – FIPS normalization & county name join
# aggregate_county_metrics – per-county event counts, damage totals,
# weather averages, and composite risk score
# aggregate_hazard_metrics – per-hazard-type rollup for comparison charts
# add_time_frame – attaches frame_label/frame_sort for animations
# build_animation_dataset – county × time-frame grid with zero-fill
# classify_trend_direction – maps a normalized slope to Increasing/Stable/Decreasing
# compute_county_trend_classification – per-county trend over recent N frames
# compute_weather_correlations – Pearson r between storm events and weather vars
# ═══════════════════════════════════════════════════════════════════════════════
def prepare_county_dataset(df: pd.DataFrame) -> pd.DataFrame:
working = normalize_dataframe_columns(df.copy())
if working.empty or not COUNTY_NAME_MAP:
return working.iloc[0:0].copy()
fips_column = get_geo_fips_column(working)
if fips_column is None:
return working.iloc[0:0].copy()
working["FIPS"] = working[fips_column].map(
lambda v: to_county_fips(v, STATE_CONFIG["state_fips_prefix"])
)
working = working[working["FIPS"].isin(COUNTY_FIPS)].copy()
if working.empty:
return working
working["county_name"] = working["FIPS"].map(COUNTY_NAME_MAP)
geo_column = get_geo_group_column(working)
if geo_column is not None:
working["source_geo_name"] = working[geo_column].astype("string").fillna("").str.strip()
hazard_column = get_hazard_display_column(working)
if hazard_column is not None:
working["hazard_label"] = working[hazard_column].astype("string").fillna("Unknown").str.strip()
date_column = get_begin_date_column(working)
if date_column is not None:
working[date_column] = pd.to_datetime(working[date_column], errors="coerce")
working = working[working[date_column].notna()].copy()
return working
# ── Ceiling computed here — prepare_county_dataset is now defined ──────────────
RISK_SCORE_CEILING = _compute_risk_ceiling()
def aggregate_county_metrics(
df: pd.DataFrame,
start_year: int | None = None,
end_year: int | None = None,
ceiling: float | None = None,
) -> pd.DataFrame:
mapped = prepare_county_dataset(df)
if mapped.empty:
return mapped
# 1. Infer year range from the data if not supplied
if start_year is None or end_year is None:
date_col = get_begin_date_column(mapped)
if date_col is not None:
years = pd.to_datetime(mapped[date_col], errors="coerce").dt.year.dropna()
start_year = int(years.min()) if start_year is None and not years.empty else (start_year or 2020)
end_year = int(years.max()) if end_year is None and not years.empty else (end_year or 2020)
else:
start_year, end_year = 2020, 2020
# 2. Resolve data columns
count_source = get_event_id_column(mapped) or "FIPS"
damage_column = get_damage_property_column(mapped)
crop_column = get_damage_crops_column(mapped)
injuries_column = get_injuries_column(mapped)
deaths_column = get_deaths_column(mapped)
precip_column = get_precipitation_column(mapped)
tmax_column = get_max_temperature_column(mapped)
tmin_column = resolve_column(mapped, ("daily_tmin_avg", "tmin", "min_temperature"))
wind_column = get_wind_speed_column(mapped)
snow_column = get_snowfall_column(mapped)
# 3. Flag "significant" events: any event with measurable damage, injury, or death.
# sig_events feeds the risk score formula; event_count feeds visual totals.
is_sig = pd.Series(False, index=mapped.index)
if damage_column is not None: is_sig = is_sig | (mapped[damage_column].fillna(0) > 0)
if crop_column is not None: is_sig = is_sig | (mapped[crop_column].fillna(0) > 0)
if injuries_column is not None: is_sig = is_sig | (mapped[injuries_column].fillna(0) > 0)
if deaths_column is not None: is_sig = is_sig | (mapped[deaths_column].fillna(0) > 0)
mapped['is_significant'] = is_sig.astype(int)
# 4. Aggregate: every row counts toward event_count (used in charts);
# only significant events count toward sig_events (used in risk math).
agg_kwargs = {
"event_count": (count_source, "count"),
"sig_events": ("is_significant", "sum")
}
if damage_column is not None: agg_kwargs["property_damage"] = (damage_column, "sum")
if crop_column is not None: agg_kwargs["crop_damage"] = (crop_column, "sum")
if injuries_column is not None: agg_kwargs["injuries_direct"] = (injuries_column, "sum")
if deaths_column is not None: agg_kwargs["deaths_direct"] = (deaths_column, "sum")
if precip_column is not None: agg_kwargs["avg_precip"] = (precip_column, "mean")
if tmax_column is not None: agg_kwargs["avg_tmax"] = (tmax_column, "mean")
if tmin_column is not None: agg_kwargs["avg_tmin"] = (tmin_column, "mean")
if wind_column is not None: agg_kwargs["avg_wind"] = (wind_column, "mean")
if snow_column is not None: agg_kwargs["avg_snow"] = (snow_column, "mean")
# 5. Group data by county
county_data = mapped.groupby(["FIPS", "county_name"], dropna=False).agg(**agg_kwargs).reset_index()
# 6. Fill missing metrics with defaults
for column in ("property_damage", "crop_damage", "injuries_direct", "deaths_direct"):
if column not in county_data.columns:
county_data[column] = 0.0
county_data["total_damage"] = county_data["property_damage"] + county_data["crop_damage"]
for column in ("avg_precip", "avg_tmax", "avg_tmin", "avg_wind", "avg_snow"):
if column not in county_data.columns:
county_data[column] = np.nan
# 7. Raw absolute risk score using 'sig_events' instead of 'event_count'
county_data["raw_risk_score"] = compute_risk_score(
county_data["sig_events"],
county_data["total_damage"],
county_data["injuries_direct"],
county_data["deaths_direct"],
)
# 8. Normalization (Annualize & Per-Capita)
years_in_window = max(end_year - start_year + 1, 1)
county_data["annualized_risk"] = county_data["raw_risk_score"] / years_in_window
county_data["avg_population"] = county_data["FIPS"].apply(
lambda fips: get_avg_population_for_range(str(fips), start_year, end_year)
).clip(lower=1)
county_data["per_capita_risk"] = (
county_data["annualized_risk"] / county_data["avg_population"] * 10_000
)
# 9. Scale 0–100 using dynamic ceiling
effective_ceiling = ceiling if (ceiling is not None and ceiling > 0) else RISK_SCORE_CEILING
effective_ceiling = max(effective_ceiling, 1.0)
county_data["risk_score"] = (
(county_data["per_capita_risk"] / effective_ceiling * 100)
.clip(upper=100)
.round(1)
)
return county_data.sort_values("risk_score", ascending=False).reset_index(drop=True)
def aggregate_hazard_metrics(df: pd.DataFrame) -> pd.DataFrame:
working = normalize_dataframe_columns(df.copy())
hazard_column = get_hazard_display_column(working)
if working.empty or hazard_column is None:
return pd.DataFrame()
working["event_type"] = working[hazard_column].astype("string").fillna("Unknown").str.strip()
count_source = get_event_id_column(working) or hazard_column
damage_column = get_damage_property_column(working)
injuries_column = get_injuries_column(working)
precip_column = get_precipitation_column(working)
tmax_column = get_max_temperature_column(working)
wind_column = get_wind_speed_column(working)
snow_column = get_snowfall_column(working)
agg_kwargs = {"event_count": (count_source, "count")}
if damage_column is not None:
agg_kwargs["property_damage"] = (damage_column, "sum")
if injuries_column is not None:
agg_kwargs["injuries_direct"] = (injuries_column, "sum")
if precip_column is not None:
agg_kwargs["avg_precip"] = (precip_column, "mean")
if tmax_column is not None:
agg_kwargs["avg_tmax"] = (tmax_column, "mean")
if wind_column is not None:
agg_kwargs["avg_wind"] = (wind_column, "mean")
if snow_column is not None:
agg_kwargs["avg_snow"] = (snow_column, "mean")
hazard_data = working.groupby("event_type", dropna=False).agg(**agg_kwargs).reset_index()
for column in ("property_damage", "injuries_direct", "avg_precip", "avg_tmax", "avg_wind", "avg_snow"):
if column not in hazard_data.columns:
hazard_data[column] = np.nan if column.startswith("avg_") else 0.0
return hazard_data.sort_values("event_count", ascending=False).reset_index(drop=True)
def add_time_frame(
df: pd.DataFrame,
date_column: str,
preferred_frame: str | None = None,
) -> tuple[pd.DataFrame, str | None]:
working = df.copy()
working[date_column] = pd.to_datetime(working[date_column], errors="coerce")
working = working[working[date_column].notna()].copy()
if working.empty:
return working, None
dates = working[date_column]
monthly_available = dates.dt.to_period("M").nunique() > 1
if preferred_frame == "Month" and monthly_available:
monthly_frames = True
elif preferred_frame == "Year":
monthly_frames = False
else:
span_days = (dates.max() - dates.min()).days
monthly_frames = span_days <= 730 and monthly_available
if monthly_frames:
working["frame_label"] = dates.dt.strftime("%b %Y")
working["frame_sort"] = dates.dt.to_period("M").dt.to_timestamp()
return working, "Month"
working["frame_label"] = dates.dt.year.astype(int).astype(str)
working["frame_sort"] = dates.dt.to_period("Y").dt.to_timestamp()
return working, "Year"
def build_animation_dataset(df: pd.DataFrame, ceiling: float | None = None) -> tuple[pd.DataFrame, str | None]:
mapped = prepare_county_dataset(df)
date_column = get_begin_date_column(mapped)
if mapped.empty or date_column is None:
return mapped.iloc[0:0].copy(), None
framed, frame_name = add_time_frame(mapped, date_column)
if framed.empty or frame_name is None:
return framed.iloc[0:0].copy(), None
count_source = get_event_id_column(framed) or "FIPS"
damage_column = get_damage_property_column(framed)
crop_column = get_damage_crops_column(framed)
injuries_column = get_injuries_column(framed)
deaths_column = get_deaths_column(framed)
is_sig = pd.Series(False, index=framed.index)
if damage_column is not None: is_sig = is_sig | (framed[damage_column].fillna(0) > 0)
if crop_column is not None: is_sig = is_sig | (framed[crop_column].fillna(0) > 0)
if injuries_column is not None: is_sig = is_sig | (framed[injuries_column].fillna(0) > 0)
if deaths_column is not None: is_sig = is_sig | (framed[deaths_column].fillna(0) > 0)
framed['is_significant'] = is_sig.astype(int)