File size: 69,593 Bytes
3656aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
"""Image gate, scale-relative geometry, and an honest intensity estimate.

This is not an operational forecast. A single infrared frame cannot
forecast landfall. Confidence is uncalibrated unless a matching
real-data run record includes a coverage check or a held-out storm
check. The intensity category is this project's grouping on the
configured knot bins, not an official IMD class.

The network is reached only through :class:`src.model_access.ModelAccess`.
Letterboxing happens before ``src.preprocessing.prepare_image``, which
resizes a square to the checkpoint size. Southern Hemisphere frames stay
unflipped via ``src.preprocessing.leave_unflipped``.
"""

from __future__ import annotations

import json
import math
import os
from dataclasses import dataclass
from pathlib import Path

import numpy as np

from src.config import image_sizes_match, parse_image_size
from src.model_access import ModelAccess
from src.schema import wind_to_imd5

# Shared with the web demo. cloudie.app re-exports these names.
NO_TRAINED_MODEL_BANNER = (
    "No trained model yet. This page cannot produce estimates. "
    "Not a forecast or warning system. "
    "Best-track labels are noisy, and no survey or smoke number is a result of this project."
)


def research_disclaimer_banner(
    run_id: str = "",
    dataset: str = "",
    model: str = "",
) -> str:
    """Research disclaimer banner displayed when a real trained model is available."""
    details = []
    if dataset:
        details.append(f"dataset: {dataset.upper()}")
    if model:
        details.append(f"model: {model}")
    if run_id:
        details.append(f"run: {run_id}")
    spec = f" ({', '.join(details)})" if details else ""
    return (
        f"Active research prototype{spec}. "
        "Academic and retrospective evaluation only. "
        "NOT AN OPERATIONAL FORECAST OR WARNING SYSTEM. "
        "Best-track labels are noisy and model uncertainty is uncalibrated. "
        "Do not use for life-safety, emergency planning, navigation, or operational decision-making."
    )

PAGE_LEAD = "Predict cyclone wind speed and intensity category from an infrared image."
CONFIDENCE_NOTE = (
    "Confidence mixes the image gate, dropout spread, and a residual-quantile "
    "width when one exists. It is uncalibrated until a held-out storm check exists. "
    "It is not a forecast interval."
)
SCALE_NOTE = (
    "Reported winds stay between 0 and 200 kt: below depression, depression, "
    "cyclonic storm, severe, very severe, and extremely severe or super cyclonic storm. "
    "Those names are this project's grouping, not an official IMD class."
)
GROUPING_LABEL = "Project grouping"


def _section(config: dict, *keys: str):
    cursor = config
    walked: list[str] = []
    for key in keys:
        walked.append(key)
        if not isinstance(cursor, dict) or key not in cursor:
            raise ValueError(f"config {'.'.join(walked)} is required")
        cursor = cursor[key]
    return cursor


def _finite(raw, path: str) -> float:
    try:
        value = float(raw)
    except (TypeError, ValueError) as exc:
        raise ValueError(f"config {path} must be a number") from exc
    if not math.isfinite(value):
        raise ValueError(f"config {path} must be finite")
    return value


@dataclass(frozen=True)
class GateSettings:
    """Thresholds for the infrared-cyclone gate. All of them come from config."""

    refusal: str
    grayscale_tolerance: float
    min_std: float
    min_symmetry: float
    min_cold_concentration: float
    cold_radius_fraction: float
    cold_tail_fraction: float
    eye_radius_fraction: float
    eyewall_outer_fraction: float
    outer_inner_fraction: float
    outer_outer_fraction: float
    min_wall_contrast: float
    radial_bins: int
    cold_value: str
    max_dropout_std_kt: float
    concentration_reference: float

    @staticmethod
    def from_config(config: dict) -> GateSettings:
        raw = _section(config, "predict", "gate")
        settings = GateSettings(
            refusal=str(raw["refusal"]).strip(),
            grayscale_tolerance=_finite(raw["grayscale_tolerance"], "predict.gate.grayscale_tolerance"),
            min_std=_finite(raw["min_std"], "predict.gate.min_std"),
            min_symmetry=_finite(raw["min_symmetry"], "predict.gate.min_symmetry"),
            min_cold_concentration=_finite(
                raw["min_cold_concentration"], "predict.gate.min_cold_concentration"
            ),
            cold_radius_fraction=_finite(
                raw["cold_radius_fraction"], "predict.gate.cold_radius_fraction"
            ),
            cold_tail_fraction=_finite(raw["cold_tail_fraction"], "predict.gate.cold_tail_fraction"),
            eye_radius_fraction=_finite(raw["eye_radius_fraction"], "predict.gate.eye_radius_fraction"),
            eyewall_outer_fraction=_finite(
                raw["eyewall_outer_fraction"], "predict.gate.eyewall_outer_fraction"
            ),
            outer_inner_fraction=_finite(raw["outer_inner_fraction"], "predict.gate.outer_inner_fraction"),
            outer_outer_fraction=_finite(raw["outer_outer_fraction"], "predict.gate.outer_outer_fraction"),
            min_wall_contrast=_finite(raw["min_wall_contrast"], "predict.gate.min_wall_contrast"),
            radial_bins=int(raw["radial_bins"]),
            cold_value=str(raw["cold_value"]).strip(),
            max_dropout_std_kt=_finite(raw["max_dropout_std_kt"], "predict.gate.max_dropout_std_kt"),
            concentration_reference=_finite(
                raw["concentration_reference"], "predict.gate.concentration_reference"
            ),
        )
        if not settings.refusal:
            raise ValueError("config predict.gate.refusal is empty")
        if settings.cold_value not in {"auto", "low", "high"}:
            raise ValueError("config predict.gate.cold_value must be auto, low, or high")
        if settings.radial_bins < 2:
            raise ValueError("config predict.gate.radial_bins must be at least 2")
        if settings.concentration_reference <= 0:
            raise ValueError("config predict.gate.concentration_reference must be positive")
        if settings.max_dropout_std_kt <= 0:
            raise ValueError("config predict.gate.max_dropout_std_kt must be positive")
        radii = (
            settings.eye_radius_fraction,
            settings.eyewall_outer_fraction,
            settings.outer_inner_fraction,
            settings.outer_outer_fraction,
        )
        if not (0 < radii[0] < radii[1] < radii[2] < radii[3] <= 1):
            raise ValueError("config predict.gate radii must increase and stay within (0, 1]")
        if not 0 < settings.cold_radius_fraction <= 1:
            raise ValueError("config predict.gate.cold_radius_fraction must be in (0, 1]")
        if not 0 < settings.cold_tail_fraction < 0.5:
            raise ValueError("config predict.gate.cold_tail_fraction must be in (0, 0.5)")
        if settings.min_std < 0:
            raise ValueError("config predict.gate.min_std must be >= 0")
        return settings


@dataclass(frozen=True)
class GateReport:
    """One frame's gate. ``score`` is 0 when the frame is refused."""

    accepted: bool
    reason: str
    score: float
    field: np.ndarray | None
    symmetry: float | None = None
    cold_concentration: float | None = None
    wall_contrast: float | None = None
    eye_contrast: float | None = None
    polarity: str | None = None

    def feature_map(self) -> dict[str, float]:
        """Scale-relative summaries. None of these are pixel counts."""
        return {
            "symmetry": 0.0 if self.symmetry is None else float(self.symmetry),
            "cold_concentration": (
                0.0 if self.cold_concentration is None else float(self.cold_concentration)
            ),
            "wall_contrast": 0.0 if self.wall_contrast is None else float(self.wall_contrast),
            "eye_contrast": 0.0 if self.eye_contrast is None else float(self.eye_contrast),
        }


class FrameGeometry:
    """Pad a frame to a square without stretching it.

    ``prepare_image`` then resizes that square to the checkpoint size.
    A square input is returned unchanged, so the resize is the only resample.
    """

    @staticmethod
    def mode(config: dict) -> str:
        mode = str(_section(config, "data", "resize")).strip()
        if mode not in {"letterbox", "stretch"}:
            raise ValueError("config data.resize must be letterbox or stretch")
        return mode

    @staticmethod
    def pad_square(image: np.ndarray, pad: str) -> np.ndarray:
        """Return a square view of one channel. ``pad`` is ``median``."""
        if pad != "median":
            raise ValueError("config data.pad must be median")
        array = np.asarray(image, dtype=np.float32)
        if array.ndim != 2:
            raise ValueError("letterbox expects one infrared channel")
        height, width = array.shape
        if height == width:
            return array
        side = max(height, width)
        finite = array[np.isfinite(array)]
        fill = float(np.median(finite)) if finite.size else 0.0
        canvas = np.full((side, side), fill, dtype=np.float32)
        top = (side - height) // 2
        left = (side - width) // 2
        canvas[top : top + height, left : left + width] = array
        return canvas


class CycloneImageGate:
    """Decide whether a frame is a plausible tropical-cyclone infrared image.

    The checks are a single greyscale channel, a cold core relative to the
    frame, and radial organization. A colour-enhanced RGB or RGBA frame is
    refused before those checks. Radii are fractions of the half-width.
    Model uncertainty is applied later by :meth:`uncertainty_reason`. A
    refusal is not a wind speed.
    """

    @staticmethod
    def uncertainty_reason(std_kt: float | None, settings: GateSettings) -> str | None:
        """Refuse when dropout spread exceeds the configured limit."""
        if std_kt is None:
            return None
        if float(std_kt) > settings.max_dropout_std_kt:
            return (
                f"model uncertainty {float(std_kt):.1f} kt exceeds the configured "
                f"limit of {settings.max_dropout_std_kt:.0f} kt"
            )
        return None

    @staticmethod
    def assess(image: np.ndarray, settings: GateSettings) -> GateReport:
        planes, channel_reason = CycloneImageGate._planes(image, settings)
        if channel_reason is not None:
            return GateReport(False, channel_reason, 0.0, None)
        field = np.mean(np.stack(planes, axis=0), axis=0).astype(np.float64)
        finite = field[np.isfinite(field)]
        if finite.size == 0:
            return GateReport(False, "the frame has no finite pixels", 0.0, None)
        spread = float(finite.std())
        if spread < settings.min_std:
            return GateReport(
                False,
                f"the frame is too flat to be an infrared cyclone (std {spread:.4f})",
                0.0,
                field,
            )
        candidates = CycloneImageGate._candidates(field, settings)
        passing = [item for item in candidates if item[0]]
        chosen = max(passing or candidates, key=lambda item: item[1])
        accepted, score, reason, metrics, polarity = chosen
        return GateReport(
            accepted=accepted,
            reason=reason,
            score=score if accepted else 0.0,
            field=field,
            symmetry=metrics["symmetry"],
            cold_concentration=metrics["cold_concentration"],
            wall_contrast=metrics["wall_contrast"],
            eye_contrast=metrics["eye_contrast"],
            polarity=polarity,
        )

    @staticmethod
    def _planes(image: np.ndarray, settings: GateSettings) -> tuple[list[np.ndarray], str | None]:
        array = np.asarray(image)
        if array.ndim == 2:
            return [np.asarray(array, dtype=np.float64)], None
        if array.ndim != 3:
            return [], f"the array shape {array.shape} is not an infrared frame"
        if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4:
            planes = [np.asarray(array[index], dtype=np.float64) for index in range(array.shape[0])]
        elif array.shape[-1] <= 4 and array.shape[0] > 4 and array.shape[1] > 4:
            planes = [np.asarray(array[..., index], dtype=np.float64) for index in range(array.shape[-1])]
        else:
            return [], f"the array shape {array.shape} is not an infrared frame"
        if len(planes) == 1:
            return planes, None
        if len(planes) not in (3, 4):
            return [], "the frame is not a single infrared channel"
        # Four planes are RGB plus alpha. Alpha is not a colour channel.
        colour = planes[:3]
        reason = CycloneImageGate._colour_reason(colour, settings)
        if reason is not None:
            return [], reason
        return colour, None

    @staticmethod
    def _colour_reason(planes: list[np.ndarray], settings: GateSettings) -> str | None:
        """Refuse a false-colour enhancement. Near-copies stay greyscale IR."""
        mean = np.mean(np.stack(planes, axis=0), axis=0)
        finite = mean[np.isfinite(mean)]
        if finite.size == 0:
            return "the frame has no finite pixels"
        low, high = np.percentile(finite, [5, 95])
        scale = max(float(high - low), 1e-6)
        pair_gaps = [
            float(np.mean(np.abs(planes[i] - planes[j])))
            for i in range(3)
            for j in range(i + 1, 3)
        ]
        ratio = float(np.mean(pair_gaps)) / scale
        if ratio > settings.grayscale_tolerance:
            return (
                "the frame is colour-enhanced rather than greyscale infrared "
                f"(relative channel spread {ratio:.2f})"
            )
        return None

    @staticmethod
    def _candidates(field: np.ndarray, settings: GateSettings) -> list[tuple]:
        if settings.cold_value == "low":
            signed = [(field, "low")]
        elif settings.cold_value == "high":
            signed = [(-field, "high")]
        else:
            signed = [(field, "low"), (-field, "high")]
        reports = []
        for values, polarity in signed:
            reports.append(CycloneImageGate._score_field(values, polarity, settings))
        return reports

    @staticmethod
    def _score_field(field: np.ndarray, polarity: str, settings: GateSettings) -> tuple:
        finite = np.isfinite(field)
        values = field[finite]
        low, high = np.percentile(values, [5, 95])
        scale = max(float(high - low), 1e-6)
        scaled = (field - float(np.median(values))) / scale
        height, width = scaled.shape
        yy, xx = np.mgrid[0:height, 0:width]
        half = min(height, width) / 2.0
        radius = np.hypot(yy - (height - 1) / 2.0, xx - (width - 1) / 2.0) / max(half, 1e-6)
        symmetry = CycloneImageGate._symmetry(scaled, radius, finite, settings.radial_bins)
        tail = float(np.percentile(scaled[finite], settings.cold_tail_fraction * 100.0))
        cold = finite & (scaled <= tail)
        core = radius <= settings.cold_radius_fraction
        concentration = float(cold[core].sum() / max(int(cold.sum()), 1))
        wall_mask = (radius > settings.eye_radius_fraction) & (
            radius <= settings.eyewall_outer_fraction
        )
        outer_mask = (radius > settings.outer_inner_fraction) & (
            radius <= settings.outer_outer_fraction
        )
        eye_mask = radius <= settings.eye_radius_fraction
        wall_mean = CycloneImageGate._masked_mean(scaled, wall_mask & finite)
        outer_mean = CycloneImageGate._masked_mean(scaled, outer_mask & finite)
        eye_mean = CycloneImageGate._masked_mean(scaled, eye_mask & finite)
        wall_contrast = (
            None if wall_mean is None or outer_mean is None else outer_mean - wall_mean
        )
        eye_contrast = None if eye_mean is None or wall_mean is None else eye_mean - wall_mean
        metrics = {
            "symmetry": symmetry,
            "cold_concentration": concentration,
            "wall_contrast": wall_contrast,
            "eye_contrast": eye_contrast,
        }
        failures: list[str] = []
        if symmetry is None or symmetry < settings.min_symmetry:
            shown = "missing" if symmetry is None else f"{symmetry:.2f}"
            failures.append(f"radial symmetry {shown} is below {settings.min_symmetry:.2f}")
        if concentration < settings.min_cold_concentration:
            failures.append(
                "cold-cloud concentration "
                f"{concentration:.2f} is below {settings.min_cold_concentration:.2f}"
            )
        if wall_contrast is None or wall_contrast < settings.min_wall_contrast:
            shown = "missing" if wall_contrast is None else f"{wall_contrast:.2f}"
            failures.append(f"cold-core contrast {shown} is below {settings.min_wall_contrast:.2f}")
        score = CycloneImageGate._score(symmetry, concentration, wall_contrast, settings)
        if failures:
            reason = "; ".join(failures) + f" ({polarity} values treated as cold)"
            return False, score, reason, metrics, polarity
        reason = (
            "cold cloud is radially organized "
            f"({polarity} values treated as cold)"
        )
        return True, score, reason, metrics, polarity

    @staticmethod
    def _symmetry(scaled, radius, finite, radial_bins: int) -> float | None:
        inside = finite & (radius <= 1)
        if int(inside.sum()) < 8:
            return None
        edges = np.linspace(0.0, 1.0, int(radial_bins) + 1)
        residual = np.zeros(scaled.shape, dtype=np.float64)
        for index in range(int(radial_bins)):
            mask = inside & (radius >= edges[index]) & (radius < edges[index + 1])
            if int(mask.sum()) == 0:
                continue
            residual[mask] = scaled[mask] - float(scaled[mask].mean())
        variance = float(scaled[inside].var())
        if variance <= 1e-8:
            return 1.0
        return float(1.0 - residual[inside].var() / variance)

    @staticmethod
    def _masked_mean(scaled, mask) -> float | None:
        if int(mask.sum()) == 0:
            return None
        return float(scaled[mask].mean())

    @staticmethod
    def _score(symmetry, concentration, wall_contrast, settings: GateSettings) -> float:
        if symmetry is None or wall_contrast is None:
            return 0.0
        return float(
            np.clip(
                min(
                    1.0,
                    max(float(symmetry), 0.0),
                    max(float(wall_contrast), 0.0),
                    max(float(concentration), 0.0) / settings.concentration_reference,
                ),
                0.0,
                1.0,
            )
        )


class ConfidenceScore:
    """Gate score, dropout spread, and residual quantiles when a checkpoint has them.

    ``src.evaluate`` stores a residual-quantile interval as the validation
    quantile of ``|residual|``. That value is a half-width. The full width
    used here is twice that half-width. A ``low_kt`` / ``high_kt`` pair is
    the older full span and is used only when no evaluate levels are present.

    The label stays ``uncalibrated`` unless a matching real-data run record
    carries a coverage check or a held-out storm check whose quoted level
    is ``within_tolerance``. This is not a prediction interval and it is
    not an operational calibration claim.
    """

    @staticmethod
    def source(payload: dict, record: dict | None):
        """Quantile payload for the blend. The run record is the second choice."""
        candidates = []
        if isinstance(payload, dict):
            candidates.append(payload.get("residual_quantiles"))
            candidates.append(payload.get("uncertainty"))
        if isinstance(record, dict):
            candidates.append(record.get("residual_quantiles"))
            candidates.append(record.get("uncertainty"))
        for candidate in candidates:
            if ConfidenceScore.interval_width(candidate) is not None:
                return candidate
        return None

    @staticmethod
    def interval_width(raw) -> float | None:
        half = ConfidenceScore._half_width(raw)
        if half is not None:
            return 2.0 * half
        if not isinstance(raw, dict) or "low_kt" not in raw or "high_kt" not in raw:
            return None
        low = _finite(raw["low_kt"], "residual_quantiles.low_kt")
        high = _finite(raw["high_kt"], "residual_quantiles.high_kt")
        if high < low:
            return None
        return high - low

    @staticmethod
    def _level_rows(raw) -> dict | None:
        """Rows from ``report['uncertainty']['residual_quantile']['levels']``."""
        if not isinstance(raw, dict):
            return None
        uncertainty = raw.get("uncertainty")
        if isinstance(uncertainty, dict):
            found = ConfidenceScore._level_rows(uncertainty.get("residual_quantile"))
            if found:
                return found
        for key in ("residual_quantile", "residual_quantiles"):
            nested = raw.get(key)
            if isinstance(nested, dict):
                found = ConfidenceScore._level_rows(nested)
                if found:
                    return found
        levels = raw.get("levels")
        if isinstance(levels, dict):
            found = ConfidenceScore._level_rows(levels)
            if found:
                return found
        rows = {
            str(key): value
            for key, value in raw.items()
            if isinstance(value, dict) and "absolute_residual_quantile_kt" in value
        }
        return rows or None

    @staticmethod
    def _quantile_block(raw) -> dict | None:
        """The evaluate residual-quantile object, including its storm lists."""
        if not isinstance(raw, dict):
            return None
        uncertainty = raw.get("uncertainty")
        if isinstance(uncertainty, dict):
            found = ConfidenceScore._quantile_block(uncertainty)
            if found is not None:
                return found
        for key in ("residual_quantile", "residual_quantiles"):
            nested = raw.get(key)
            if isinstance(nested, dict):
                found = ConfidenceScore._quantile_block(nested)
                if found is not None:
                    return found
        levels = raw.get("levels")
        if isinstance(levels, dict) and ConfidenceScore._level_rows(levels):
            return raw
        if ConfidenceScore._level_rows(raw):
            return raw
        return None

    @staticmethod
    def _chosen_row(rows: dict) -> dict | None:
        """Highest nominal level. That is the interval this score quotes."""
        chosen = None
        nominal = None
        for row in rows.values():
            if not isinstance(row, dict):
                continue
            try:
                level = float(row.get("nominal", 0.0))
                half = float(row["absolute_residual_quantile_kt"])
            except (TypeError, ValueError):
                continue
            if not math.isfinite(level) or not math.isfinite(half) or half < 0:
                continue
            if nominal is None or level > nominal:
                nominal = level
                chosen = row
        return chosen

    @staticmethod
    def _half_width(raw) -> float | None:
        rows = ConfidenceScore._level_rows(raw)
        if not rows:
            return None
        chosen = ConfidenceScore._chosen_row(rows)
        if chosen is None:
            return None
        return float(chosen["absolute_residual_quantile_kt"])

    @staticmethod
    def combine(
        config: dict,
        gate_score: float,
        dropout_std: float | None,
        residual_quantiles,
    ) -> float:
        cfg = _section(config, "predict", "confidence")
        weights = {
            "gate": _finite(cfg["gate_weight"], "predict.confidence.gate_weight"),
            "mc": _finite(cfg["mc_weight"], "predict.confidence.mc_weight"),
            "interval": _finite(cfg["interval_weight"], "predict.confidence.interval_weight"),
        }
        if min(weights.values()) <= 0:
            raise ValueError("config predict.confidence weights must be positive")
        terms = [(weights["gate"], float(np.clip(gate_score, 0.0, 1.0)))]
        if dropout_std is not None:
            scale = _finite(cfg["mc_std_scale_kt"], "predict.confidence.mc_std_scale_kt")
            if scale <= 0:
                raise ValueError("config predict.confidence.mc_std_scale_kt must be positive")
            terms.append((weights["mc"], 1.0 / (1.0 + float(dropout_std) / scale)))
        width = ConfidenceScore.interval_width(residual_quantiles)
        if width is not None:
            scale = _finite(cfg["interval_scale_kt"], "predict.confidence.interval_scale_kt")
            if scale <= 0:
                raise ValueError("config predict.confidence.interval_scale_kt must be positive")
            interval = float(np.clip(1.0 - width / scale, 0.0, 1.0))
            terms.append((weights["interval"], interval))
        total = sum(weight for weight, _value in terms)
        score = sum(weight * value for weight, value in terms) / total
        return float(np.clip(score, 0.0, 1.0))

    @staticmethod
    def status(config: dict, record: dict | None) -> str:
        cfg = _section(config, "predict", "confidence")
        uncalibrated = str(cfg["uncalibrated_label"]).strip()
        recorded = str(cfg["coverage_label"]).strip()
        if not isinstance(record, dict):
            return uncalibrated
        if ConfidenceScore._coverage_recorded(record):
            return recorded
        if ConfidenceScore._held_out_storm_check(record):
            return recorded
        return uncalibrated

    @staticmethod
    def _coverage_recorded(record: dict) -> bool:
        check = record.get("coverage_check")
        if not isinstance(check, dict) or check.get("real_data") is not True:
            return False
        try:
            count = int(check["n"])
            nominal = float(check["nominal"])
            observed = float(check["observed"])
        except (KeyError, TypeError, ValueError):
            return False
        return count >= 1 and math.isfinite(nominal) and math.isfinite(observed)

    @staticmethod
    def _held_out_storm_check(record: dict) -> bool:
        """True when evaluate scored residual quantiles on held-out storms.

        Half-widths alone do not count. The block has to name test storms,
        the quoted level has to be ``within_tolerance``, and the report
        must not be synthetic. The label is still the coverage label, not
        ``calibrated``.
        """
        block = ConfidenceScore._quantile_block(record)
        if not isinstance(block, dict):
            return False
        if str(block.get("eval_split", "")).strip() != "test":
            return False
        storms = block.get("test_storms")
        if not isinstance(storms, (list, tuple)) or not storms:
            return False
        if not all(str(storm).strip() for storm in storms):
            return False
        synthetic = record.get("synthetic", block.get("synthetic"))
        if synthetic in {"yes", "mixed", True}:
            return False
        rows = ConfidenceScore._level_rows(block)
        if not rows:
            return False
        chosen = ConfidenceScore._chosen_row(rows)
        if chosen is None or str(chosen.get("status", "")).strip() != "within_tolerance":
            return False
        if chosen.get("eval_split") not in (None, "test"):
            return False
        try:
            count = int(float(chosen["n"]))
        except (KeyError, TypeError, ValueError):
            return False
        return count >= 1

    @staticmethod
    def _held_out_test_evaluated(record: dict) -> bool:
        """True when a real run has completed a non-synthetic held-out test evaluation.

        Allows model prediction even when residual-quantile empirical coverage is
        outside tolerance (in which case the interval is labeled uncalibrated).
        """
        if not isinstance(record, dict):
            return False
        synthetic = record.get("synthetic", record.get("is_synthetic"))
        if synthetic in {"yes", "mixed", True}:
            return False

        block = ConfidenceScore._quantile_block(record)
        if isinstance(block, dict):
            if str(block.get("eval_split", "")).strip() != "test":
                return False
            storms = block.get("test_storms")
            if not isinstance(storms, (list, tuple)) or not storms:
                return False
            if not all(str(storm).strip() for storm in storms):
                return False
            block_syn = record.get("synthetic", block.get("synthetic"))
            if block_syn in {"yes", "mixed", True}:
                return False
            rows = ConfidenceScore._level_rows(block)
            if rows:
                chosen = ConfidenceScore._chosen_row(rows)
                if chosen is not None and chosen.get("eval_split") in (None, "test"):
                    try:
                        count = int(float(chosen["n"]))
                        if count >= 1:
                            return True
                    except (KeyError, TypeError, ValueError):
                        pass

        test_block = record.get("test")
        if (
            isinstance(test_block, dict)
            and test_block.get("scored", True) is not False
            and test_block.get("eval_split") == "test"
        ):
            try:
                count = int(float(test_block.get("n", 0)))
                if count >= 1:
                    return True
            except (KeyError, TypeError, ValueError):
                pass
        return False


class IntensityGrouping:
    """Project bins. The names are not an official IMD class."""

    @staticmethod
    def note(config: dict) -> str:
        return str(_section(config, "data", "grouping_note")).strip()

    @staticmethod
    def code(wind_kt: float, edges: tuple[float, ...], names: tuple[str, ...]) -> str | None:
        return wind_to_imd5(float(wind_kt), edges, names)


class RunRecord:
    """A checkpoint may be shown only when a real-data record matches it.

    A synthetic checkpoint is always flagged. A checkpoint that claims to
    be real and has no matching record produces no wind speed.
    """

    @staticmethod
    def load_match(config: dict, payload: dict) -> tuple[bool, dict | None]:
        run_id = payload.get("run_id")
        if run_id in (None, ""):
            return False, None
        run_id = str(run_id)
        if "/" in run_id or "\\" in run_id or ".." in run_id:
            return False, None
        record = RunRecord._legacy_record(config, run_id)
        if record is None:
            record = RunRecord._run_directory_record(config, run_id)
        if record is None:
            record = RunRecord._active_directory_record(config, run_id)
        if record is None:
            return False, None
        normalized = RunRecord._normalize(record, payload)
        if str(normalized.get("run_id")) != run_id:
            return False, None
        if bool(normalized.get("is_synthetic", True)):
            return False, None
        if str(normalized.get("data_kind")) != "real":
            return False, None
        try:
            same_model = str(normalized.get("model_name")) == str(payload.get("model_name"))
            same_size = image_sizes_match(normalized.get("image_size"), payload.get("image_size"))
        except (TypeError, ValueError):
            return False, None
        if not same_model or not same_size:
            return False, None
        return True, normalized

    @staticmethod
    def _read_json(path: Path) -> dict | None:
        if not path.is_file():
            return None
        try:
            record = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError, UnicodeError):
            return None
        if not isinstance(record, dict):
            return None
        return record

    @staticmethod
    def _legacy_record(config: dict, run_id: str) -> dict | None:
        paths = config.get("paths")
        if not isinstance(paths, dict) or "run_records" not in paths:
            return None
        return RunRecord._read_json(Path(paths["run_records"]) / f"{run_id}.json")

    @staticmethod
    def _run_directory_record(config: dict, run_id: str) -> dict | None:
        """``paths.runs/<run_id>/metrics.json`` from ``src.train.run_training``."""
        paths = config.get("paths")
        if not isinstance(paths, dict) or not paths.get("runs"):
            return None
        return RunRecord._read_json(Path(paths["runs"]) / run_id / "metrics.json")

    @staticmethod
    def _active_directory_record(config: dict, run_id: str) -> dict | None:
        """A Hub snapshot of one run directory, set in memory by :class:`RunCheckpoint`."""
        paths = config.get("paths")
        if not isinstance(paths, dict) or not paths.get("active_run_dir"):
            return None
        return RunRecord._read_json(Path(paths["active_run_dir"]) / "metrics.json")

    @staticmethod
    def _normalize(record: dict, payload: dict) -> dict:
        normalized = dict(record)
        if not normalized.get("model_name") and normalized.get("model"):
            normalized["model_name"] = normalized.get("model")
        if "image_size" not in normalized:
            normalized["image_size"] = payload.get("image_size")
        if not normalized.get("data_kind"):
            dataset = str(normalized.get("dataset", "")).strip().lower()
            real_run = (
                dataset in {"nasa", "tcir", "incyde"}
                and normalized.get("is_synthetic") is False
                and (
                    normalized.get("result") is True
                    or normalized.get("scored") is True
                    or "residual_quantiles" in normalized
                    or "test" in normalized
                )
            )
            if real_run or (
                normalized.get("is_synthetic") is False
                and (normalized.get("eval_split") == "test" or "residual_quantiles" in normalized)
            ):
                normalized["data_kind"] = "real"
        return normalized

    @staticmethod
    def _with_active(config: dict, directory: Path) -> dict:
        prepared = dict(config)
        prepared["paths"] = dict(config.get("paths") or {})
        prepared["paths"]["active_run_dir"] = str(directory)
        for cfg_name in ("resolved_config.yaml", "config.yaml"):
            cfg_path = directory / cfg_name
            if cfg_path.is_file():
                try:
                    import yaml

                    saved = yaml.safe_load(cfg_path.read_text(encoding="utf-8"))
                    if isinstance(saved, dict):
                        for k, v in saved.items():
                            if k not in prepared or not isinstance(prepared[k], dict) or not isinstance(v, dict):
                                prepared[k] = v
                            else:
                                merged = dict(prepared[k])
                                merged.update(v)
                                prepared[k] = merged
                    break
                except Exception:
                    pass
        metrics_path = directory / "metrics.json"
        if metrics_path.is_file():
            try:
                m_data = json.loads(metrics_path.read_text(encoding="utf-8"))
                if isinstance(m_data, dict):
                    m_model = m_data.get("model") or m_data.get("model_name")
                    if m_model:
                        prepared.setdefault("model", {})
                        if isinstance(prepared["model"], dict):
                            prepared["model"]["name"] = str(m_model)
            except Exception:
                pass
        return prepared


class CoastalContext:
    """Nearest configured coastal reference points. Not a landfall forecast."""

    @staticmethod
    def describe(config: dict, latitude, longitude, metadata) -> tuple:
        position = CoastalContext.position(config, latitude, longitude, metadata)
        if position is None:
            return None, None, None
        lat, lon = position
        count = int(_section(config, "predict", "coastal_count"))
        if count < 1:
            raise ValueError("config predict.coastal_count must be at least 1")
        radius = _finite(_section(config, "predict", "earth_radius_km"), "predict.earth_radius_km")
        places = _section(config, "predict", "coast")
        if not isinstance(places, list) or not places:
            raise ValueError("config predict.coast must list reference points")
        ranked = sorted(
            (
                (
                    CoastalContext.distance_km(lat, lon, float(place["lat"]), float(place["lon"]), radius),
                    str(place["name"]),
                )
                for place in places
            ),
            key=lambda item: item[0],
        )
        names = tuple(name for _distance, name in ranked[:count])
        note = str(_section(config, "predict", "landfall_note")).strip()
        reference = str(_section(config, "predict", "coast_reference_note")).strip()
        return names, note, reference

    @staticmethod
    def position(config: dict, latitude, longitude, metadata) -> tuple[float, float] | None:
        meta = metadata or {}
        lat = latitude
        lon = longitude
        if lat is None:
            for key in _section(config, "predict", "latitude_keys"):
                if key in meta and meta[key] is not None:
                    lat = meta[key]
                    break
        if lon is None:
            for key in _section(config, "predict", "longitude_keys"):
                if key in meta and meta[key] is not None:
                    lon = meta[key]
                    break
        if lat is None and lon is None:
            return None
        if lat is None or lon is None:
            raise ValueError("latitude and longitude must be supplied together")
        lat_f = float(lat)
        lon_f = float(lon)
        if not (-90.0 <= lat_f <= 90.0 and -180.0 <= lon_f <= 180.0):
            raise ValueError("latitude or longitude is outside the geographic range")
        return lat_f, lon_f

    @staticmethod
    def distance_km(lat1: float, lon1: float, lat2: float, lon2: float, radius_km: float) -> float:
        phi1, phi2 = math.radians(lat1), math.radians(lat2)
        d_phi = math.radians(lat2 - lat1)
        d_lon = math.radians(lon2 - lon1)
        haversine = (
            math.sin(d_phi / 2.0) ** 2
            + math.cos(phi1) * math.cos(phi2) * math.sin(d_lon / 2.0) ** 2
        )
        return 2.0 * radius_km * math.asin(min(1.0, math.sqrt(haversine)))


class CheckpointStore:
    """Load a ``.pt`` state dict or a ``.joblib`` estimator. No other suffix."""

    @staticmethod
    def load(path: Path) -> dict:
        if path.suffix == ".joblib":
            import joblib

            payload = joblib.load(path)
            if not isinstance(payload, dict) or "estimator" not in payload:
                raise ValueError("joblib checkpoint must be a dict with an estimator")
            loaded = dict(payload)
            loaded["_kind"] = "sklearn"
            return loaded
        if path.suffix == ".pt":
            import torch

            try:
                payload = torch.load(path, map_location="cpu", weights_only=False)
            except TypeError:
                payload = torch.load(path, map_location="cpu")
            if not isinstance(payload, dict):
                raise ValueError("torch checkpoint must be a dict")
            loaded = dict(payload)
            loaded["_kind"] = "torch"
            return loaded
        raise ValueError("checkpoint must be a .pt or .joblib file")


@dataclass(frozen=True)
class Estimate:
    """What ``predict_images`` turns into a :class:`cloudie.predict.Prediction`."""

    outcome: str
    banner: str
    is_synthetic: bool
    wind_kt: float | None = None
    wind_kmh: float | None = None
    dropout_std_kt: float | None = None
    samples: tuple[float, ...] = ()
    confidence: float | None = None
    confidence_status: str | None = None
    grouping_note: str | None = None
    operational_disclaimer: str | None = None
    coastal_heading: str | None = None
    nearest_coastal_states: tuple[str, ...] | None = None
    landfall_note: str | None = None
    coast_reference_note: str | None = None
    gate_reason: str | None = None
    gate_score: float | None = None
    matched_run: bool = False
    outside_training: bool = False
    wind_averaging: str | None = None
    edges: tuple[float, ...] = ()
    names: tuple[str, ...] = ()
    honesty: str | None = None


class IntensityEstimate:
    """Run the gate, then the checkpoint, and refuse a wind when either fails.

    This is not an operational forecast. Dropout spread and residual
    quantiles are not a calibrated interval. Nearest coastal states are
    context for a supplied position, not a landfall forecast.
    """

    @staticmethod
    def predict(
        config: dict,
        path: Path,
        images: list[np.ndarray],
        *,
        hemisphere: str | None,
        latitude,
        longitude,
        metadata,
    ) -> Estimate:
        ctx = IntensityEstimate._context(config, latitude, longitude, metadata)
        payload = CheckpointStore.load(path)
        IntensityEstimate._check_identity(config, payload)
        synthetic = bool(payload.get("is_synthetic"))
        matched, record = RunRecord.load_match(config, payload)
        if synthetic:
            matched, record = False, None
        expected = int(payload.get("n_frames", 1))
        if len(images) != expected:
            banner = (
                f"This checkpoint expects {expected} infrared frames and received "
                f"{len(images)}. There is no model output. This is not a forecast."
            )
            return Estimate("frame_count", banner, synthetic, matched_run=matched, **ctx)
        frames = IntensityEstimate._unflipped(images, hemisphere)
        missing = IntensityEstimate._missing_fraction(frames, float(payload["max_missing_fraction"]))
        if missing is not None:
            return Estimate("missing_pixels", "", synthetic, matched_run=matched, **ctx)
        settings = GateSettings.from_config(config)
        reports = [CycloneImageGate.assess(frame, settings) for frame in frames]
        refused = next((report for report in reports if not report.accepted), None)
        if refused is not None:
            return Estimate(
                "not_cyclone",
                IntensityEstimate._gate_banner(settings, refused.reason),
                synthetic,
                gate_reason=refused.reason,
                gate_score=refused.score,
                matched_run=matched,
                **ctx,
            )
        if not synthetic and not matched:
            banner = str(_section(config, "predict", "no_run_record_refusal")).strip()
            return Estimate("no_run_record", banner, synthetic, matched_run=False, **ctx)
        prepared = IntensityEstimate._prepare(config, payload, reports)
        wind_kt, samples, std_kt = IntensityEstimate._wind(config, payload, prepared, reports)
        uncertain = CycloneImageGate.uncertainty_reason(std_kt, settings)
        if uncertain is not None:
            return Estimate(
                "not_cyclone",
                IntensityEstimate._gate_banner(settings, uncertain),
                synthetic,
                gate_reason=uncertain,
                matched_run=matched,
                **ctx,
            )
        edges = tuple(float(edge) for edge in payload.get("edges_kt", config["data"]["imd5_edges_kt"]))
        names = tuple(str(name) for name in payload.get("class_names", config["data"]["imd5_names"]))
        averaging = payload.get("wind_averaging")
        averaging = None if averaging in (None, "") else str(averaging)
        field_mean = IntensityEstimate._mean(reports)
        width = _finite(_section(config, "predict", "training_mean_width"), "predict.training_mean_width")
        scale = max(float(payload["norm_std"]), 1e-6)
        outside = abs(field_mean - float(payload["norm_mean"])) > width * scale
        low, high = (float(bound) for bound in config["data"]["plausible_wind_kt"])
        if outside or not (low <= wind_kt <= high):
            return Estimate(
                "outside_range",
                "",
                synthetic,
                outside_training=outside,
                wind_averaging=averaging,
                edges=edges,
                names=names,
                honesty=payload.get("honesty"),
                matched_run=matched,
                **ctx,
            )
        gate_score = min(report.score for report in reports)
        quantiles = ConfidenceScore.source(payload, record if matched else None)
        confidence = ConfidenceScore.combine(config, gate_score, std_kt, quantiles)
        factor = _finite(_section(config, "data", "kt_to_kmh"), "data.kt_to_kmh")
        if factor <= 0:
            raise ValueError("config data.kt_to_kmh must be positive")
        banner_text = ""
        if not synthetic and matched and isinstance(record, dict):
            banner_text = research_disclaimer_banner(
                run_id=str(record.get("run_id", "")),
                dataset=str(record.get("dataset", "")),
                model=str(record.get("model") or record.get("model_name", "")),
            )
        return Estimate(
            "ok",
            banner_text,
            synthetic,
            wind_kt=float(wind_kt),
            wind_kmh=float(wind_kt) * factor,
            dropout_std_kt=None if std_kt is None else float(std_kt),
            samples=tuple(float(value) for value in samples),
            confidence=confidence,
            confidence_status=ConfidenceScore.status(config, record if matched else None),
            grouping_note=IntensityGrouping.note(config),
            gate_score=gate_score,
            matched_run=matched,
            wind_averaging=averaging,
            edges=edges,
            names=names,
            honesty=None if payload.get("honesty") is None else str(payload.get("honesty")),
            **ctx,
        )

    @staticmethod
    def _context(config: dict, latitude, longitude, metadata) -> dict:
        states, note, reference = CoastalContext.describe(config, latitude, longitude, metadata)
        return {
            "operational_disclaimer": str(_section(config, "predict", "operational_disclaimer")).strip(),
            "coastal_heading": str(_section(config, "predict", "coastal_heading")).strip(),
            "nearest_coastal_states": states,
            "landfall_note": note,
            "coast_reference_note": reference,
        }

    @staticmethod
    def _check_identity(config: dict, payload: dict) -> None:
        if str(config["model"].get("name", "simple_cnn")) != str(payload["model_name"]):
            raise ValueError("config model.name does not match the checkpoint")
        if not image_sizes_match(config["data"]["image_size"], payload["image_size"]):
            raise ValueError("config image_size does not match the checkpoint")
        if payload.get("hidden") is not None and int(config["model"].get("hidden", 16)) != int(
            payload["hidden"]
        ):
            raise ValueError("config model.hidden does not match the checkpoint")
        if str(payload.get("norm_source_split")) != "train":
            raise ValueError("checkpoint normalization was not fit on train")

    @staticmethod
    def _unflipped(images: list[np.ndarray], hemisphere: str | None) -> list[np.ndarray]:
        from src.preprocessing import leave_unflipped

        return [leave_unflipped(image, hemisphere) for image in images]

    @staticmethod
    def _missing_fraction(images: list[np.ndarray], limit: float) -> str | None:
        from src.preprocessing import as_channel_first, missing_fraction

        for image in images:
            if missing_fraction(as_channel_first(image)) > limit:
                return "missing"
        return None

    @staticmethod
    def _gate_banner(settings: GateSettings, reason: str) -> str:
        return (
            f"{settings.refusal}: {reason}. "
            "There is no wind speed. This is not a forecast."
        )

    @staticmethod
    def _prepare(config: dict, payload: dict, reports: list[GateReport]) -> list[np.ndarray]:
        from src.preprocessing import norm_stats_from_checkpoint, prepare_image

        mode = FrameGeometry.mode(config)
        pad = str(_section(config, "data", "pad")).strip()
        stats = norm_stats_from_checkpoint(payload)
        image_size = parse_image_size(payload["image_size"])
        limit = float(payload["max_missing_fraction"])
        prepared = []
        for report in reports:
            field = report.field if mode == "stretch" else FrameGeometry.pad_square(report.field, pad)
            prepared.append(prepare_image(field, image_size, stats, limit))
        return prepared

    @staticmethod
    def _mean(reports: list[GateReport]) -> float:
        values = [np.asarray(report.field, dtype=np.float64) for report in reports]
        finite = [image[np.isfinite(image)] for image in values]
        finite = [image for image in finite if image.size]
        if not finite:
            raise ValueError("image has no finite pixels")
        return float(np.concatenate(finite).mean())

    @staticmethod
    def _wind(config: dict, payload: dict, prepared: list[np.ndarray], reports: list[GateReport]):
        if payload["_kind"] == "sklearn":
            wind = IntensityEstimate._sklearn_wind(config, payload, reports[0])
            return wind, np.asarray([wind], dtype=np.float64), None
        return IntensityEstimate._torch_wind(config, payload, prepared)

    @staticmethod
    def _sklearn_wind(config: dict, payload: dict, report: GateReport) -> float:
        expected = [str(name) for name in _section(config, "predict", "sklearn_features")]
        names = [str(name) for name in payload["feature_names"]]
        if names != expected:
            raise ValueError("joblib feature_names do not match predict.sklearn_features")
        estimator = payload["estimator"]
        if not hasattr(estimator, "predict"):
            raise ValueError("joblib checkpoint estimator has no predict")
        features = report.feature_map()
        vector = np.asarray([[features[name] for name in names]], dtype=np.float64)
        wind = float(np.asarray(estimator.predict(vector), dtype=np.float64).reshape(-1)[0])
        return wind

    @staticmethod
    def _torch_wind(config: dict, payload: dict, prepared: list[np.ndarray]):
        import torch

        count = int(_section(config, "model", "mc_samples"))
        if count < 1:
            raise ValueError("model.mc_samples must be at least 1")
        stack = np.stack(prepared, axis=0)
        tensor = torch.from_numpy(np.ascontiguousarray(stack))
        model_input = tensor if len(prepared) == 1 else tensor.unsqueeze(0)
        model = ModelAccess.build_net(config, size_head=bool(payload.get("size_head", False)))
        model.load_state_dict(payload["state_dict"])
        seed = int(config.get("project", {}).get("seed", 0))
        dropout = ModelAccess.mc_dropout()
        state = torch.get_rng_state()
        try:
            model.eval()
            with torch.no_grad():
                point = IntensityEstimate._as_wind(model(model_input))
                if count == 1:
                    return point, np.asarray([point], dtype=np.float64), 0.0
                dropout.enable(model)
                torch.manual_seed(seed)
                draws = [
                    IntensityEstimate._as_wind(model(model_input)) for _ in range(count)
                ]
            samples = np.asarray(draws, dtype=np.float64)
            return point, samples, float(samples.std(ddof=1))
        finally:
            model.eval()
            torch.set_rng_state(state)

    @staticmethod
    def _as_wind(output) -> float:
        wind = output[0] if isinstance(output, tuple) else output
        return float(wind.detach().cpu().reshape(-1)[0])


class RunCheckpoint:
    """Resolve a checkpoint from ``paths.runs/<run_id>/`` or a Hub mirror.

    ``src.train.run_training`` writes that directory: the checkpoint file
    named in ``paths.checkpoint_name``, plus ``metrics.json``. A model repo
    with those same relative paths is the Hub mirror. ``CLOUDIE_RUN_ID``
    overrides ``paths.run_id``. ``CLOUDIE_HF_MODEL_REPO`` overrides
    ``paths.hf_model_repo``. ``CLOUDIE_CHECKPOINT`` is one local file for
    the synthetic software check.

    A real checkpoint produces a wind only when its run record passes
    :meth:`ConfidenceScore._held_out_storm_check`. Until that record exists,
    this returns no wind. A synthetic file is flagged by ``is_synthetic``.
    """

    ENV_REPO = "CLOUDIE_HF_MODEL_REPO"
    ENV_RUN = "CLOUDIE_RUN_ID"
    ENV_FILE = "CLOUDIE_CHECKPOINT"
    MISSING = (
        "No checkpoint was found. There is no model output. This is not a forecast."
    )

    @staticmethod
    def _optional(config: dict, env_name: str, key: str) -> str | None:
        raw = os.environ.get(env_name, "").strip()
        if not raw:
            value = (config.get("paths") or {}).get(key)
            raw = "" if value in (None, "null") else str(value).strip()
        if not raw or raw.lower() in {"none", "null"}:
            return None
        return raw

    @staticmethod
    def repo_id(config: dict) -> str | None:
        raw = RunCheckpoint._optional(config, RunCheckpoint.ENV_REPO, "hf_model_repo")
        if raw is None:
            return None
        namespace, separator, name = raw.partition("/")
        allowed = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-")
        if (
            not separator
            or "/" in name
            or not namespace
            or not name
            or ".." in raw
            or any(char not in allowed for char in namespace + name)
        ):
            raise ValueError("The Hugging Face model repo id must be namespace/name.")
        return raw

    @staticmethod
    def run_id(config: dict) -> str | None:
        raw = RunCheckpoint._optional(config, RunCheckpoint.ENV_RUN, "run_id")
        if raw is None:
            return None
        if raw != Path(raw).name or ".." in raw:
            raise ValueError("paths.run_id must be a single directory name.")
        return raw

    @staticmethod
    def download(repo_id: str, filename: str) -> Path:
        """Fetch one file from a model repo. Tests replace this method."""
        if filename.startswith("/") or "\\" in filename or ".." in filename.split("/"):
            raise ValueError("The Hub filename must stay inside the repo.")
        message = (
            "The Hugging Face checkpoint could not be loaded. "
            "There is no model output. This is not a forecast."
        )
        try:
            from huggingface_hub import hf_hub_download
        except ImportError as exc:
            raise ValueError(message) from exc
        try:
            fetched = hf_hub_download(repo_id=repo_id, filename=filename, repo_type="model")
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as exc:
            raise ValueError(message) from exc
        return Path(fetched)

    @staticmethod
    def resolve(config: dict, root: Path | None = None) -> tuple[Path | None, dict]:
        """Return the checkpoint and a config that can see its ``metrics.json``."""
        override = os.environ.get(RunCheckpoint.ENV_FILE, "").strip()
        if override:
            path = Path(override)
            prepared = RunRecord._with_active(config, path.parent) if path.is_file() else config
            return (path if path.is_file() else None), prepared
        base = root or Path()
        selected = RunCheckpoint.run_id(config)
        name = str(_section(config, "paths", "checkpoint_name"))
        if name != Path(name).name:
            raise ValueError("paths.checkpoint_name must be a file name, not a path.")
        if selected:
            directory = Path(_section(config, "paths", "runs")) / selected
            if not directory.is_absolute():
                directory = base / directory
            local = directory / name
            if local.is_file():
                return local, RunRecord._with_active(config, local.parent)
        else:
            runs_val = (config.get("paths") or {}).get("runs")
            if runs_val:
                runs_dir = Path(runs_val)
                if not runs_dir.is_absolute():
                    runs_dir = base / runs_dir
                if runs_dir.is_dir():
                    for cand in sorted(runs_dir.iterdir(), reverse=True):
                        if cand.is_dir() and (cand / name).is_file():
                            local = cand / name
                            return local, RunRecord._with_active(config, local.parent)
        repo = RunCheckpoint.repo_id(config)
        if repo is None:
            return None, config
        prefix = f"{selected}/" if selected else ""
        downloaded = None
        active_prefix = prefix
        for try_pfx in ([prefix, f"runs/{prefix}"] if selected else []):
            try:
                downloaded = RunCheckpoint.download(repo, f"{try_pfx}{name}")
                active_prefix = try_pfx
                break
            except ValueError:
                continue
        if downloaded is None and not selected:
            cand_runs = []
            try:
                from huggingface_hub import list_repo_files

                for f in list_repo_files(repo):
                    if f.endswith(name):
                        parts = f.split("/")
                        if len(parts) >= 2:
                            cid = parts[-2]
                            if cid not in cand_runs:
                                cand_runs.append(cid)
            except Exception:
                if repo == "Anlea/cloudie-weights":
                    cand_runs = [
                        "nasa-resnet18-20261121T180837Z-1795284517431658868-03243d0d",
                        "incyde-resnet18-20261121T212138Z-1795296098584083196-b6801899",
                    ]
            for cid in cand_runs:
                for try_pfx in (f"runs/{cid}/", f"{cid}/"):
                    try:
                        downloaded = RunCheckpoint.download(repo, f"{try_pfx}{name}")
                        active_prefix = try_pfx
                        break
                    except ValueError:
                        continue
                if downloaded is not None:
                    break
        if downloaded is None:
            return None, config
        try:
            metrics = RunCheckpoint.download(repo, f"{active_prefix}metrics.json")
        except ValueError:
            metrics = None
        if metrics is None:
            return downloaded, config
        return downloaded, RunRecord._with_active(config, metrics.parent)

    @staticmethod
    def active_run_info(config: dict, root: Path | None = None) -> dict | None:
        """Return run metadata (run_id, dataset, model) for an active real run if resolvable."""
        override = os.environ.get(RunCheckpoint.ENV_FILE, "").strip()
        if override:
            p = Path(override)
            if p.is_file():
                m_file = p.parent / "metrics.json"
                if m_file.is_file():
                    try:
                        rec = json.loads(m_file.read_text(encoding="utf-8"))
                        if isinstance(rec, dict) and (
                            ConfidenceScore._held_out_test_evaluated(rec)
                            or ConfidenceScore._held_out_storm_check(rec)
                        ):
                            return {
                                "run_id": str(rec.get("run_id", p.stem)),
                                "dataset": str(rec.get("dataset", "")),
                                "model": str(rec.get("model") or rec.get("model_name", "")),
                            }
                    except Exception:
                        pass

        base = root or Path()
        selected = RunCheckpoint.run_id(config)
        runs_val = (config.get("paths") or {}).get("runs")
        if runs_val:
            runs_dir = Path(runs_val)
            if not runs_dir.is_absolute():
                runs_dir = base / runs_dir
            if selected:
                cand = runs_dir / selected
                m_file = cand / "metrics.json"
                if m_file.is_file():
                    try:
                        rec = json.loads(m_file.read_text(encoding="utf-8"))
                        if isinstance(rec, dict) and (
                            ConfidenceScore._held_out_test_evaluated(rec)
                            or ConfidenceScore._held_out_storm_check(rec)
                        ):
                            return {
                                "run_id": str(rec.get("run_id", selected)),
                                "dataset": str(rec.get("dataset", "")),
                                "model": str(rec.get("model") or rec.get("model_name", "")),
                            }
                    except Exception:
                        pass
            elif runs_dir.is_dir():
                for cand in sorted(runs_dir.iterdir(), reverse=True):
                    m_file = cand / "metrics.json"
                    if m_file.is_file():
                        try:
                            rec = json.loads(m_file.read_text(encoding="utf-8"))
                            if isinstance(rec, dict) and (
                                ConfidenceScore._held_out_test_evaluated(rec)
                                or ConfidenceScore._held_out_storm_check(rec)
                            ):
                                return {
                                    "run_id": str(rec.get("run_id", cand.name)),
                                    "dataset": str(rec.get("dataset", "")),
                                    "model": str(rec.get("model") or rec.get("model_name", "")),
                                }
                        except Exception:
                            pass

        repo = RunCheckpoint.repo_id(config)
        if repo:
            if selected:
                for pfx in (f"{selected}/", f"runs/{selected}/"):
                    try:
                        m_path = RunCheckpoint.download(repo, f"{pfx}metrics.json")
                        rec = json.loads(m_path.read_text(encoding="utf-8"))
                        if isinstance(rec, dict) and (
                            ConfidenceScore._held_out_test_evaluated(rec)
                            or ConfidenceScore._held_out_storm_check(rec)
                        ):
                            return {
                                "run_id": str(rec.get("run_id", selected)),
                                "dataset": str(rec.get("dataset", "")),
                                "model": str(rec.get("model") or rec.get("model_name", "")),
                            }
                    except Exception:
                        pass
            else:
                cand_runs = []
                try:
                    from huggingface_hub import list_repo_files

                    for f in list_repo_files(repo):
                        if f.endswith("metrics.json"):
                            parts = f.split("/")
                            if len(parts) >= 2:
                                cid = parts[-2]
                                if cid not in cand_runs:
                                    cand_runs.append(cid)
                except Exception:
                    if repo == "Anlea/cloudie-weights":
                        cand_runs = [
                            "nasa-resnet18-20261121T180837Z-1795284517431658868-03243d0d",
                            "incyde-resnet18-20261121T212138Z-1795296098584083196-b6801899",
                        ]
                for cid in cand_runs:
                    for pfx in (f"{cid}/", f"runs/{cid}/"):
                        try:
                            m_path = RunCheckpoint.download(repo, f"{pfx}metrics.json")
                            rec = json.loads(m_path.read_text(encoding="utf-8"))
                            if isinstance(rec, dict) and (
                                ConfidenceScore._held_out_test_evaluated(rec)
                                or ConfidenceScore._held_out_storm_check(rec)
                            ):
                                return {
                                    "run_id": str(rec.get("run_id", cid)),
                                    "dataset": str(rec.get("dataset", "")),
                                    "model": str(rec.get("model") or rec.get("model_name", "")),
                                }
                        except Exception:
                            pass
        return None

    @staticmethod
    def resolve_banner(config: dict, root: Path | None = None) -> str:
        """Return research_disclaimer_banner if real run is resolvable, else NO_TRAINED_MODEL_BANNER."""
        info = RunCheckpoint.active_run_info(config, root)
        if info is not None:
            return research_disclaimer_banner(
                run_id=info.get("run_id", ""),
                dataset=info.get("dataset", ""),
                model=info.get("model", ""),
            )
        return NO_TRAINED_MODEL_BANNER

    @staticmethod
    def held_out(config: dict, payload: dict) -> bool:
        matched, record = RunRecord.load_match(config, payload)
        if not matched or record is None:
            return False
        return bool(
            ConfidenceScore._held_out_test_evaluated(record)
            or ConfidenceScore._held_out_storm_check(record)
        )

    @staticmethod
    def estimate(
        config: dict,
        images: list[np.ndarray],
        *,
        hemisphere: str | None = None,
        latitude=None,
        longitude=None,
        metadata=None,
        root: Path | None = None,
        path: Path | None = None,
        resolve: bool = True,
    ) -> Estimate:
        """Gate the frame, then load a run checkpoint when one is allowed to answer.

        ``path`` is an explicit file. ``resolve`` looks up ``paths.runs`` and
        the Hub mirror when ``path`` is omitted.
        """
        try:
            ctx = IntensityEstimate._context(config, latitude, longitude, metadata)
        except ValueError:
            ctx = IntensityEstimate._context(config, None, None, None)
        settings = GateSettings.from_config(config)
        frames = IntensityEstimate._unflipped(images, hemisphere)
        reports = [CycloneImageGate.assess(frame, settings) for frame in frames]
        refused = next((report for report in reports if not report.accepted), None)
        if refused is not None:
            return Estimate(
                "not_cyclone",
                IntensityEstimate._gate_banner(settings, refused.reason),
                False,
                gate_reason=refused.reason,
                gate_score=refused.score,
                **ctx,
            )
        try:
            if path is not None:
                chosen = Path(path)
                if chosen.is_file():
                    prepared = RunRecord._with_active(config, chosen.parent)
                else:
                    chosen = None
                    prepared = config
            elif resolve:
                chosen, prepared = RunCheckpoint.resolve(config, root)
            else:
                chosen, prepared = None, config
        except ValueError as exc:
            return Estimate("no_run_record", str(exc), False, **ctx)
        path = chosen
        if path is None:
            return Estimate("missing_checkpoint", RunCheckpoint.MISSING, False, **ctx)
        try:
            payload = CheckpointStore.load(path)
        except (OSError, ValueError) as exc:
            return Estimate("no_run_record", str(exc), False, **ctx)
        synthetic = bool(payload.get("is_synthetic"))
        if not synthetic and not RunCheckpoint.held_out(prepared, payload):
            matched, _record = RunRecord.load_match(prepared, payload)
            if matched:
                message = str(_section(prepared, "predict", "held_out_refusal")).strip()
            else:
                message = str(_section(prepared, "predict", "no_run_record_refusal")).strip()
            return Estimate("no_run_record", message, False, matched_run=matched, **ctx)
        try:
            return IntensityEstimate.predict(
                prepared,
                path,
                images,
                hemisphere=hemisphere,
                latitude=latitude,
                longitude=longitude,
                metadata=metadata,
            )
        except (OSError, ValueError) as exc:
            return Estimate("no_run_record", str(exc), synthetic, **ctx)