-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpost_bluesky.py
More file actions
2539 lines (2110 loc) · 97.1 KB
/
Copy pathpost_bluesky.py
File metadata and controls
2539 lines (2110 loc) · 97.1 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
#!/usr/bin/env python3
"""
WXD Bluesky Poster - Generates AI commentary and posts to Bluesky.
Reads history_compact.json, analyzes run-to-run changes, generates
confidence indicators, triggers threshold alerts, and posts to Bluesky.
Usage:
python post_bluesky.py # Normal post with chart
python post_bluesky.py --changelog "msg" # Post manual changelog
python post_bluesky.py --weekly # Post weekly git changelog (auto)
"""
import argparse
import json
import subprocess
import sys
import os
from datetime import datetime, timezone, timedelta
from pathlib import Path
from statistics import mean, stdev
from collections import defaultdict
# Import period analysis from shared module
import sys
sys.path.insert(0, 'trackers')
from shared.analysis import analyze_by_period, format_period_context
# Import post registry for feedback tracing
try:
from lib.bluesky import register_post
HAS_REGISTRY = True
except ImportError:
HAS_REGISTRY = False
register_post = None
# Import Met Office warnings
try:
from daily_summary import fetch_metoffice_narrative, filter_warnings_48h
HAS_METOFFICE = True
except ImportError:
HAS_METOFFICE = False
fetch_metoffice_narrative = None
filter_warnings_48h = None
def fetch_current_warnings() -> str:
"""Fetch and format current Met Office warnings for Claude prompt.
Uses filter_warnings_48h() for STRICT validation:
- Only structured warning data (not forecast headers)
- Must have date, level, AND regions
- Within 48 hours only
"""
if not HAS_METOFFICE or not fetch_metoffice_narrative:
return ""
try:
mo_data = fetch_metoffice_narrative()
uk_warn = mo_data.get("uk_warnings", "")
# Use strict 48h filter - returns empty string if validation fails
filtered = filter_warnings_48h(uk_warn) if filter_warnings_48h else ""
if filtered:
return f"MET OFFICE WARNINGS (VERIFIED, 48H): {filtered}"
else:
return "MET OFFICE WARNINGS: None currently in force. DO NOT invent or assume warnings."
except Exception as e:
print(f" Warning fetch error: {e}")
return ""
# Try imports - will fail gracefully if not installed
try:
import matplotlib
matplotlib.use('Agg') # Headless
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
try:
from atproto import Client, models as atproto_models
HAS_ATPROTO = True
except ImportError:
HAS_ATPROTO = False
# Thresholds
COLD_THRESHOLD = -5.0 # Cold alert threshold
EXTREME_COLD_THRESHOLD = -8.0 # Extreme cold threshold
WARM_THRESHOLD = 10.0 # Warm threshold (summer)
RUN_DIFF_THRESHOLD = 2.0 # Flag if model shifts more than this
MODEL_DIVERGENCE_THRESHOLD = 4.0 # Inter-model disagreement threshold
HYSTERESIS_RUNS = 2 # Must appear in N consecutive runs to trigger
# Model display names (for posts and alerts)
MODEL_NAMES = {
'gfs': 'GFS',
'ecmwf_ifs': 'ECM',
'ecmwf_aifs': 'AIFS',
'gem': 'GEM'
}
def format_model_name(model_key: str) -> str:
"""Format model key for display in posts."""
return MODEL_NAMES.get(model_key, model_key.upper().replace('_', ' '))
def utcnow() -> datetime:
return datetime.now(timezone.utc)
def get_run_label(fetched_at: str) -> str:
"""Determine which model run this fetch captures (00z or 12z)."""
try:
dt = datetime.fromisoformat(fetched_at.replace('Z', '+00:00'))
hour = dt.hour
# 09:00 UTC fetch captures 00z run, 21:00 UTC captures 12z run
if 6 <= hour < 18:
return "00z run"
else:
return "12z run"
except Exception:
return ""
def load_alert_state(state_path: Path) -> dict:
"""Load alert state for hysteresis tracking."""
if state_path.exists():
try:
with open(state_path, 'r') as f:
return json.load(f)
except Exception:
pass
return {
'cold_count': 0,
'extreme_cold_count': 0,
'warm_count': 0,
'last_cold_alert': None,
'last_extreme_cold_alert': None,
'last_warm_alert': None
}
def save_alert_state(state_path: Path, state: dict) -> None:
"""Save alert state for hysteresis tracking."""
with open(state_path, 'w') as f:
json.dump(state, f, indent=2)
def analyze_run_diff(data: dict) -> list:
"""Compare current run vs previous run, return significant shifts."""
runs = data.get('runs', [])
if len(runs) < 2:
return []
current = runs[0]
previous = runs[1]
diffs = []
current_ts = current.get('timestamps', [])
previous_ts = previous.get('timestamps', [])
# Find common timestamps
common_ts = set(current_ts) & set(previous_ts)
for model_key in current.get('models', {}).keys():
curr_model = current['models'].get(model_key, {})
prev_model = previous.get('models', {}).get(model_key, {})
if not curr_model or not prev_model:
continue
curr_means = curr_model.get('mean', [])
prev_means = prev_model.get('mean', [])
for ts in common_ts:
try:
curr_idx = current_ts.index(ts)
prev_idx = previous_ts.index(ts)
if curr_idx < len(curr_means) and prev_idx < len(prev_means):
curr_val = curr_means[curr_idx]
prev_val = prev_means[prev_idx]
if curr_val is not None and prev_val is not None:
diff = curr_val - prev_val
if abs(diff) >= RUN_DIFF_THRESHOLD:
diffs.append({
'model': format_model_name(model_key),
'timestamp': ts,
'diff': round(diff, 1),
'direction': 'warmed' if diff > 0 else 'cooled'
})
except (ValueError, IndexError):
continue
# Sort by absolute diff, return top 3
diffs.sort(key=lambda x: abs(x['diff']), reverse=True)
return diffs[:3]
def check_cold_threshold(data: dict) -> dict:
"""Check ALL models hitting cold threshold, return details for each.
Returns dict with:
- models: list of all models crossing threshold with their coldest temp/date
- coldest: the single coldest model (for backwards compat)
- extreme: True if any model hits extreme threshold
- multi_model: True if 2+ models cross threshold (strong signal)
"""
runs = data.get('runs', [])
if not runs:
return None
current = runs[0]
models = current.get('models', {})
timestamps = current.get('timestamps', [])
# Find coldest point for each model
model_coldest = []
extreme_cold = False
for model_key, model_data in models.items():
means = model_data.get('mean', [])
model_min = {'temp': 999, 'model': format_model_name(model_key), 'date': None}
for i, val in enumerate(means):
if val is not None and val < model_min['temp']:
model_min['temp'] = val
if i < len(timestamps):
model_min['date'] = timestamps[i][:10]
# Check if this model crosses threshold
if model_min['temp'] <= COLD_THRESHOLD:
model_min['temp'] = round(model_min['temp'], 1)
model_coldest.append(model_min)
if model_min['temp'] <= EXTREME_COLD_THRESHOLD:
extreme_cold = True
if not model_coldest:
return None
# Sort by temperature (coldest first)
model_coldest.sort(key=lambda x: x['temp'])
return {
'models': model_coldest,
'coldest': model_coldest[0], # Backwards compat - single coldest
'temp': model_coldest[0]['temp'], # Backwards compat
'model': model_coldest[0]['model'], # Backwards compat
'date': model_coldest[0]['date'], # Backwards compat
'extreme': extreme_cold,
'multi_model': len(model_coldest) >= 2,
'type': 'extreme' if extreme_cold else 'cold'
}
def get_peak_timing_from_raw(data: dict) -> str:
"""Get PEAK TIMING context from raw data, regardless of cold threshold.
This finds the coldest point across all models and determines if it's
PAST, TODAY, or FUTURE relative to today.
Returns context string or None.
"""
runs = data.get('runs', [])
if not runs:
return None
current = runs[0]
models = current.get('models', {})
timestamps = current.get('timestamps', [])
if not models or not timestamps:
return None
# Find coldest point across all models
overall_coldest = {'temp': 999, 'date': None}
for model_key, model_data in models.items():
means = model_data.get('mean', [])
for i, val in enumerate(means):
if val is not None and val < overall_coldest['temp']:
overall_coldest['temp'] = val
if i < len(timestamps):
overall_coldest['date'] = timestamps[i][:10]
if not overall_coldest['date']:
return None
try:
today = datetime.now(timezone.utc).date()
peak_date = datetime.strptime(overall_coldest['date'], '%Y-%m-%d').date()
if peak_date < today:
return f"PEAK TIMING: PAST - coldest point ({overall_coldest['temp']:.1f}C) was {peak_date.strftime('%a %b %d')}, we are now WARMING. Do NOT say 'peak holding' or 'cold persisting'."
elif peak_date == today:
return f"PEAK TIMING: TODAY - coldest point ({overall_coldest['temp']:.1f}C) is today, warming follows."
else:
days_away = (peak_date - today).days
if days_away <= 2:
return f"PEAK TIMING: SOON - coldest ({overall_coldest['temp']:.1f}C) arrives {peak_date.strftime('%a %b %d')}, still cooling."
else:
return f"PEAK TIMING: FUTURE - coldest ({overall_coldest['temp']:.1f}C) on {peak_date.strftime('%a %b %d')}, {days_away} days away."
except:
return None
def get_temperature_trajectory(data: dict) -> str:
"""Get multi-model mean temperature trajectory for context.
Shows daily noon temperatures so Claude can verify dates.
"""
runs = data.get('runs', [])
if not runs:
return None
current = runs[0]
timestamps = current.get('timestamps', [])
multi_model_mean = current.get('multi_model_mean', [])
if not timestamps or not multi_model_mean:
return None
# Build daily noon trajectory
trajectory = []
seen_dates = set()
for i, (ts, temp) in enumerate(zip(timestamps, multi_model_mean)):
if temp is None:
continue
try:
dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
date_key = dt.date()
# Take noon value (or first value for each day)
if date_key not in seen_dates and (dt.hour == 12 or date_key not in seen_dates):
seen_dates.add(date_key)
trajectory.append(f"{dt.strftime('%a %b %d')}: {temp:+.1f}C")
except:
continue
if not trajectory:
return None
# Only include first 12 days to keep context manageable
trajectory = trajectory[:12]
return "TEMPERATURE TRAJECTORY (multi-model mean, daily):\n" + "\n".join(trajectory)
def check_model_divergence(data: dict) -> dict:
"""Check for strong model disagreement (>4°C) at any forecast time."""
runs = data.get('runs', [])
if not runs:
return None
current = runs[0]
models = current.get('models', {})
timestamps = current.get('timestamps', [])
if len(models) < 2:
return None
max_divergence = {'diff': 0, 'date': None, 'models': []}
for i, ts in enumerate(timestamps):
model_means = {}
for model_key, model_data in models.items():
means = model_data.get('mean', [])
if i < len(means) and means[i] is not None:
model_means[model_key] = means[i]
if len(model_means) >= 2:
sorted_models = sorted(model_means.items(), key=lambda x: x[1])
coldest = sorted_models[0]
warmest = sorted_models[-1]
diff = warmest[1] - coldest[1]
if diff > max_divergence['diff']:
max_divergence = {
'diff': round(diff, 1),
'date': ts[:10],
'coldest': format_model_name(coldest[0]),
'warmest': format_model_name(warmest[0]),
'coldest_temp': round(coldest[1], 1),
'warmest_temp': round(warmest[1], 1)
}
if max_divergence['diff'] > MODEL_DIVERGENCE_THRESHOLD:
return max_divergence
return None
def check_rapid_swing(data: dict) -> dict:
"""Check for rapid temperature swing (≥6°C change in 48h window).
Only considers FUTURE swings (start_date >= today) to avoid
narrating past weather events. Historical data is for run-to-run
comparison, not for reporting what already happened.
"""
runs = data.get('runs', [])
if not runs:
return None
current = runs[0]
mmm = current.get('multi_model_mean', [])
timestamps = current.get('timestamps', [])
if len(mmm) < 5 or len(timestamps) < 5: # Need at least a few data points
return None
# Only look at future timestamps (>= today)
today = utcnow().strftime('%Y-%m-%d')
# Look for biggest 48h swing (4 x 12h intervals) in FUTURE only
max_swing = {'swing': 0, 'start_date': None, 'end_date': None, 'direction': None}
for i in range(len(mmm) - 4):
start_date = timestamps[i][:10]
# Skip historical swings - only report future forecast
if start_date < today:
continue
if mmm[i] is not None and mmm[i + 4] is not None:
swing = mmm[i + 4] - mmm[i]
if abs(swing) > abs(max_swing['swing']):
max_swing = {
'swing': round(swing, 1),
'start_date': start_date,
'end_date': timestamps[i + 4][:10],
'direction': 'warming' if swing > 0 else 'cooling'
}
if abs(max_swing['swing']) >= 6.0:
return max_swing
return None
def check_warm_threshold(data: dict) -> dict:
"""Check for warm threshold (+10°C/+15°C) - only active Apr-Sep."""
# Check if we're in warm season
now = utcnow()
if now.month < 4 or now.month > 9:
return None # Only active Apr-Sep
runs = data.get('runs', [])
if not runs:
return None
current = runs[0]
models = current.get('models', {})
timestamps = current.get('timestamps', [])
warmest = {'temp': -999, 'model': None, 'date': None}
extreme_warm = False
for model_key, model_data in models.items():
means = model_data.get('mean', [])
for i, val in enumerate(means):
if val is not None and val > warmest['temp']:
warmest['temp'] = val
warmest['model'] = format_model_name(model_key)
if i < len(timestamps):
warmest['date'] = timestamps[i][:10]
if warmest['temp'] >= 15.0:
extreme_warm = True
if warmest['temp'] >= WARM_THRESHOLD:
return {
'temp': round(warmest['temp'], 1),
'model': warmest['model'],
'date': warmest['date'],
'extreme': extreme_warm
}
return None
def analyze_percentile_framing(data_dir: Path) -> dict:
"""
Count what % of ensemble members are below key thresholds.
Reads raw model files to access individual members.
Returns dict with model -> {timestamp -> pct_below_threshold}
"""
results = {}
thresholds = [COLD_THRESHOLD, EXTREME_COLD_THRESHOLD] # -5, -8
for model_key in ['gfs', 'ecmwf_ifs', 'ecmwf_aifs', 'gem']:
model_path = data_dir / f"{model_key}_latest.json"
if not model_path.exists():
continue
try:
with open(model_path, 'r') as f:
model_data = json.load(f)
hourly = model_data.get('hourly', {})
timestamps = hourly.get('time', [])
# Find all member columns
member_keys = [k for k in hourly.keys() if k.startswith('temperature_850hPa_member')]
if not member_keys:
continue
model_results = {'timestamps': [], 'pct_below_cold': [], 'pct_below_extreme': []}
for i, ts in enumerate(timestamps):
values = []
for key in member_keys:
if i < len(hourly[key]) and hourly[key][i] is not None:
values.append(hourly[key][i])
if values:
pct_cold = round(100 * sum(1 for v in values if v < COLD_THRESHOLD) / len(values), 0)
pct_extreme = round(100 * sum(1 for v in values if v < EXTREME_COLD_THRESHOLD) / len(values), 0)
model_results['timestamps'].append(ts)
model_results['pct_below_cold'].append(pct_cold)
model_results['pct_below_extreme'].append(pct_extreme)
results[model_key] = model_results
except Exception as e:
print(f" Percentile error for {model_key}: {e}")
continue
return results
def find_peak_percentile(percentile_data: dict) -> dict:
"""Find the peak percentile (most members below threshold) across all models.
Only considers FUTURE dates (from now onwards) - past dates are irrelevant.
"""
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
today_str = now.strftime('%Y-%m-%d')
peak = {'model': None, 'date': None, 'pct': 0, 'threshold': 'cold'}
for model_key, data in percentile_data.items():
timestamps = data.get('timestamps', [])
pct_cold = data.get('pct_below_cold', [])
pct_extreme = data.get('pct_below_extreme', [])
for i, ts in enumerate(timestamps):
date_str = ts[:10]
# Skip past dates - only report future forecasts
if date_str < today_str:
continue
# Check extreme first
if i < len(pct_extreme) and pct_extreme[i] > peak['pct']:
peak = {
'model': format_model_name(model_key),
'date': date_str,
'pct': pct_extreme[i],
'threshold': 'extreme'
}
# Then cold (only if no extreme is higher)
elif i < len(pct_cold) and pct_cold[i] > peak['pct']:
peak = {
'model': format_model_name(model_key),
'date': date_str,
'pct': pct_cold[i],
'threshold': 'cold'
}
# Only return if significant (>20% of members)
if peak['pct'] >= 20:
return peak
return None
def detect_bimodal_distribution(data_dir: Path) -> dict:
"""
Detect if ensemble shows bimodal split (2 distinct temperature clusters).
Simple approach: check if there's a gap in the distribution.
"""
results = {}
for model_key in ['gfs', 'ecmwf_ifs', 'ecmwf_aifs', 'gem']:
model_path = data_dir / f"{model_key}_latest.json"
if not model_path.exists():
continue
try:
with open(model_path, 'r') as f:
model_data = json.load(f)
hourly = model_data.get('hourly', {})
timestamps = hourly.get('time', [])
member_keys = [k for k in hourly.keys() if k.startswith('temperature_850hPa_member')]
if len(member_keys) < 10: # Need enough members for meaningful split
continue
# Check each timestamp for bimodal distribution
for i, ts in enumerate(timestamps):
values = []
for key in member_keys:
if i < len(hourly[key]) and hourly[key][i] is not None:
values.append(hourly[key][i])
if len(values) < 10:
continue
# Sort values and look for gap
sorted_vals = sorted(values)
n = len(sorted_vals)
# Find largest gap in distribution
max_gap = 0
gap_idx = 0
for j in range(1, n):
gap = sorted_vals[j] - sorted_vals[j-1]
if gap > max_gap:
max_gap = gap
gap_idx = j
# Bimodal if gap > 3°C and both clusters have meaningful membership (>25%)
if max_gap >= 3.0:
cold_cluster = sorted_vals[:gap_idx]
warm_cluster = sorted_vals[gap_idx:]
cold_pct = round(100 * len(cold_cluster) / n)
warm_pct = round(100 * len(warm_cluster) / n)
# Both clusters need at least 25% of members
if cold_pct >= 25 and warm_pct >= 25:
cold_mean = round(mean(cold_cluster), 1)
warm_mean = round(mean(warm_cluster), 1)
results[model_key] = {
'timestamp': ts,
'date': ts[:10],
'cold_pct': cold_pct,
'warm_pct': warm_pct,
'cold_mean': cold_mean,
'warm_mean': warm_mean,
'gap': round(max_gap, 1)
}
break # Take first significant bimodal instance
except Exception as e:
print(f" Bimodal error for {model_key}: {e}")
continue
return results
def track_trend_persistence(data: dict, alert_state: dict) -> dict:
"""
Track how many consecutive runs a cold/warm signal has appeared.
Updates alert_state and returns persistence info for Claude.
IMPORTANT: Only counts distinct model runs (00z/12z cycles), not
repeated script executions on the same data.
"""
runs = data.get('runs', [])
if not runs:
return None
current = runs[0]
mmm = current.get('multi_model_mean', [])
fetched_at = current.get('fetched_at', '')
if not mmm:
return None
# Determine run ID (date + 00z/12z) to avoid counting same data twice
run_label = get_run_label(fetched_at)
run_date = fetched_at[:10] if fetched_at else ''
current_run_id = f"{run_date}_{run_label}" if run_label else fetched_at[:16]
# Check if this is actually a new run
prev_run_id = alert_state.get('last_run_id', '')
is_new_run = current_run_id != prev_run_id
# Find minimum multi-model mean (coldest point in forecast)
valid_mmm = [v for v in mmm if v is not None]
if not valid_mmm:
return None
min_temp = min(valid_mmm)
max_temp = max(valid_mmm)
# Determine current signal type
current_signal = None
if min_temp < COLD_THRESHOLD:
current_signal = 'cold'
elif max_temp > WARM_THRESHOLD:
current_signal = 'warm'
# Get previous persistence state
prev_signal = alert_state.get('trend_signal', None)
prev_count = alert_state.get('trend_run_count', 0)
prev_strength = alert_state.get('trend_strength', None) # min_temp of previous run
# Calculate current strength (how far below/above threshold)
if current_signal == 'cold':
current_strength = min_temp
elif current_signal == 'warm':
current_strength = max_temp
else:
current_strength = None
result = None
if current_signal:
if current_signal == prev_signal:
# Signal persists - only increment if this is a new run
if is_new_run:
new_count = prev_count + 1
# Determine if strengthening or weakening vs previous run
if prev_strength is not None and current_strength is not None:
if current_signal == 'cold':
trend = 'strengthening' if current_strength < prev_strength else 'weakening'
else: # warm
trend = 'strengthening' if current_strength > prev_strength else 'weakening'
else:
trend = 'steady'
# Update state for new run
alert_state['trend_run_count'] = new_count
alert_state['trend_strength'] = current_strength
alert_state['last_run_id'] = current_run_id
else:
# Same run - keep existing count and trend
new_count = prev_count
trend = 'steady' # Can't determine trend within same run
result = {
'signal': current_signal,
'run_count': new_count,
'trend': trend,
'strength': current_strength
}
else:
# New signal or signal changed - always reset
result = {
'signal': current_signal,
'run_count': 1,
'trend': 'new',
'strength': current_strength
}
alert_state['trend_signal'] = current_signal
alert_state['trend_run_count'] = 1
alert_state['trend_strength'] = current_strength
alert_state['last_run_id'] = current_run_id
else:
# No signal - reset
if prev_signal:
result = {
'signal': 'neutral',
'run_count': 0,
'trend': 'cleared',
'prev_signal': prev_signal
}
alert_state['trend_signal'] = None
alert_state['trend_run_count'] = 0
alert_state['trend_strength'] = None
alert_state['last_run_id'] = current_run_id
return result
def calculate_timing_uncertainty(data: dict) -> dict:
"""
When models agree on event but disagree on timing.
Find when each model first crosses threshold and calculate spread.
"""
runs = data.get('runs', [])
if not runs:
return None
current = runs[0]
models = current.get('models', {})
timestamps = current.get('timestamps', [])
if len(models) < 2 or not timestamps:
return None
# Find when each model first crosses cold threshold
cold_crossings = {}
for model_key, model_data in models.items():
means = model_data.get('mean', [])
for i, val in enumerate(means):
if val is not None and val < COLD_THRESHOLD:
if i < len(timestamps):
cold_crossings[model_key] = {
'timestamp': timestamps[i],
'index': i,
'temp': val
}
break
# Need at least 2 models to cross for comparison
if len(cold_crossings) < 2:
return None
# Calculate timing spread
indices = [v['index'] for v in cold_crossings.values()]
min_idx = min(indices)
max_idx = max(indices)
# Each index is 12 hours (compact history uses 12-hourly data)
spread_hours = (max_idx - min_idx) * 12
# Only report if spread > 24 hours
if spread_hours <= 24:
return None
# Find earliest and latest crossing
earliest = min(cold_crossings.items(), key=lambda x: x[1]['index'])
latest = max(cold_crossings.items(), key=lambda x: x[1]['index'])
# Calculate middle date
earliest_ts = earliest[1]['timestamp']
latest_ts = latest[1]['timestamp']
try:
earliest_dt = datetime.fromisoformat(earliest_ts.replace('Z', '+00:00'))
latest_dt = datetime.fromisoformat(latest_ts.replace('Z', '+00:00'))
mid_dt = earliest_dt + (latest_dt - earliest_dt) / 2
mid_date = mid_dt.strftime('%b %d')
except:
mid_date = earliest_ts[:10]
spread_days = spread_hours / 24
return {
'event': 'cold',
'threshold': COLD_THRESHOLD,
'mid_date': mid_date,
'spread_days': round(spread_days, 1),
'earliest_model': format_model_name(earliest[0]),
'earliest_date': earliest[1]['timestamp'][:10],
'latest_model': format_model_name(latest[0]),
'latest_date': latest[1]['timestamp'][:10],
'models_crossing': len(cold_crossings),
'models_total': len(models)
}
def _runs_to_duration(runs: int, runs_per_day: float = 2) -> str:
"""Convert run count to human-readable duration."""
days = runs / runs_per_day
if days < 2:
return "since yesterday"
elif days < 5:
return f"~{int(round(days))} days"
elif days < 10:
return "~1 week"
elif days < 17:
return "~2 weeks"
else:
weeks = int(round(days / 7))
return f"~{weeks} weeks"
def calculate_signal_strength(cold_info: dict, persistence_info: dict) -> dict:
"""
Calculate signal strength based on model agreement + run persistence.
Returns dict with:
- level: 'high_confidence' | 'strong' | 'emerging' | 'weak'
- models_agreeing: int (how many models show cold signal)
- run_count: int (consecutive runs with signal)
- label: str (human-readable label for context)
Framework:
- Locked: 4/4 models AND 5+ runs persistent
- Strong: 3-4/4 models OR 3+ runs persistent
- Emerging: 2/4 models, <3 runs
- Weak: 1/4 models or no persistence
"""
models_agreeing = 0
run_count = 0
if cold_info and cold_info.get('models'):
models_agreeing = len(cold_info['models'])
if persistence_info:
run_count = persistence_info.get('run_count', 0)
# Convert run count to duration for context
duration = _runs_to_duration(run_count) if run_count >= 4 else ""
# Determine signal level (don't expose run counts - they're noise)
if models_agreeing >= 4 and run_count >= 5:
level = 'high_confidence'
label = f"High confidence ({models_agreeing}/4 models, tracked {duration})"
elif models_agreeing >= 3 or run_count >= 3:
level = 'strong'
label = f"Strong signal ({models_agreeing}/4 models agreeing)"
elif models_agreeing >= 2:
level = 'emerging'
label = f"Emerging signal ({models_agreeing}/4 models)"
else:
level = 'weak'
label = "Weak/uncertain signal"
return {
'level': level,
'models_agreeing': models_agreeing,
'run_count': run_count,
'label': label
}
def format_timing_window(timing_info: dict, cold_info: dict) -> dict:
"""
Format timing as a date window rather than single point with ±.
Returns dict with:
- spread_label: 'tight' | 'moderate' | 'broad'
- spread_days: float
- window: str (e.g., "Jan 3-5")
- label: str (human-readable for context)
"""
if not timing_info:
# Fall back to cold_info dates if no timing spread calculated
if cold_info and cold_info.get('models'):
dates = [m['date'] for m in cold_info['models']]
unique_dates = sorted(set(dates))
if len(unique_dates) == 1:
return {
'spread_label': 'tight',
'spread_days': 0,
'window': unique_dates[0],
'label': f"Coldest period: {unique_dates[0]}"
}
else:
# Format as range
from datetime import datetime
try:
dts = [datetime.fromisoformat(d) for d in unique_dates]
start = min(dts).strftime('%b %d')
end = max(dts).strftime('%b %d')
spread = (max(dts) - min(dts)).days
except:
start = unique_dates[0]
end = unique_dates[-1]
spread = len(unique_dates)
if spread <= 1:
spread_label = 'tight'
elif spread <= 2:
spread_label = 'moderate'
else:
spread_label = 'broad'
return {
'spread_label': spread_label,
'spread_days': spread,
'window': f"{start}-{end}",
'label': f"Coldest period: {start}-{end} (±{spread} days)"
}
return None
spread_days = timing_info.get('spread_days', 0)
# Determine spread label
if spread_days <= 1:
spread_label = 'tight'
elif spread_days <= 2:
spread_label = 'moderate'
else:
spread_label = 'broad'
# Build window string from earliest/latest
earliest = timing_info.get('earliest_date', '')[:10]
latest = timing_info.get('latest_date', '')[:10]
try:
from datetime import datetime
start_dt = datetime.fromisoformat(earliest)
end_dt = datetime.fromisoformat(latest)
window = f"{start_dt.strftime('%b %d')}-{end_dt.strftime('%b %d')}"
except:
window = f"{earliest} to {latest}"
return {
'spread_label': spread_label,
'spread_days': round(spread_days, 1),
'window': window,
'label': f"Coldest period: {window} (±{round(spread_days)} days)"
}
def calculate_confidence(data: dict) -> str: