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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
"""Held-out intensity scores for supplied wind predictions.

Bins are our own grouping, IMD-style names at 17/34/48/64/91 kt. VSCS and
ESCS/SuCS are always reported. IMD class definitions use 3-minute winds.
NASA HURDAT2 labels are 1-minute winds. ``wind_averaging`` is stored on the
report (for example ``1min`` for NASA) and mixed periods are refused. This
module does not convert one averaging period into another.

The evaluated storms are the test side of ``storm_ids_by_split``. Pixel
normalization uses ``fit_split_normalization`` (defined on ``src.train``,
which already calls the splits helper; ``cloudie.train`` re-exports it).
Mean, ridge, and persistence reuse ``src.baselines``. Persistence is a
reference baseline (``src.baselines.persistence_predictions``): the previous
frame's best-track label, not the imagery. Image-only models cannot be
compared against it.

Monte Carlo dropout coverage reads a NumPy array of draws. This module does
not import torch. Residual-quantile widths are fit on validation storms and
scored on test storms. A coverage gap larger than the tolerance is labeled
``uncalibrated``. ``quote_as_result`` stays ``no``. This is not a forecast
and not an operational-readiness claim.

``intensity_class_evaluation`` scores regression predictions on the
validation split only. It reports RMSE, MAE, and bias (prediction minus
true wind) overall and in each project intensity bin, with row counts,
distinct storm counts, and 95% percentile intervals from a bootstrap that
resamples storm IDs. Test rows are refused. A ``wind_averaging`` column is
copied through and grouped when it is present. An ``on_fix`` column, when
present, adds the same table on rows whose label sits on a best-track fix.
Classes with fewer than 3 storms are marked indicative. ``evaluate`` still
scores the test storms with point metrics and does not run this bootstrap
on them.

Checkpoint scoring stays in ``cloudie.evaluate``.
"""

from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
from typing import Sequence

os.environ.setdefault("MPLBACKEND", "Agg")

import numpy as np
import pandas as pd

from src.baselines import baseline_params, fit_numeric_pipeline, persistence_predictions
from src.config import load_config
from src.features import model_matrix
from src.metrics import (
    mean_baseline,
    metrics_by_class,
    regression_metrics,
    storm_bootstrap_metrics,
)
from src.plots import save_regression_scatter
from src.schema import (
    DEFAULT_EDGES_KT,
    DEFAULT_NAMES,
    recorded_wind_averaging,
    require_valid,
    wind_to_imd5,
)
from src.splits import (
    LeakageError,
    assert_no_forbidden_inputs,
    assign_storms,
    storm_ids_by_split,
)

BINNING_LABEL = "our own grouping, IMD-style names"
INDICATIVE_STATUS = "indicative (n_storms<3)"
_SMALL_CLASS_STORMS = 3
_ON_FIX_TRUE = frozenset({"1", "true", "yes", "y", "t"})
_ON_FIX_FALSE = frozenset({"0", "false", "no", "n", "f"})
_CLASS_TABLE_COLUMNS = (
    "wind_averaging",
    "subset",
    "row_kind",
    "intensity_class",
    "storm_id",
    "n_rows",
    "n_storms",
    "rmse_kt",
    "mae_kt",
    "bias_kt",
    "rmse_kt_ci_low",
    "rmse_kt_ci_high",
    "mae_kt_ci_low",
    "mae_kt_ci_high",
    "bias_kt_ci_low",
    "bias_kt_ci_high",
    "ci_level",
    "n_resamples",
    "seed",
    "resample",
    "status",
)
HIGHLIGHT_CODES = ("VSCS", "ESCS_SUCS")
HIGHLIGHT_DISPLAY = {"VSCS": "VSCS", "ESCS_SUCS": "ESCS/SuCS"}
WIND_AVERAGING_NOTE = (
    "IMD class definitions use 3-minute winds. "
    "NASA HURDAT2 labels are 1-minute winds and can be recorded as "
    "wind_averaging='1min'. This report stores the period it was given "
    "and does not convert between averaging periods."
)
BANNER = (
    "Software check only. Do not quote these numbers as experimental results. "
    "Bins are our own grouping, IMD-style names. "
    "IMD class definitions use 3-minute winds. NASA HURDAT2 labels are "
    "1-minute winds. wind_averaging is recorded and is not converted. "
    "Monte Carlo dropout coverage is not a calibrated forecast interval. "
    "Residual-quantile intervals are labeled uncalibrated when held-out "
    "coverage misses the nominal level by more than the tolerance. "
    "This is not a forecast, a warning, or an operational-readiness claim."
)
_EMPTY_METRICS = {"n": 0.0, "mae_kt": None, "rmse_kt": None, "bias_kt": None}
_LEVELS = (0.80, 0.90)
_TOLERANCE = 0.05
# Float slack so a gap that lands on the tolerance is not marked uncalibrated.
_GAP_SLACK = 1e-9


def _pyplot():
    import matplotlib

    matplotlib.use("Agg", force=True)
    import matplotlib.pyplot as plt

    return plt


def _level_key(level: float) -> str:
    return f"{float(level):.2f}"


def _check_levels(levels: Sequence[float]) -> tuple[float, ...]:
    values = tuple(float(level) for level in levels)
    if not values:
        raise ValueError("at least one nominal coverage level is required")
    for level in values:
        if not 0.0 < level < 1.0:
            raise ValueError(f"coverage level must be between 0 and 1, got {level}")
    return values


def interval_status(empirical: float, nominal: float, tolerance: float) -> str:
    """Label an interval ``uncalibrated`` when coverage misses by more than ``tolerance``."""
    if tolerance < 0:
        raise ValueError("coverage tolerance must be non-negative")
    gap = abs(float(empirical) - float(nominal))
    if gap > float(tolerance) + _GAP_SLACK:
        return "uncalibrated"
    return "within_tolerance"


def _bin_spec(config: dict) -> tuple[tuple[float, ...], tuple[str, ...]]:
    data = dict(config.get("data") or {})
    edges = tuple(float(edge) for edge in data.get("imd5_edges_kt", DEFAULT_EDGES_KT))
    names = tuple(str(name) for name in data.get("imd5_names", DEFAULT_NAMES))
    if len(edges) != len(names) or not edges:
        raise ValueError("intensity edges and names must be non-empty and the same length")
    return edges, names


def assign_bins(
    winds: np.ndarray,
    edges: Sequence[float] = DEFAULT_EDGES_KT,
    names: Sequence[str] = DEFAULT_NAMES,
) -> np.ndarray:
    """Project target wind onto our own grouping, IMD-style names.

    Winds below the first edge are None. The names are not a warning product.
    """
    edge_tuple = tuple(float(edge) for edge in edges)
    name_tuple = tuple(str(name) for name in names)
    values = np.asarray(winds, dtype=np.float64).ravel()
    return np.asarray(
        [wind_to_imd5(float(wind), edge_tuple, name_tuple) for wind in values],
        dtype=object,
    )


def _empty_metrics() -> dict[str, float | None]:
    return dict(_EMPTY_METRICS)


def _highlight(by_bin: dict[str, dict]) -> dict[str, dict]:
    highlighted: dict[str, dict] = {}
    for code in HIGHLIGHT_CODES:
        metrics = dict(by_bin.get(code) or _empty_metrics())
        metrics["display_name"] = HIGHLIGHT_DISPLAY[code]
        highlighted[code] = metrics
    return highlighted


def score_winds(
    y_true: np.ndarray,
    y_pred: np.ndarray,
    edges: Sequence[float] = DEFAULT_EDGES_KT,
    names: Sequence[str] = DEFAULT_NAMES,
) -> dict:
    """MAE, RMSE, and bias overall and per target-wind bin.

    Empty bins, including VSCS and ESCS/SuCS when absent, keep null errors.
    A zero error is not invented for an empty bin.
    """
    truth = np.asarray(y_true, dtype=np.float64).ravel()
    pred = np.asarray(y_pred, dtype=np.float64).ravel()
    if truth.size == 0:
        by_bin = {str(name): _empty_metrics() for name in names}
        for code in HIGHLIGHT_CODES:
            by_bin.setdefault(code, _empty_metrics())
        return {
            "overall": _empty_metrics(),
            "by_bin": by_bin,
            "highlight": _highlight(by_bin),
            "n_below_lowest_edge": 0,
        }
    labels = assign_bins(truth, edges, names)
    found = metrics_by_class(truth, pred, labels)
    by_bin: dict[str, dict] = {}
    for name in tuple(names) + HIGHLIGHT_CODES:
        key = str(name)
        if key in by_bin:
            continue
        by_bin[key] = dict(found[key]) if key in found else _empty_metrics()
    below = int(sum(label is None for label in labels))
    return {
        "overall": regression_metrics(truth, pred),
        "by_bin": by_bin,
        "highlight": _highlight(by_bin),
        "n_below_lowest_edge": below,
    }


def _missing_label(value: object) -> bool:
    if value is None:
        return True
    try:
        missing = pd.isna(value)
    except (TypeError, ValueError):
        return False
    if missing is True:
        return True
    if isinstance(missing, np.ndarray):
        return False
    return bool(missing)


def _parse_on_fix(value: object) -> bool:
    """Explicit true or false. Null and unrecognized values raise."""
    if isinstance(value, (bool, np.bool_)):
        return bool(value)
    if _missing_label(value):
        raise ValueError("on_fix is null; each row must be an explicit true or false")
    if isinstance(value, str):
        text = value.strip().lower()
        if text in _ON_FIX_TRUE:
            return True
        if text in _ON_FIX_FALSE:
            return False
        raise ValueError(f"on_fix value {value!r} is not an explicit true or false")
    item = getattr(value, "item", None)
    if callable(item) and not isinstance(value, (str, bytes, bool)):
        try:
            unpacked = item()
        except (TypeError, ValueError):
            unpacked = value
        else:
            if type(unpacked) is not type(value):
                return _parse_on_fix(unpacked)
    if isinstance(value, (int, np.integer)) and not isinstance(value, bool):
        if int(value) in (0, 1):
            return bool(int(value))
        raise ValueError(f"on_fix value {value!r} is not an explicit true or false")
    if isinstance(value, float) and value in (0.0, 1.0):
        return bool(value)
    raise ValueError(f"on_fix value {value!r} is not an explicit true or false")


def _on_fix_mask(values: np.ndarray | None, n_rows: int) -> np.ndarray | None:
    if values is None:
        return None
    raw = np.asarray(values, dtype=object).ravel()
    if raw.size != n_rows:
        raise ValueError("on_fix must align with y_true")
    return np.asarray([_parse_on_fix(value) for value in raw.tolist()], dtype=bool)


def _require_validation_split(splits: np.ndarray, n_rows: int) -> None:
    labels = np.asarray(splits, dtype=object).ravel()
    if labels.size != n_rows:
        raise ValueError("splits must align with y_true")
    refused = sorted({str(value) for value in labels.tolist()} - {"val"})
    if refused:
        raise LeakageError(
            "intensity-class evaluation scores the validation split only; "
            f"refusing {refused}"
        )


def _class_labels(classes: np.ndarray, n_rows: int) -> np.ndarray:
    raw = np.asarray(classes, dtype=object).ravel()
    if raw.size != n_rows:
        raise ValueError("classes must align with y_true")
    labels = np.empty(n_rows, dtype=object)
    for index, value in enumerate(raw.tolist()):
        labels[index] = None if _missing_label(value) else str(value)
    return labels


def _averaging_blocks(
    n_rows: int, wind_averaging: np.ndarray | None
) -> list[tuple[object, np.ndarray]]:
    """One block when the column is absent. Otherwise group, without converting."""
    if wind_averaging is None:
        return [(None, np.arange(n_rows, dtype=np.int64))]
    raw = np.asarray(wind_averaging, dtype=object).ravel()
    if raw.size != n_rows:
        raise ValueError("wind_averaging must align with y_true")
    order: list[object] = []
    buckets: dict[object, list[int]] = {}
    for index, value in enumerate(raw.tolist()):
        key: object = None if _missing_label(value) else str(value)
        if key not in buckets:
            buckets[key] = []
            order.append(key)
        buckets[key].append(index)
    if not order and n_rows == 0:
        return [(None, np.zeros(0, dtype=np.int64))]
    return [(key, np.asarray(buckets[key], dtype=np.int64)) for key in order]


def _class_names_in_order(labels: np.ndarray, class_names: Sequence[str]) -> list[str]:
    ordered: list[str] = []
    seen: set[str] = set()
    for name in class_names:
        key = str(name)
        if key not in seen:
            ordered.append(key)
            seen.add(key)
    for label in labels.tolist():
        if label is None or label in seen:
            continue
        ordered.append(str(label))
        seen.add(str(label))
    return ordered


def _empty_class_metrics(n_resamples: int, seed: int, ci_level: float) -> dict[str, object]:
    return {
        "n_rows": 0,
        "n_storms": 0,
        "rmse_kt": np.nan,
        "mae_kt": np.nan,
        "bias_kt": np.nan,
        "rmse_kt_ci_low": np.nan,
        "rmse_kt_ci_high": np.nan,
        "mae_kt_ci_low": np.nan,
        "mae_kt_ci_high": np.nan,
        "bias_kt_ci_low": np.nan,
        "bias_kt_ci_high": np.nan,
        "ci_level": float(ci_level),
        "n_resamples": int(n_resamples),
        "seed": int(seed),
        "resample": "storm_id",
        "status": "",
    }


def _metric_record(
    truth: np.ndarray,
    pred: np.ndarray,
    storm_ids: np.ndarray,
    *,
    wind_averaging: object,
    subset: str,
    row_kind: str,
    intensity_class: str,
    storm_id: object,
    n_resamples: int,
    seed: int,
    ci_level: float,
) -> dict[str, object]:
    if truth.size == 0:
        metrics: dict[str, object] = _empty_class_metrics(n_resamples, seed, ci_level)
    else:
        metrics = dict(
            storm_bootstrap_metrics(
                truth,
                pred,
                storm_ids,
                n_resamples=n_resamples,
                seed=seed,
                ci_level=ci_level,
            )
        )
        n_storms = int(metrics["n_storms"])
        metrics["status"] = (
            INDICATIVE_STATUS if 0 < n_storms < _SMALL_CLASS_STORMS else ""
        )
    metrics.update(
        {
            "wind_averaging": np.nan if wind_averaging is None else wind_averaging,
            "subset": subset,
            "row_kind": row_kind,
            "intensity_class": intensity_class,
            "storm_id": np.nan if storm_id is None else storm_id,
        }
    )
    return metrics


def _storm_ids_in_order(storm_ids: np.ndarray) -> list[str]:
    seen: dict[str, None] = {}
    for storm in np.asarray(storm_ids, dtype=object).ravel().tolist():
        seen.setdefault(str(storm), None)
    return list(seen)


def intensity_class_evaluation(
    y_true: np.ndarray,
    y_pred: np.ndarray,
    storm_ids: np.ndarray,
    classes: np.ndarray,
    splits: np.ndarray,
    *,
    wind_averaging: np.ndarray | None = None,
    on_fix: np.ndarray | None = None,
    class_names: Sequence[str] = DEFAULT_NAMES,
    n_resamples: int = 1000,
    seed: int = 0,
    ci_level: float = 0.95,
    per_storm_breakdown: bool = True,
) -> pd.DataFrame:
    """Validation RMSE, MAE, and bias by this project's intensity bins.

    Bias is prediction minus true wind. Intervals resample storm IDs. The
    default is 1000 resamples and a 95% percentile interval. ``splits`` must
    be ``val`` on every row.

    ``classes`` are the existing project labels, usually ``imd5_class``.
    Every configured bin is reported. A bin with no rows keeps null errors.
    Unlabeled rows stay in the overall line only.

    ``wind_averaging``, when given, is copied onto the table and the metrics
    are computed inside each distinct period. Periods are not converted and
    mixed periods are not pooled. Omit it when the column is absent.

    ``on_fix``, when given, must be an explicit boolean per row. The table
    then also contains ``subset='on_fix'``, restricted to rows on a
    best-track fix. ``subset='all'`` is always reported.

    A class with at least one row and fewer than 3 storms is marked
    ``indicative (n_storms<3)``. The same mark is applied to an overall
    line with fewer than 3 storms. When ``per_storm_breakdown`` is true,
    each such class also lists one row per storm.
    """
    if not isinstance(per_storm_breakdown, bool):
        raise ValueError("per_storm_breakdown must be true or false")
    truth = np.asarray(y_true, dtype=np.float64).ravel()
    pred = np.asarray(y_pred, dtype=np.float64).ravel()
    if truth.shape != pred.shape:
        raise ValueError("y_true and y_pred must be the same shape")
    if truth.size and (not np.isfinite(truth).all() or not np.isfinite(pred).all()):
        raise ValueError("y_true and y_pred must be finite")
    n_rows = int(truth.size)
    _require_validation_split(splits, n_rows)
    ids = np.asarray(storm_ids, dtype=object).ravel()
    if ids.size != n_rows:
        raise ValueError("storm_ids must align with y_true")
    labels = _class_labels(classes, n_rows)
    fix_mask = _on_fix_mask(on_fix, n_rows)
    if not class_names:
        raise ValueError("at least one intensity class name is required")
    rows: list[dict[str, object]] = []
    for period, positions in _averaging_blocks(n_rows, wind_averaging):
        subsets = [("all", positions)]
        if fix_mask is not None:
            subsets.append(("on_fix", positions[fix_mask[positions]]))
        for subset, index in subsets:
            slice_truth = truth[index]
            slice_pred = pred[index]
            slice_storms = ids[index]
            slice_labels = labels[index]
            overall = _metric_record(
                slice_truth,
                slice_pred,
                slice_storms,
                wind_averaging=period,
                subset=subset,
                row_kind="overall",
                intensity_class="overall",
                storm_id=None,
                n_resamples=n_resamples,
                seed=seed,
                ci_level=ci_level,
            )
            rows.append(overall)
            for name in _class_names_in_order(slice_labels, class_names):
                chosen = np.flatnonzero(slice_labels == name)
                class_row = _metric_record(
                    slice_truth[chosen],
                    slice_pred[chosen],
                    slice_storms[chosen],
                    wind_averaging=period,
                    subset=subset,
                    row_kind="class",
                    intensity_class=name,
                    storm_id=None,
                    n_resamples=n_resamples,
                    seed=seed,
                    ci_level=ci_level,
                )
                rows.append(class_row)
                n_storms = int(class_row["n_storms"])
                if per_storm_breakdown and 0 < n_storms < _SMALL_CLASS_STORMS:
                    class_storms = slice_storms[chosen]
                    class_truth = slice_truth[chosen]
                    class_pred = slice_pred[chosen]
                    for storm in _storm_ids_in_order(class_storms):
                        storm_index = np.flatnonzero(
                            np.asarray([str(item) for item in class_storms.tolist()]) == storm
                        )
                        rows.append(
                            _metric_record(
                                class_truth[storm_index],
                                class_pred[storm_index],
                                class_storms[storm_index],
                                wind_averaging=period,
                                subset=subset,
                                row_kind="storm",
                                intensity_class=name,
                                storm_id=storm,
                                n_resamples=n_resamples,
                                seed=seed,
                                ci_level=ci_level,
                            )
                        )
    return pd.DataFrame(rows, columns=list(_CLASS_TABLE_COLUMNS))


def mc_dropout_intervals(
    samples: np.ndarray, level: float
) -> tuple[np.ndarray, np.ndarray]:
    """Central interval from draws shaped ``(n_draws, n_rows)``.

    The draws are an array. Nothing here runs a network.
    """
    (level,) = _check_levels((level,))
    draws = np.asarray(samples, dtype=np.float64)
    if draws.ndim != 2 or draws.shape[0] < 2:
        raise ValueError("samples must have shape (n_draws, n_rows) with at least 2 draws")
    if not np.isfinite(draws).all():
        raise ValueError("MC-dropout samples must be finite")
    alpha = (1.0 - level) / 2.0
    lower = np.quantile(draws, alpha, axis=0, method="linear")
    upper = np.quantile(draws, 1.0 - alpha, axis=0, method="linear")
    return np.asarray(lower, dtype=np.float64), np.asarray(upper, dtype=np.float64)


def _sample_matrix(samples: np.ndarray, n_rows: int) -> np.ndarray:
    array = np.asarray(samples, dtype=np.float64)
    if array.ndim == 3 and array.shape[-1] == 1:
        array = array[..., 0]
    if array.ndim != 2:
        raise ValueError("MC-dropout samples must have shape (n_draws, n_rows)")
    if array.shape[0] == n_rows and array.shape[1] != n_rows:
        raise ValueError("samples must have shape (n_draws, n_rows), with draws on axis 0")
    if array.shape[0] < 2 or array.shape[1] != n_rows:
        raise ValueError(
            "samples must have shape (n_draws, n_rows) with at least 2 draws; "
            f"got {array.shape} for {n_rows} rows"
        )
    if not np.isfinite(array).all():
        raise ValueError("MC-dropout samples must be finite")
    return array


def mc_dropout_coverage(
    y_true: np.ndarray,
    samples: np.ndarray,
    levels: Sequence[float] = _LEVELS,
    tolerance: float = _TOLERANCE,
) -> dict[str, dict]:
    """Empirical coverage of central intervals drawn from ``samples``.

    ``samples`` is ``(n_draws, n_rows)`` aligned with ``y_true``. A level whose
    coverage misses the nominal rate by more than ``tolerance`` is
    ``uncalibrated``.
    """
    truth = np.asarray(y_true, dtype=np.float64).ravel()
    if truth.size == 0 or not np.isfinite(truth).all():
        raise ValueError("MC-dropout coverage needs finite targets")
    draws = _sample_matrix(samples, truth.size)
    checked = _check_levels(levels)
    report: dict[str, dict] = {}
    for level in checked:
        lower, upper = mc_dropout_intervals(draws, level)
        covered = (truth >= lower) & (truth <= upper)
        empirical = float(np.mean(covered))
        report[_level_key(level)] = {
            "nominal": float(level),
            "empirical_coverage": empirical,
            "n": float(truth.size),
            "n_covered": float(np.sum(covered)),
            "mean_interval_width_kt": float(np.mean(upper - lower)),
            "status": interval_status(empirical, level, tolerance),
        }
    return report


def residual_quantile_coverage(
    y_true_val: np.ndarray,
    y_pred_val: np.ndarray,
    y_true_test: np.ndarray,
    y_pred_test: np.ndarray,
    levels: Sequence[float] = _LEVELS,
    tolerance: float = _TOLERANCE,
) -> dict[str, dict]:
    """Fit quantiles of ``|residual|`` on validation rows and score test rows.

    The half-width is the validation quantile at the nominal level. Test
    coverage is the fraction of test rows with ``|residual|`` at or below that
    width. Validation rows are not included in the coverage count.
    """
    val_truth = np.asarray(y_true_val, dtype=np.float64).ravel()
    val_pred = np.asarray(y_pred_val, dtype=np.float64).ravel()
    test_truth = np.asarray(y_true_test, dtype=np.float64).ravel()
    test_pred = np.asarray(y_pred_test, dtype=np.float64).ravel()
    if val_truth.shape != val_pred.shape or val_truth.size == 0:
        raise ValueError("validation residuals need a non-empty aligned pair")
    if test_truth.shape != test_pred.shape or test_truth.size == 0:
        raise ValueError("test residuals need a non-empty aligned pair")
    if not (
        np.isfinite(val_truth).all()
        and np.isfinite(val_pred).all()
        and np.isfinite(test_truth).all()
        and np.isfinite(test_pred).all()
    ):
        raise ValueError("residual-quantile inputs must be finite")
    val_abs = np.abs(val_pred - val_truth)
    test_abs = np.abs(test_pred - test_truth)
    report: dict[str, dict] = {}
    for level in _check_levels(levels):
        half_width = float(np.quantile(val_abs, level, method="linear"))
        covered = test_abs <= half_width
        empirical = float(np.mean(covered))
        report[_level_key(level)] = {
            "nominal": float(level),
            "absolute_residual_quantile_kt": half_width,
            "empirical_coverage": empirical,
            "n": float(test_truth.size),
            "n_covered": float(np.sum(covered)),
            "fit_split": "val",
            "eval_split": "test",
            "status": interval_status(empirical, level, tolerance),
        }
    return report


def compute_residual_quantiles(
    y_true_val: np.ndarray,
    y_pred_val: np.ndarray,
    y_true_test: np.ndarray,
    y_pred_test: np.ndarray,
    val_storms: Sequence[str],
    test_storms: Sequence[str],
    *,
    levels: Sequence[float] = _LEVELS,
    tolerance: float = _TOLERANCE,
    is_synthetic: bool = False,
) -> dict:
    """Compute held-out residual-quantile intervals matching ConfidenceScore schema."""
    val_clean = [str(s).strip() for s in val_storms if str(s).strip()]
    test_clean = [str(s).strip() for s in test_storms if str(s).strip()]
    if not val_clean:
        raise ValueError("val_storms must contain at least one storm id")
    if not test_clean:
        raise ValueError("test_storms must contain at least one storm id")

    levels_report = residual_quantile_coverage(
        y_true_val=y_true_val,
        y_pred_val=y_pred_val,
        y_true_test=y_true_test,
        y_pred_test=y_pred_test,
        levels=levels,
        tolerance=tolerance,
    )
    return {
        "fit_split": "val",
        "eval_split": "test",
        "val_storms": sorted(set(val_clean)),
        "test_storms": sorted(set(test_clean)),
        "synthetic": bool(is_synthetic),
        "levels": levels_report,
    }


def merge_residual_quantiles(
    metrics: dict,
    residual_block: dict,
    *,
    tolerance: float = _TOLERANCE,
    levels: Sequence[float] = _LEVELS,
) -> dict:
    """Merge residual quantile block into a run's metrics record."""
    result = dict(metrics)
    uncertainty = dict(result.get("uncertainty") or {})
    uncertainty["coverage_tolerance"] = float(tolerance)
    uncertainty["nominal_levels"] = [float(lvl) for lvl in levels]
    uncertainty["residual_quantile"] = residual_block
    result["uncertainty"] = uncertainty
    result["residual_quantile"] = residual_block
    if "synthetic" not in result or result.get("synthetic") is None:
        result["synthetic"] = bool(residual_block.get("synthetic", False))
    return result


def evaluate_run_directory(
    run_dir: str | Path,
    *,
    tolerance: float = _TOLERANCE,
    levels: Sequence[float] = _LEVELS,
) -> dict:
    """Evaluate an existing run directory without retraining.

    Computes held-out residual-quantile intervals (fit on val storms,
    evaluated on test storms) and merges the resulting block into metrics.json.
    Exports predictions.npz if not already present.
    """
    run_path = Path(run_dir)
    if not run_path.is_dir():
        raise FileNotFoundError(f"Run directory not found: {run_path}")

    metrics_file = run_path / "metrics.json"
    metrics: dict = {}
    if metrics_file.is_file():
        try:
            metrics = json.loads(metrics_file.read_text(encoding="utf-8"))
        except Exception:
            metrics = {}

    is_synth = metrics.get("is_synthetic", metrics.get("synthetic", False))
    if isinstance(is_synth, str):
        is_synth = is_synth.strip().lower() in ("true", "1", "yes")
    else:
        is_synth = bool(is_synth)

    npz_candidates = [
        run_path / "predictions.npz",
        run_path / "calibration.npz",
        run_path / "test_predictions.npz",
    ]
    npz_file = next((p for p in npz_candidates if p.is_file()), None)

    y_true_test = None
    y_pred_test = None
    mc_samples_test = None
    y_true_val = None
    y_pred_val = None
    mc_samples_val = None
    val_storms = []
    test_storms = []

    manifest_file = run_path / "split_manifest.csv"
    manifest_df = None
    if manifest_file.is_file():
        manifest_df = pd.read_csv(manifest_file)
        if "storm_id" in manifest_df.columns and "split" in manifest_df.columns:
            val_storms = sorted(manifest_df.loc[manifest_df["split"] == "val", "storm_id"].astype(str).unique())
            test_storms = sorted(manifest_df.loc[manifest_df["split"] == "test", "storm_id"].astype(str).unique())

    if not val_storms and isinstance(metrics.get("split_storm_ids"), dict):
        val_storms = sorted(str(s) for s in metrics["split_storm_ids"].get("val", []))
    if not test_storms and isinstance(metrics.get("split_storm_ids"), dict):
        test_storms = sorted(str(s) for s in metrics["split_storm_ids"].get("test", []))

    if npz_file is not None:
        data = dict(np.load(str(npz_file), allow_pickle=True))
        y_true_test = data.get("y_true_test", data.get("y_test", data.get("y_true")))
        if y_true_test is not None:
            y_true_test = np.asarray(y_true_test, dtype=np.float64).ravel()

        y_pred_test = data.get("y_pred_test", data.get("y_pred"))
        mc_test = data.get("mc_samples_test", data.get("mc_samples"))
        if mc_test is not None:
            mc_test = np.asarray(mc_test, dtype=np.float64)
            if mc_test.ndim == 1 and y_true_test is not None:
                mc_test = mc_test.reshape(1, -1)
            elif y_true_test is not None and mc_test.ndim > 1 and mc_test.shape[1] != y_true_test.size and mc_test.shape[0] == y_true_test.size:
                mc_test = mc_test.T
            mc_samples_test = mc_test
            if y_pred_test is None and mc_test.ndim > 1:
                y_pred_test = np.mean(mc_test, axis=0)

        if y_pred_test is not None:
            y_pred_test = np.asarray(y_pred_test, dtype=np.float64).ravel()

        y_true_val = data.get("y_true_val", data.get("y_val"))
        if y_true_val is not None:
            y_true_val = np.asarray(y_true_val, dtype=np.float64).ravel()

        y_pred_val = data.get("y_pred_val")
        mc_val = data.get("mc_samples_val")
        if mc_val is not None:
            mc_val = np.asarray(mc_val, dtype=np.float64)
            if mc_val.ndim == 1 and y_true_val is not None:
                mc_val = mc_val.reshape(1, -1)
            elif y_true_val is not None and mc_val.ndim > 1 and mc_val.shape[1] != y_true_val.size and mc_val.shape[0] == y_true_val.size:
                mc_val = mc_val.T
            mc_samples_val = mc_val
            if y_pred_val is None and mc_val.ndim > 1:
                y_pred_val = np.mean(mc_val, axis=0)

        if y_pred_val is not None:
            y_pred_val = np.asarray(y_pred_val, dtype=np.float64).ravel()

    if y_true_test is None or y_pred_test is None or y_true_val is None or y_pred_val is None:
        if manifest_df is not None:
            pred_col = next((c for c in ("y_pred", "pred", "predicted_wind_kt") if c in manifest_df.columns), None)
            wind_col = next((c for c in ("wind_speed_kt", "target", "wind_kt", "wind_kt_3min") if c in manifest_df.columns), None)
            if pred_col and wind_col:
                v_mask = manifest_df["split"].astype(str) == "val"
                t_mask = manifest_df["split"].astype(str) == "test"
                y_true_val = manifest_df.loc[v_mask, wind_col].to_numpy(dtype=np.float64)
                y_pred_val = manifest_df.loc[v_mask, pred_col].to_numpy(dtype=np.float64)
                y_true_test = manifest_df.loc[t_mask, wind_col].to_numpy(dtype=np.float64)
                y_pred_test = manifest_df.loc[t_mask, pred_col].to_numpy(dtype=np.float64)

        if y_true_test is None or y_pred_test is None or y_true_val is None or y_pred_val is None:
            ckpt_name = metrics.get("checkpoint_name", "checkpoint.pt")
            ckpt_path = run_path / ckpt_name
            if not ckpt_path.is_file():
                candidates = list(run_path.glob("*.pt")) + list(run_path.glob("*.joblib"))
                if candidates:
                    ckpt_path = candidates[0]
            if not ckpt_path.is_file():
                raise FileNotFoundError(
                    f"Neither predictions (.npz) nor checkpoint (.pt) found in {run_path}"
                )
            if manifest_df is None:
                raise FileNotFoundError(f"split_manifest.csv required for checkpoint inference in {run_path}")

            import yaml
            from src.train import (
                PathFrames,
                _collect_predictions,
                _path_records,
                _torch,
                build_loader,
                build_net,
                execution_policy,
                training_wind_column,
            )

            torch = _torch()
            cfg_file = run_path / "resolved_config.yaml"
            if not cfg_file.is_file():
                cfg_file = Path("config/config.yaml")
            resolved = yaml.safe_load(cfg_file.read_text(encoding="utf-8")) if cfg_file.is_file() else {}

            payload = torch.load(ckpt_path, map_location="cpu", weights_only=False)
            model = build_net(resolved, size_head=payload.get("size_head", False))
            model.load_state_dict(payload["state_dict"])
            model.eval()

            wind_column = payload.get("label_column") or training_wind_column(resolved)
            image_size = int(payload.get("image_size", (resolved.get("data") or {}).get("image_size", 128)))
            norm_mean = float(payload.get("norm_mean", 0.0))
            norm_std = float(payload.get("norm_std", 1.0))
            max_missing = float(payload.get("max_missing_fraction", 0.3))
            known = list(payload.get("class_names") or (resolved.get("data") or {}).get("imd5_names", []))

            val_records = _path_records(manifest_df, manifest_file, "val", wind_column, None)
            test_records = _path_records(manifest_df, manifest_file, "test", wind_column, None)
            val_loader = build_loader(
                PathFrames(val_records, image_size, norm_mean, norm_std, max_missing, known),
                batch_size=int((resolved.get("train") or {}).get("batch_size", 32)),
                shuffle=False,
                num_workers=0,
            )
            test_loader = build_loader(
                PathFrames(test_records, image_size, norm_mean, norm_std, max_missing, known),
                batch_size=int((resolved.get("train") or {}).get("batch_size", 32)),
                shuffle=False,
                num_workers=0,
            )
            policy = execution_policy(resolved, torch.device("cpu"))
            val_truth, val_pred = _collect_predictions(model, val_loader, torch.device("cpu"), policy)
            test_truth, test_pred = _collect_predictions(model, test_loader, torch.device("cpu"), policy)

            y_true_val = val_truth
            y_pred_val = val_pred
            y_true_test = test_truth
            y_pred_test = test_pred

    out_npz = run_path / "predictions.npz"
    if not out_npz.is_file() and y_true_test is not None and y_pred_test is not None:
        np.savez(
            out_npz,
            y_true_test=y_true_test,
            y_pred_test=y_pred_test,
            mc_samples_test=mc_samples_test if mc_samples_test is not None else y_pred_test[None, :],
            y_true_val=y_true_val,
            y_pred_val=y_pred_val,
            mc_samples_val=mc_samples_val if mc_samples_val is not None else y_pred_val[None, :],
        )

    if not val_storms:
        val_storms = ["val_storm"]
    if not test_storms:
        test_storms = ["test_storm"]

    residual_block = compute_residual_quantiles(
        y_true_val=y_true_val,
        y_pred_val=y_pred_val,
        y_true_test=y_true_test,
        y_pred_test=y_pred_test,
        val_storms=val_storms,
        test_storms=test_storms,
        levels=levels,
        tolerance=tolerance,
        is_synthetic=is_synth,
    )

    merged = merge_residual_quantiles(metrics, residual_block, tolerance=tolerance, levels=levels)
    merged["synthetic"] = is_synth
    metrics_file.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")
    return merged


def _positions(frame: pd.DataFrame, split_name: str) -> np.ndarray:
    return np.flatnonzero(frame["split"].astype(str).to_numpy() == split_name)


def _ensure_split(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
    """Keep a complete storm split, or assign one. Random frame splits raise."""
    if "split" in frame.columns:
        if bool(frame["split"].isna().any()):
            raise LeakageError("split has nulls; refusing to fill them frame by frame")
        unknown = set(frame["split"].astype(str).unique()) - {"train", "val", "test"}
        if unknown:
            raise LeakageError(f"unknown splits: {sorted(unknown)}")
        return frame
    split_cfg = dict(config.get("split") or {})
    strategy = str(split_cfg.get("strategy", "storm_wise"))
    holdout_basin = split_cfg.get("holdout_basin") or None
    if holdout_basin in {None, "", "null"}:
        holdout_basin = None
    return assign_storms(
        frame,
        strategy,
        test_fraction=float(split_cfg.get("test_fraction", 0.2)),
        val_fraction=float(split_cfg.get("val_fraction", 0.2)),
        seed=int(split_cfg.get("seed", 0)),
        holdout_years=[int(year) for year in (split_cfg.get("holdout_years") or [])],
        holdout_basin=holdout_basin,
    )


def _require_finite_predictions(frame: pd.DataFrame, column: str, split_name: str) -> np.ndarray:
    if column not in frame.columns:
        raise ValueError(f"missing prediction column {column}")
    positions = _positions(frame, split_name)
    if positions.size == 0:
        raise ValueError(f"split {split_name} has no rows")
    values = pd.to_numeric(frame.iloc[positions][column], errors="coerce").to_numpy(dtype=np.float64)
    if not np.isfinite(values).all():
        raise ValueError(f"{split_name} predictions must be finite")
    return values


def _train_norm_stats(frame: pd.DataFrame, manifest: str | Path, config: dict):
    """Fit train-only pixel stats through the existing helper."""
    from src.train import fit_split_normalization

    prepared = frame.copy()
    if "_class" not in prepared.columns:
        prepared["_class"] = None
    stats = fit_split_normalization(prepared, manifest, config)
    if stats.source_split != "train":
        raise LeakageError("normalization stats may be fit on the train split only")
    return stats


def _synthetic_label(frame: pd.DataFrame) -> str:
    flags = frame["is_synthetic"].astype(bool)
    if bool(flags.all()):
        return "yes"
    if bool(flags.any()):
        return "mixed"
    return "no"


def _baseline_predictions(
    frame: pd.DataFrame,
    feature_names: Sequence[str],
    config: dict,
    train_pos: np.ndarray,
    test_pos: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, list[str], str, str]:
    """Fit mean and ridge on train rows. Return test predictions and fit notes."""
    names = tuple(feature_names)
    if not names:
        raise ValueError("ridge needs at least one feature column")
    train = frame.iloc[train_pos]
    test = frame.iloc[test_pos]
    x_train = model_matrix(train, names)
    x_test = model_matrix(test, names)
    y_train = train["wind_speed_kt"].to_numpy(dtype=np.float64)
    params = baseline_params(config)
    fitted: set[str] = set()
    seed = int(params["seed"])
    mean_hat, _mean_pipe, mean_note = fit_numeric_pipeline(
        x_train,
        y_train,
        x_test,
        task="regression",
        model_name="mean",
        params=params,
        seed=seed,
        train_storms=train["storm_id"].astype(str),
        fitted_storms=fitted,
    )
    ridge_hat, _ridge_pipe, ridge_note = fit_numeric_pipeline(
        x_train,
        y_train,
        x_test,
        task="regression",
        model_name="ridge",
        params=params,
        seed=seed,
        train_storms=train["storm_id"].astype(str),
        fitted_storms=fitted,
    )
    reference = mean_baseline(y_train, test_pos.size)
    if not np.allclose(mean_hat, reference):
        raise RuntimeError("mean baseline disagreed with src.metrics.mean_baseline")
    return (
        np.asarray(mean_hat, dtype=np.float64),
        np.asarray(ridge_hat, dtype=np.float64),
        sorted(fitted),
        str(mean_note),
        str(ridge_note),
    )


def _plain(value):
    if isinstance(value, np.ndarray):
        return _plain(value.tolist())
    if isinstance(value, dict):
        return {str(key): _plain(item) for key, item in value.items()}
    if isinstance(value, (list, tuple)):
        return [_plain(item) for item in value]
    if isinstance(value, (np.floating, float)):
        number = float(value)
        if not np.isfinite(number):
            return None
        return number
    if isinstance(value, (np.integer,)):
        return int(value)
    if isinstance(value, (np.bool_,)):
        return bool(value)
    return value


def _csv_metric_row(series: str, bin_name: str, metrics: dict, report: dict) -> dict:
    return {
        "series": series,
        "bin": bin_name,
        "n": metrics.get("n"),
        "mae_kt": metrics.get("mae_kt"),
        "rmse_kt": metrics.get("rmse_kt"),
        "bias_kt": metrics.get("bias_kt"),
        "wind_averaging": report["wind_averaging"],
        "binning": report["binning"],
        "quote_as_result": report["quote_as_result"],
        "synthetic": report["synthetic"],
        "status": "",
    }


def _metric_table(report: dict) -> pd.DataFrame:
    rows: list[dict] = []
    blocks = (
        ("model", report["model"]),
        ("mean", report["baselines"]["mean"]),
        ("ridge", report["baselines"]["ridge"]),
        ("persistence", report["baselines"]["persistence"]),
        ("paired_model", report["baselines"]["paired"]["model"]),
        ("paired_mean", report["baselines"]["paired"]["mean"]),
        ("paired_ridge", report["baselines"]["paired"]["ridge"]),
        ("paired_persistence", report["baselines"]["paired"]["persistence"]),
    )
    for series, block in blocks:
        rows.append(_csv_metric_row(series, "overall", block["overall"], report))
        for name, metrics in block["by_bin"].items():
            rows.append(_csv_metric_row(series, name, metrics, report))
    uncertainty = report["uncertainty"]
    for method in ("mc_dropout", "residual_quantile"):
        payload = uncertainty.get(method)
        if not payload:
            continue
        for level, metrics in payload["levels"].items():
            rows.append(
                {
                    "series": method,
                    "bin": level,
                    "n": metrics.get("n"),
                    "mae_kt": None,
                    "rmse_kt": None,
                    "bias_kt": None,
                    "wind_averaging": report["wind_averaging"],
                    "binning": report["binning"],
                    "quote_as_result": report["quote_as_result"],
                    "synthetic": report["synthetic"],
                    "status": metrics.get("status"),
                    "nominal": metrics.get("nominal"),
                    "empirical_coverage": metrics.get("empirical_coverage"),
                }
            )
    return pd.DataFrame(rows)


def save_error_by_bin(by_bin: dict[str, dict], names: Sequence[str], path: str | Path) -> Path:
    """Bar chart of MAE by bin. Empty bins are marked n=0 and have no bar."""
    plt = _pyplot()
    ordered = [str(name) for name in names]
    for code in HIGHLIGHT_CODES:
        if code not in ordered:
            ordered.append(code)
    values = []
    for name in ordered:
        mae = (by_bin.get(name) or _empty_metrics())["mae_kt"]
        values.append(np.nan if mae is None else float(mae))
    figure, axis = plt.subplots(figsize=(7.2, 4.4))
    positions = np.arange(len(ordered))
    finite = [value for value in values if np.isfinite(value)]
    for position, value in zip(positions, values, strict=True):
        if np.isfinite(value):
            color = "#9b2226" if ordered[position] in HIGHLIGHT_CODES else "#1d3557"
            axis.bar(position, value, color=color, width=0.72)
        else:
            axis.text(position, 0.0, "n=0", ha="center", va="bottom", fontsize=8, color="#6c757d")
    labels = [HIGHLIGHT_DISPLAY.get(name, name) for name in ordered]
    axis.set_xticks(positions, labels, rotation=20, ha="right")
    for tick, name in zip(axis.get_xticklabels(), ordered, strict=True):
        if name in HIGHLIGHT_CODES:
            tick.set_fontweight("bold")
    axis.set_ylabel("MAE (kt)")
    axis.set_xlabel(BINNING_LABEL)
    axis.set_title("Error by bin on held-out storms. VSCS and ESCS/SuCS are marked. Not a forecast.")
    if finite:
        axis.set_ylim(0.0, max(finite) * 1.25 + 1.0)
    else:
        axis.set_ylim(0.0, 1.0)
    figure.tight_layout()
    destination = Path(path)
    destination.parent.mkdir(parents=True, exist_ok=True)
    figure.savefig(destination, dpi=100)
    plt.close(figure)
    return destination


def save_coverage_figure(uncertainty: dict, path: str | Path) -> Path:
    """Nominal versus empirical coverage. Misses are annotated uncalibrated."""
    plt = _pyplot()
    figure, axis = plt.subplots(figsize=(5.6, 5.2))
    tolerance = float(uncertainty["coverage_tolerance"])
    grid = np.linspace(0.0, 1.0, 40)
    axis.fill_between(
        grid,
        grid - tolerance,
        grid + tolerance,
        color="#dee2e6",
        label="tolerance",
    )
    axis.plot([0.0, 1.0], [0.0, 1.0], color="#6c757d", linewidth=1)
    series = (
        ("MC dropout", uncertainty.get("mc_dropout"), "#1d3557"),
        ("residual quantile", uncertainty.get("residual_quantile"), "#9b2226"),
    )
    for label, payload, color in series:
        if not payload:
            continue
        nominals = []
        empiricals = []
        for row in payload["levels"].values():
            nominals.append(float(row["nominal"]))
            empiricals.append(float(row["empirical_coverage"]))
            if row["status"] == "uncalibrated":
                axis.annotate(
                    "uncalibrated",
                    (float(row["nominal"]), float(row["empirical_coverage"])),
                    textcoords="offset points",
                    xytext=(6, 6),
                    fontsize=8,
                    color=color,
                )
        axis.plot(nominals, empiricals, marker="o", color=color, label=label)
    axis.set_xlim(0.0, 1.0)
    axis.set_ylim(0.0, 1.0)
    axis.set_xlabel("Nominal coverage")
    axis.set_ylabel("Empirical coverage on test storms")
    axis.set_title("Held-out coverage. Not a calibrated forecast.")
    axis.legend(frameon=False)
    figure.tight_layout()
    destination = Path(path)
    destination.parent.mkdir(parents=True, exist_ok=True)
    figure.savefig(destination, dpi=100)
    plt.close(figure)
    return destination


def _write_report(report: dict, destination: Path) -> dict[str, str]:
    destination.mkdir(parents=True, exist_ok=True)
    _pyplot()
    (destination / "README.txt").write_text(BANNER + "\n", encoding="utf-8")
    metrics_path = destination / "metrics.json"
    table_path = destination / "metrics.csv"
    _metric_table(report).to_csv(table_path, index=False)
    test_truth = np.asarray(report["_plot_truth"], dtype=np.float64)
    test_pred = np.asarray(report["_plot_pred"], dtype=np.float64)
    parity = save_regression_scatter(
        test_truth,
        test_pred,
        destination / "parity.png",
        title="Held-out parity. Not a forecast.",
    )
    error_path = save_error_by_bin(
        report["model"]["by_bin"],
        report["bin_names"],
        destination / "error_by_bin.png",
    )
    coverage_path = save_coverage_figure(report["uncertainty"], destination / "coverage.png")
    outputs = {
        "metrics_json": str(metrics_path),
        "metrics_csv": str(table_path),
        "readme": str(destination / "README.txt"),
        "parity": str(parity),
        "error_by_bin": str(error_path),
        "coverage": str(coverage_path),
    }
    report["outputs"] = outputs
    public = {key: value for key, value in report.items() if not key.startswith("_")}
    metrics_path.write_text(json.dumps(_plain(public), indent=2) + "\n", encoding="utf-8")
    return outputs


def evaluate(
    frame: pd.DataFrame,
    manifest: str | Path,
    config: dict,
    *,
    feature_names: Sequence[str],
    prediction_column: str = "y_pred",
    out_dir: str | Path | None = None,
    levels: Sequence[float] = _LEVELS,
    coverage_tolerance: float | None = None,
    samples: np.ndarray | None = None,
    samples_aligned_to: str = "test",
) -> dict:
    """Score test storms and write figures plus a metrics file under ``out_dir``.

    ``frame`` carries the storm split, targets, predictions, and the feature
    columns used by ridge. Images referenced by ``manifest`` are used only to
    fit train normalization. Train storms are not part of the evaluated set.
    """
    limits = list((config.get("data") or {}).get("plausible_wind_kt") or [0, 200])
    work = require_valid(
        frame,
        wind_min_kt=float(limits[0]),
        wind_max_kt=float(limits[1]),
    )
    work = _ensure_split(work, config).reset_index(drop=True)
    groups = storm_ids_by_split(work)
    if not groups["train"] or not groups["val"] or not groups["test"]:
        raise LeakageError("train, val, and test storms are all required")
    if groups["train"] & groups["test"] or groups["train"] & groups["val"]:
        raise LeakageError("train storms leaked into a held-out split")
    edges, names = _bin_spec(config)
    wind_averaging = recorded_wind_averaging(work)
    train_pos = _positions(work, "train")
    val_pos = _positions(work, "val")
    test_pos = _positions(work, "test")
    evaluated = frozenset(work.iloc[test_pos]["storm_id"].astype(str))
    if evaluated & groups["train"]:
        raise LeakageError(f"train storms are in the evaluated set: {sorted(evaluated & groups['train'])}")
    if evaluated != groups["test"]:
        raise LeakageError("evaluated storms are not exactly the test storms")
    assert_no_forbidden_inputs(feature_names, "refusing to fit ridge on")
    val_pred = _require_finite_predictions(work, prediction_column, "val")
    test_pred = _require_finite_predictions(work, prediction_column, "test")
    val_truth = work.iloc[val_pos]["wind_speed_kt"].to_numpy(dtype=np.float64)
    test_truth = work.iloc[test_pos]["wind_speed_kt"].to_numpy(dtype=np.float64)
    stats = _train_norm_stats(work, manifest, config)
    checked_levels = _check_levels(levels)
    if coverage_tolerance is None:
        configured = dict(config.get("evaluate") or {})
        tolerance = float(configured.get("coverage_tolerance", _TOLERANCE))
    else:
        tolerance = float(coverage_tolerance)
    if tolerance < 0:
        raise ValueError("coverage tolerance must be non-negative")

    model_block = score_winds(test_truth, test_pred, edges, names)
    model_block["storms"] = sorted(evaluated)
    mean_hat, ridge_hat, fitted_ids, mean_note, ridge_note = _baseline_predictions(
        work, feature_names, config, train_pos, test_pos
    )
    fitted = frozenset(fitted_ids)
    if not fitted <= groups["train"]:
        raise LeakageError("baseline fit saw storms outside the training split")
    held_out = groups["val"] | groups["test"]
    if fitted & held_out:
        leaked = sorted(fitted & held_out)
        raise LeakageError(f"baseline fit saw held-out storms: {leaked}")

    persist_all = persistence_predictions(work)
    persist_test = persist_all[test_pos]
    paired = np.isfinite(persist_test)
    mean_block = score_winds(test_truth, mean_hat, edges, names)
    ridge_block = score_winds(test_truth, ridge_hat, edges, names)
    if int(np.sum(paired)) == 0:
        persistence_block = score_winds([], [], edges, names)
        paired_model = score_winds([], [], edges, names)
        paired_mean = score_winds([], [], edges, names)
        paired_ridge = score_winds([], [], edges, names)
        paired_persistence = score_winds([], [], edges, names)
    else:
        persistence_block = score_winds(test_truth[paired], persist_test[paired], edges, names)
        paired_model = score_winds(test_truth[paired], test_pred[paired], edges, names)
        paired_mean = score_winds(test_truth[paired], mean_hat[paired], edges, names)
        paired_ridge = score_winds(test_truth[paired], ridge_hat[paired], edges, names)
        paired_persistence = persistence_block
    persistence_storms = sorted(
        set(work.iloc[test_pos]["storm_id"].astype(str).to_numpy()[paired])
    )
    mean_block["storms"] = sorted(evaluated)
    ridge_block["storms"] = sorted(evaluated)
    persistence_block["storms"] = persistence_storms

    if samples is None:
        mc_report = None
    else:
        if samples_aligned_to == "test":
            draw_matrix = _sample_matrix(samples, test_pos.size)
            mc_truth = test_truth
        elif samples_aligned_to == "frame":
            draw_matrix = _sample_matrix(samples, len(work))[:, test_pos]
            mc_truth = test_truth
        else:
            raise ValueError("samples_aligned_to must be 'test' or 'frame'")
        mc_report = {
            "source": "sampled predictions",
            "imports_torch": False,
            "levels": mc_dropout_coverage(mc_truth, draw_matrix, checked_levels, tolerance),
        }
    residual_report = {
        "fit_split": "val",
        "eval_split": "test",
        "val_storms": sorted(groups["val"]),
        "test_storms": sorted(groups["test"]),
        "levels": residual_quantile_coverage(
            val_truth, val_pred, test_truth, test_pred, checked_levels, tolerance
        ),
    }
    reports_root = Path((config.get("paths") or {}).get("reports", "reports"))
    destination = Path(out_dir) if out_dir is not None else reports_root / "heldout"
    report = {
        "note": BANNER,
        "quote_as_result": "no",
        "present_as_forecast": False,
        "binning": BINNING_LABEL,
        "reported_especially": [HIGHLIGHT_DISPLAY[code] for code in HIGHLIGHT_CODES],
        "wind_averaging": wind_averaging,
        "wind_averaging_note": WIND_AVERAGING_NOTE,
        "edges_kt": [float(edge) for edge in edges],
        "bin_names": [str(name) for name in names],
        "eval_split": "test",
        "synthetic": _synthetic_label(work),
        "train_storms": sorted(groups["train"]),
        "val_storms": sorted(groups["val"]),
        "test_storms": sorted(groups["test"]),
        "evaluated_storms": sorted(evaluated),
        "normalization": {
            "mean": float(stats.mean),
            "std": float(stats.std),
            "source_split": str(stats.source_split),
            "helper": "src.train.fit_split_normalization",
        },
        "model": model_block,
        "baselines": {
            "fit_split": "train",
            "score_split": "test",
            "fitted_storms": sorted(fitted),
            "mean_fit_notes": mean_note,
            "ridge_fit_notes": ridge_note,
            "persistence_definition": (
                "reference baseline: previous best-track wind_speed_kt in the "
                "same storm, not the imagery; image-only models cannot be "
                "compared against it; the first frame of a storm is not scored"
            ),
            "mean": mean_block,
            "ridge": ridge_block,
            "persistence": persistence_block,
            "paired": {
                "rows": "test rows with a previous best-track wind in the same storm",
                "model": paired_model,
                "mean": paired_mean,
                "ridge": paired_ridge,
                "persistence": paired_persistence,
            },
        },
        "uncertainty": {
            "coverage_tolerance": tolerance,
            "nominal_levels": [float(level) for level in checked_levels],
            "mc_dropout": mc_report,
            "residual_quantile": residual_report,
        },
        "_plot_truth": test_truth,
        "_plot_pred": test_pred,
    }
    _write_report(report, destination)
    return {key: value for key, value in report.items() if not key.startswith("_")}


def main(argv: list[str] | None = None) -> dict:
    """CLI entry point. Prints paths and the honesty banner, not a score to quote."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--run-dir",
        type=Path,
        default=None,
        help="Path to an existing run directory to evaluate and compute held-out residual quantiles",
    )
    parser.add_argument("--config", type=Path, default=None)
    parser.add_argument(
        "--frame",
        type=Path,
        default=None,
        help="CSV with storms, winds, y_pred, and features",
    )
    parser.add_argument(
        "--manifest",
        type=Path,
        default=None,
        help="Path used to resolve image_path. Defaults to --frame.",
    )
    parser.add_argument("--features", nargs="*", default=None)
    parser.add_argument("--prediction-column", default="y_pred")
    parser.add_argument("--out", type=Path, default=None)
    parser.add_argument("--levels", nargs="+", type=float, default=list(_LEVELS))
    parser.add_argument("--coverage-tolerance", type=float, default=None)
    parser.add_argument(
        "--samples",
        type=Path,
        default=None,
        help="NPY array of MC-dropout draws, shape (n_draws, n_test_rows)",
    )
    parser.add_argument(
        "--samples-aligned-to",
        choices=("test", "frame"),
        default="test",
    )
    args = parser.parse_args(argv)
    if args.run_dir is not None:
        tol = _TOLERANCE if args.coverage_tolerance is None else float(args.coverage_tolerance)
        merged = evaluate_run_directory(
            args.run_dir,
            tolerance=tol,
            levels=args.levels,
        )
        print(f"Updated metrics.json with held-out residual quantiles in {args.run_dir}")
        return merged

    if args.config is None or args.frame is None or args.features is None:
        parser.error("--config, --frame, and --features are required when --run-dir is omitted.")
    config = load_config(args.config)
    table = pd.read_csv(args.frame)
    samples = None if args.samples is None else np.load(args.samples)
    report = evaluate(
        table,
        args.manifest or args.frame,
        config,
        feature_names=args.features,
        prediction_column=args.prediction_column,
        out_dir=args.out,
        levels=args.levels,
        coverage_tolerance=args.coverage_tolerance,
        samples=samples,
        samples_aligned_to=args.samples_aligned_to,
    )
    print(BANNER)
    print(f"wind_averaging={report['wind_averaging']}")
    print("quote_as_result=no")
    print(f"Wrote {report['outputs']['metrics_json']}")
    return report


if __name__ == "__main__":
    main()