File size: 60,370 Bytes
dfb3947
 
883e092
dfb3947
 
 
 
 
883e092
 
 
dfb3947
 
883e092
 
dfb3947
 
 
883e092
dfb3947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883e092
 
 
 
 
dfb3947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883e092
 
dfb3947
 
883e092
 
dfb3947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883e092
 
 
 
 
 
 
 
 
 
dfb3947
883e092
 
 
 
 
 
 
 
 
dfb3947
 
883e092
 
 
 
 
 
dfb3947
 
 
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
 
883e092
dfb3947
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
883e092
dfb3947
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
883e092
 
dfb3947
883e092
dfb3947
883e092
 
 
 
 
 
dfb3947
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
883e092
 
 
 
dfb3947
883e092
 
 
 
 
 
dfb3947
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
883e092
dfb3947
 
 
 
 
 
 
 
 
 
883e092
dfb3947
 
 
 
 
 
 
 
 
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
883e092
dfb3947
 
 
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
 
 
 
 
 
 
883e092
dfb3947
 
 
 
 
883e092
dfb3947
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
 
 
 
 
 
 
 
 
 
883e092
 
dfb3947
 
 
 
 
 
 
 
 
 
 
 
 
 
883e092
 
 
 
 
dfb3947
 
 
 
883e092
 
 
dfb3947
 
 
 
883e092
 
 
dfb3947
 
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
 
 
 
 
 
 
 
 
883e092
 
 
 
 
 
 
dfb3947
 
 
 
883e092
 
dfb3947
 
 
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883e092
dfb3947
 
 
 
 
 
 
 
 
 
883e092
 
 
dfb3947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883e092
 
 
 
dfb3947
 
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883e092
 
 
 
 
dfb3947
 
 
 
 
 
 
 
 
883e092
 
dfb3947
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Evaluate automatic-pick JSONL against the continuous-waveform data product.

Main features
-------------
1. Stream-read huge JSONL auto-pick files, e.g. >40 GB.
2. Build a fast per-station / per-phase / per-second SQLite index for auto picks.
3. Match reference and automatic picks one-to-one with a configurable tolerance.
4. Normalize generic and regional phase names (P/Pg/Pn and S/Sg/Sn).
5. Report label-centred recall and pick-centred matched fractions separately.
6. Separate statistics for manual labels only and all labels.
7. Count automatic picks in the SQLite index.
8. Qualify labels with exact NSLC intervals and finite HDF5 samples.
9. Optionally export residual diagnostics for workflow inspection.

Typical usage
-------------
python scripts/evaluate_picks.py \
  --auto-jsonl data/picks/phasenet.pick.jsonl \
  --label-json data/label/annotations_for_continuous_hdf5.json \
  --index-db data/picks/phasenet.pick.index.sqlite \
  --outdir eval_phasenet \
  --build-index \
  --tp-tol 1.5 \
  --err-window 5.0

If the SQLite index already exists, omit --build-index.
"""

from __future__ import annotations

import argparse
import json
import math
import os
import sqlite3
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

import bisect

import numpy as np

try:
    import h5py
except Exception:  # pragma: no cover
    h5py = None

# matplotlib is only needed for --plot. Keep import lazy in plot_results().

try:
    from scipy import stats as scipy_stats
except Exception:  # pragma: no cover
    scipy_stats = None


# -----------------------------
# Time and phase normalization
# -----------------------------

def parse_utc_to_epoch_seconds(value: str) -> float:
    """Parse ISO UTC string to epoch seconds.

    Supports strings with or without trailing Z. Naive timestamps are treated as UTC.
    """
    if value is None:
        raise ValueError("time value is None")
    s = str(value).strip()
    if s.endswith("Z"):
        s = s[:-1] + "+00:00"
    dt = datetime.fromisoformat(s)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    else:
        dt = dt.astimezone(timezone.utc)
    return dt.timestamp()


def norm_location(loc: Optional[str]) -> str:
    if loc is None or loc == "":
        return "--"
    return str(loc)


def norm_station_id(station_id: Optional[str], network: Optional[str] = None,
                    station: Optional[str] = None, location: Optional[str] = None) -> str:
    """Normalize station id to network.station.location, using -- for empty location."""
    if station_id:
        parts = str(station_id).split(".")
        if len(parts) >= 3:
            return f"{parts[0]}.{parts[1]}.{norm_location(parts[2])}"
        return str(station_id)
    return f"{network}.{station}.{norm_location(location)}"


DEFAULT_PHASE_MAP = {
    "P": ["P", "Pg", "Pn"],
    "S": ["S", "Sg", "Sn"],
    "Pg": ["Pg"],
    "Sg": ["Sg"],
    "Pn": ["Pn"],
    "Sn": ["Sn"],
}


def parse_phase_map(text: Optional[str]) -> Dict[str, List[str]]:
    """Parse phase map string like 'P:Pg,Pn;S:Sg,Sn'."""
    if not text:
        return dict(DEFAULT_PHASE_MAP)
    phase_map: Dict[str, List[str]] = {}
    for item in text.split(";"):
        item = item.strip()
        if not item:
            continue
        left, right = item.split(":", 1)
        phase_map[left.strip()] = [x.strip() for x in right.split(",") if x.strip()]
    return phase_map


# -----------------------------
# SQLite index for huge JSONL
# -----------------------------

def connect_db(db_path: Path) -> sqlite3.Connection:
    """Open SQLite DB and automatically create its parent directory."""
    db_path = Path(db_path).expanduser().resolve()
    db_path.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(db_path))
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("PRAGMA synchronous=NORMAL;")
    conn.execute("PRAGMA temp_store=MEMORY;")
    conn.execute("PRAGMA cache_size=-200000;")  # about 200 MB
    return conn


def init_pick_index(conn: sqlite3.Connection, drop_existing: bool = False) -> None:
    cur = conn.cursor()
    if drop_existing:
        cur.execute("DROP TABLE IF EXISTS auto_picks")
    cur.execute(
        """
        CREATE TABLE IF NOT EXISTS auto_picks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            station_id TEXT NOT NULL,
            network TEXT,
            station TEXT,
            location TEXT,
            phase_name TEXT NOT NULL,
            time_epoch REAL NOT NULL,
            sec_key INTEGER NOT NULL,
            phase_prob REAL,
            polarity TEXT,
            polarity_prob REAL,
            snr REAL,
            amplitude REAL,
            h5_file TEXT,
            raw_json TEXT
        )
        """
    )
    cur.execute("CREATE INDEX IF NOT EXISTS idx_station_phase_sec ON auto_picks(station_id, phase_name, sec_key)")
    cur.execute("CREATE INDEX IF NOT EXISTS idx_station_sec ON auto_picks(station_id, sec_key)")
    cur.execute("CREATE INDEX IF NOT EXISTS idx_time ON auto_picks(time_epoch)")
    conn.commit()


def iter_jsonl(path: Path) -> Iterable[Dict[str, Any]]:
    with path.open("r", encoding="utf-8", errors="replace") as f:
        for line_no, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue
            try:
                yield json.loads(line)
            except json.JSONDecodeError as exc:
                print(f"[WARN] skip bad JSONL line {line_no}: {exc}", file=sys.stderr)


def build_auto_pick_index(
    auto_jsonl: Path,
    db_path: Path,
    batch_size: int = 50000,
    drop_existing: bool = False,
    keep_raw_json: bool = False,
    progress_every: int = 200000,
) -> None:
    auto_jsonl = Path(auto_jsonl).expanduser().resolve()
    db_path = Path(db_path).expanduser().resolve()
    if not auto_jsonl.exists():
        raise FileNotFoundError(f"auto JSONL not found: {auto_jsonl}")

    conn = connect_db(db_path)
    init_pick_index(conn, drop_existing=drop_existing)
    cur = conn.cursor()

    insert_sql = (
        "INSERT INTO auto_picks "
        "(station_id, network, station, location, phase_name, time_epoch, sec_key, "
        "phase_prob, polarity, polarity_prob, snr, amplitude, h5_file, raw_json) "
        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    )

    batch = []
    n = 0
    skipped = 0
    for rec in iter_jsonl(auto_jsonl):
        if rec.get("record_type") != "phase_pick":
            continue
        try:
            station_info = rec.get("station_info") or {}
            station_id = norm_station_id(
                station_info.get("station_id"),
                station_info.get("network"),
                station_info.get("station"),
                station_info.get("location"),
            )
            phase_name = str(rec.get("phase_name"))
            t = parse_utc_to_epoch_seconds(rec.get("phase_time"))
            sec_key = int(math.floor(t))
            raw_json = json.dumps(rec, ensure_ascii=False) if keep_raw_json else None
            batch.append((
                station_id,
                station_info.get("network"),
                station_info.get("station"),
                norm_location(station_info.get("location")),
                phase_name,
                t,
                sec_key,
                rec.get("phase_prob"),
                rec.get("polarity"),
                rec.get("polarity_prob"),
                rec.get("snr"),
                rec.get("amplitude"),
                rec.get("h5_file"),
                raw_json,
            ))
        except Exception as exc:
            skipped += 1
            if skipped <= 10:
                print(f"[WARN] skip record: {exc}", file=sys.stderr)
            continue

        if len(batch) >= batch_size:
            cur.executemany(insert_sql, batch)
            conn.commit()
            n += len(batch)
            batch.clear()
            if n % progress_every < batch_size:
                print(f"[INDEX] inserted {n:,} picks, skipped {skipped:,}")

    if batch:
        cur.executemany(insert_sql, batch)
        conn.commit()
        n += len(batch)

    conn.execute("ANALYZE")
    conn.commit()
    conn.close()
    print(f"[INDEX] done. inserted {n:,} picks, skipped {skipped:,}. db={db_path}")


# -----------------------------
# Label loading
# -----------------------------

@dataclass
class LabelPick:
    label_phase: str
    label_time_epoch: float
    station_id: str
    status: str
    event_id: Optional[str]
    distance_km: Optional[float]
    raw: Dict[str, Any]


def iter_label_picks(label_json: Path) -> Iterable[LabelPick]:
    with label_json.open("r", encoding="utf-8") as f:
        data = json.load(f)

    years = data.get("years", {})
    for _year_id, year_obj in years.items():
        for _day_id, day_obj in (year_obj.get("days") or {}).items():
            for event_id, event_obj in (day_obj.get("events") or {}).items():
                for station_id0, sta_obj in (event_obj.get("stations") or {}).items():
                    for p in (sta_obj.get("picks") or []):
                        try:
                            station_id = norm_station_id(
                                p.get("station_id") or station_id0,
                                p.get("network"),
                                p.get("station"),
                                p.get("location"),
                            )
                            yield LabelPick(
                                label_phase=str(p.get("phase")),
                                label_time_epoch=parse_utc_to_epoch_seconds(p.get("time")),
                                station_id=station_id,
                                status=str(p.get("status", "unknown")),
                                event_id=p.get("event_id") or event_id,
                                distance_km=p.get("distance_km"),
                                raw=p,
                            )
                        except Exception as exc:
                            print(f"[WARN] skip label pick in event={event_id}, station={station_id0}: {exc}", file=sys.stderr)


# -----------------------------
# Matching and statistics
# -----------------------------

# -----------------------------
# Waveform coverage index
# -----------------------------


@dataclass(frozen=True)
class CoverageSegment:
    start_epoch: float
    end_epoch: float
    delta: float
    sampling_rate: float
    npts: int
    dtype: str
    h5_file: Optional[Path]
    dataset_path: Optional[str]

class WaveformCoverageIndex:
    """Segment-level station, location, and channel-family coverage index.

    Intervals are merged only within the same NSLC channel. This preserves
    intra-day gaps and prevents state-of-health or low-rate channels from
    qualifying a reference arrival for a seismic picker. A ``--`` label
    location is treated as unspecified and may match one released location;
    explicit label locations are matched exactly. Floating-point HDF5 samples
    must be finite by default, so internal NaN intervals do not qualify.
    """

    def __init__(
        self,
        waveform_db: Path,
        channel_families: Sequence[str] = ("HH", "BH", "EH", "HN"),
        validate_finite_samples: bool = True,
    ) -> None:
        waveform_db = Path(waveform_db).expanduser().resolve()
        if not waveform_db.exists():
            raise FileNotFoundError(f"Waveform index DB not found: {waveform_db}")
        self.channel_families = tuple(str(x).upper() for x in channel_families)
        if not self.channel_families:
            raise ValueError("channel_families must contain at least one family")
        self._index: Dict[
            Tuple[str, str, str, str],
            Tuple[List[Tuple[float, float]], List[float]],
        ] = {}
        self._sample_rates: Dict[Tuple[str, str, str, str], List[float]] = {}
        self._segments: Dict[Tuple[str, str, str, str], List[CoverageSegment]] = {}
        self._segment_starts: Dict[Tuple[str, str, str, str], List[float]] = {}
        self._station_keys: Dict[str, List[Tuple[str, str, str, str]]] = defaultdict(list)
        self._db_path = waveform_db
        self._release_root = waveform_db.parents[2] if len(waveform_db.parents) >= 3 else waveform_db.parent
        self._validate_finite_samples_requested = bool(validate_finite_samples)
        self._validate_finite_samples = False
        self._h5_handles: Dict[Path, Any] = {}
        self._load(waveform_db)

    def _load(self, db_path: Path) -> None:
        """Load exact segment intervals and merge only overlapping NSLC rows."""
        conn = sqlite3.connect(str(db_path))
        columns = {
            str(row[1]) for row in conn.execute("PRAGMA table_info(waveform_segments)")
        }
        sample_columns = {"h5_file", "dataset_path", "sampling_rate", "npts", "dtype"}
        sample_fields_available = sample_columns.issubset(columns)
        self._validate_finite_samples = (
            self._validate_finite_samples_requested and sample_fields_available
        )
        if self._validate_finite_samples and h5py is None:
            raise RuntimeError("h5py is required for finite-sample coverage validation")
        extra_fields = (
            "h5_file, dataset_path, COALESCE(sampling_rate, 0.0), "
            "COALESCE(npts, 0), COALESCE(dtype, '')"
            if sample_fields_available
            else "NULL, NULL, 0.0, 0, ''"
        )
        sql = f"""
            SELECT network, station,
                   COALESCE(NULLIF(location, ''), '--') AS location,
                   channel, start_epoch, end_epoch,
                   COALESCE(delta, 0.0) AS delta,
                   {extra_fields}
            FROM waveform_segments
        """
        raw: Dict[Tuple[str, str, str, str], List[CoverageSegment]] = {}
        for row in conn.execute(sql):
            (
                network, station, location, channel, t0, t1, delta,
                h5_file, dataset_path, sampling_rate, npts, dtype,
            ) = row
            family = str(channel)[:2].upper()
            if family not in self.channel_families:
                continue
            station_key = f"{network}.{station}"
            key = (station_key, norm_location(location), family, str(channel).upper())
            resolved_h5: Optional[Path] = None
            if h5_file:
                candidate = Path(str(h5_file)).expanduser()
                if not candidate.is_absolute():
                    candidate = self._release_root / candidate
                resolved_h5 = candidate.resolve()
            raw.setdefault(key, []).append(
                CoverageSegment(
                    start_epoch=float(t0),
                    end_epoch=float(t1),
                    delta=float(delta or 0.0),
                    sampling_rate=float(sampling_rate or 0.0),
                    npts=int(npts or 0),
                    dtype=str(dtype or ""),
                    h5_file=resolved_h5,
                    dataset_path=str(dataset_path) if dataset_path else None,
                )
            )
        conn.close()

        # Adjacent samples from the same NSLC may be merged within one sample
        # interval. Larger gaps, including intra-day gaps, remain explicit.
        for key, segs in raw.items():
            segs.sort(key=lambda segment: (segment.start_epoch, segment.end_epoch))
            merged: List[Tuple[float, float]] = []
            for segment in segs:
                tolerance = max(1.0e-6, abs(segment.delta))
                if merged and segment.start_epoch <= merged[-1][1] + tolerance:
                    merged[-1] = (
                        merged[-1][0], max(merged[-1][1], segment.end_epoch)
                    )
                else:
                    merged.append((segment.start_epoch, segment.end_epoch))
            self._index[key] = (merged, [x[0] for x in merged])
            self._sample_rates[key] = sorted(
                {
                    segment.sampling_rate
                    if segment.sampling_rate > 0.0
                    else 1.0 / segment.delta
                    for segment in segs
                    if segment.sampling_rate > 0.0 or segment.delta > 0.0
                }
            )
            self._segments[key] = segs
            self._segment_starts[key] = [segment.start_epoch for segment in segs]
            self._station_keys[key[0]].append(key)

        n_sta = len(self._station_keys)
        n_seg = sum(len(v[0]) for v in self._index.values())
        print(
            f"[COVERAGE] loaded {n_sta} stations and {n_seg} NSLC intervals "
            f"for families {','.join(self.channel_families)} from {db_path.name}; "
            f"finite-sample validation={'on' if self._validate_finite_samples else 'off'}",
            file=sys.stderr,
        )

    def close(self) -> None:
        for handle in self._h5_handles.values():
            try:
                handle.close()
            except Exception:
                pass
        self._h5_handles.clear()

    def __del__(self) -> None:  # pragma: no cover - interpreter shutdown varies
        self.close()

    def _dataset(self, segment: CoverageSegment) -> Any:
        if segment.h5_file is None or segment.dataset_path is None:
            raise RuntimeError("waveform index row lacks HDF5 path metadata")
        handle = self._h5_handles.get(segment.h5_file)
        if handle is None:
            if not segment.h5_file.exists():
                raise FileNotFoundError(f"Indexed HDF5 file not found: {segment.h5_file}")
            handle = h5py.File(segment.h5_file, "r")
            self._h5_handles[segment.h5_file] = handle
        return handle[segment.dataset_path]

    @staticmethod
    def _floating_dtype(dtype: str) -> bool:
        try:
            return np.issubdtype(np.dtype(dtype), np.floating)
        except TypeError:
            return False

    def _covering_segments(
        self, key: Tuple[str, str, str, str], time_epoch: float
    ) -> List[CoverageSegment]:
        segments = self._segments.get(key, [])
        starts = self._segment_starts.get(key, [])
        idx = bisect.bisect_right(starts, time_epoch) - 1
        matches: List[CoverageSegment] = []
        while idx >= 0:
            segment = segments[idx]
            if segment.end_epoch + max(segment.delta, 1.0e-6) < time_epoch:
                break
            if segment.start_epoch <= time_epoch <= segment.end_epoch + max(segment.delta, 1.0e-6):
                matches.append(segment)
            idx -= 1
        return matches

    def _sample_is_finite(self, segment: CoverageSegment, time_epoch: float) -> bool:
        if not self._validate_finite_samples or not self._floating_dtype(segment.dtype):
            return True
        if segment.delta <= 0.0 or segment.npts <= 0:
            return False
        sample_offset = (time_epoch - segment.start_epoch) / segment.delta
        sample_index = int(math.floor(sample_offset + 0.5))
        if sample_index < 0 or sample_index >= segment.npts:
            return False
        value = self._dataset(segment)[sample_index]
        return bool(np.isfinite(value))

    def _key_has_point_coverage(
        self, key: Tuple[str, str, str, str], time_epoch: float
    ) -> bool:
        if not self._contains(self._index[key], time_epoch):
            return False
        return any(
            self._sample_is_finite(segment, time_epoch)
            for segment in self._covering_segments(key, time_epoch)
        )

    @staticmethod
    def _station_parts(station_id: str) -> Tuple[str, str]:
        parts = station_id.split(".")
        station_key = f"{parts[0]}.{parts[1]}" if len(parts) >= 2 else station_id
        location = norm_location(parts[2]) if len(parts) >= 3 else "--"
        return station_key, location

    @staticmethod
    def _contains(
        value: Tuple[List[Tuple[float, float]], List[float]],
        time_epoch: float,
    ) -> bool:
        intervals, starts = value
        idx = bisect.bisect_right(starts, time_epoch) - 1
        return idx >= 0 and intervals[idx][1] >= time_epoch

    @staticmethod
    def _component(channel: str) -> str:
        suffix = str(channel)[-1:].upper()
        if suffix in {"E", "1"}:
            return "H1"
        if suffix in {"N", "2"}:
            return "H2"
        if suffix in {"Z", "3"}:
            return "Z"
        return suffix

    def coverage_details(self, station_id: str, time_epoch: float) -> Dict[str, Any]:
        """Return auditable point-coverage details for one reference arrival."""
        station_key, label_location = self._station_parts(station_id)
        keys = self._station_keys.get(station_key, [])
        if label_location != "--":
            keys = [key for key in keys if key[1] == label_location]

        candidates: List[Tuple[int, int, str, str, List[str]]] = []
        for family_rank, family in enumerate(self.channel_families):
            by_location: Dict[str, List[str]] = defaultdict(list)
            for key in keys:
                _, location, key_family, channel = key
                if key_family == family and self._key_has_point_coverage(key, time_epoch):
                    by_location[location].append(channel)
            for location, channels in by_location.items():
                components = {self._component(channel) for channel in channels}
                candidates.append(
                    (-len(components), family_rank, location, family, sorted(channels))
                )

        if not candidates:
            return {
                "point_covered": False,
                "station_key": station_key,
                "label_location": label_location,
                "matched_location": None,
                "channel_family": None,
                "component_count": 0,
                "channels": [],
                "location_match_mode": "exact" if label_location != "--" else "unspecified",
            }

        _, _, location, family, channels = min(candidates)
        return {
            "point_covered": True,
            "station_key": station_key,
            "label_location": label_location,
            "matched_location": location,
            "channel_family": family,
            "component_count": len({self._component(channel) for channel in channels}),
            "channels": channels,
            "location_match_mode": "exact" if label_location != "--" else "unspecified",
        }

    def has_coverage(self, station_id: str, time_epoch: float) -> bool:
        return bool(self.coverage_details(station_id, time_epoch)["point_covered"])

    def _covered_duration(
        self,
        key: Tuple[str, str, str, str],
        start_epoch: float,
        end_epoch: float,
    ) -> float:
        value = self._index[key]
        intervals, starts = value
        if end_epoch <= start_epoch or not intervals:
            return 0.0
        if not self._validate_finite_samples:
            idx = max(0, bisect.bisect_right(starts, start_epoch) - 1)
            covered = 0.0
            while idx < len(intervals):
                t0, t1 = intervals[idx]
                if t0 >= end_epoch:
                    break
                covered += max(0.0, min(t1, end_epoch) - max(t0, start_epoch))
                idx += 1
            return min(covered, end_epoch - start_epoch)

        covered = 0.0
        for segment in self._segments.get(key, []):
            delta = segment.delta
            if delta <= 0.0:
                continue
            segment_end_exclusive = segment.end_epoch + delta
            left = max(start_epoch, segment.start_epoch)
            right = min(end_epoch, segment_end_exclusive)
            if right <= left:
                continue
            if not self._floating_dtype(segment.dtype):
                covered += right - left
                continue
            i0 = max(
                0,
                int(math.ceil((left - segment.start_epoch) / delta - 1.0e-7)),
            )
            i1 = min(
                segment.npts,
                int(math.ceil((right - segment.start_epoch) / delta - 1.0e-7)),
            )
            if i1 <= i0:
                continue
            values = np.asarray(self._dataset(segment)[i0:i1])
            covered += float(np.count_nonzero(np.isfinite(values))) * delta
        return min(covered, end_epoch - start_epoch)

    def coverage_window_details(
        self,
        station_id: str,
        time_epoch: float,
        window_before_s: float,
        window_after_s: float,
        max_gap_fraction: float = 0.0,
        required_components: Sequence[str] = ("Z",),
    ) -> Dict[str, Any]:
        """Return point, window, and observed-component coverage details.

        C1 is satisfied when at least one observed component of the selected
        family/location meets ``max_gap_fraction``. C2 additionally requires
        every component named in ``required_components``. Component names use
        ``Z``, ``H1``, and ``H2``; copied or synthetic components are never
        introduced by this calculation.
        """
        before = float(window_before_s)
        after = float(window_after_s)
        if before < 0.0 or after < 0.0 or before + after <= 0.0:
            raise ValueError("window_before_s and window_after_s must define a positive window")
        if not 0.0 <= float(max_gap_fraction) <= 1.0:
            raise ValueError("max_gap_fraction must be between 0 and 1")
        required = tuple(str(item).upper() for item in required_components)
        unknown = set(required) - {"Z", "H1", "H2"}
        if unknown:
            raise ValueError(f"Unknown required components: {sorted(unknown)}")

        point = self.coverage_details(station_id, time_epoch)
        result = dict(point)
        result.update(
            {
                "window_start_epoch": time_epoch - before,
                "window_end_epoch": time_epoch + after,
                "window_before_s": before,
                "window_after_s": after,
                "max_gap_fraction": float(max_gap_fraction),
                "required_components": list(required),
                "component_gap_fractions": {},
                "component_channels": {},
                "component_sample_rates_hz": {},
                "window_gap_fraction": 1.0,
                "required_component_gap_fraction": 1.0,
                "window_covered": False,
                "component_covered": False,
            }
        )
        if not point["point_covered"]:
            return result

        station_key = str(point["station_key"])
        location = str(point["matched_location"])
        family = str(point["channel_family"])
        start_epoch = time_epoch - before
        end_epoch = time_epoch + after
        duration = end_epoch - start_epoch

        best_by_component: Dict[str, Tuple[float, str, List[float]]] = {}
        for key in self._station_keys.get(station_key, []):
            _, key_location, key_family, channel = key
            if key_location != location or key_family != family:
                continue
            component = self._component(channel)
            if component not in {"Z", "H1", "H2"}:
                continue
            covered = self._covered_duration(key, start_epoch, end_epoch)
            gap_fraction = max(0.0, 1.0 - covered / duration)
            candidate = (gap_fraction, channel, self._sample_rates.get(key, []))
            if component not in best_by_component or candidate[:2] < best_by_component[component][:2]:
                best_by_component[component] = candidate

        gaps = {component: item[0] for component, item in best_by_component.items()}
        result["component_gap_fractions"] = gaps
        result["component_channels"] = {
            component: item[1] for component, item in best_by_component.items()
        }
        result["component_sample_rates_hz"] = {
            component: item[2] for component, item in best_by_component.items()
        }
        if gaps:
            result["window_gap_fraction"] = min(gaps.values())
            result["window_covered"] = (
                result["window_gap_fraction"] <= float(max_gap_fraction)
            )
        if required and all(component in gaps for component in required):
            required_gap = max(gaps[component] for component in required)
            result["required_component_gap_fraction"] = required_gap
            result["component_covered"] = required_gap <= float(max_gap_fraction)
        return result

    def covered_networks(self) -> List[str]:
        return sorted({key.split(".")[0] for key in self._station_keys})


@dataclass
class MatchResult:
    subset: str
    label_phase: str
    station_id: str
    event_id: Optional[str]
    label_time_epoch: float
    matched: bool
    auto_pick_id: Optional[int] = None
    auto_phase: Optional[str] = None
    auto_time_epoch: Optional[float] = None
    residual_s: Optional[float] = None  # auto - label
    phase_prob: Optional[float] = None
    snr: Optional[float] = None
    distance_km: Optional[float] = None
    has_waveform: Optional[bool] = None   # True/False when waveform_db used; None otherwise


@dataclass
class AutoPickCandidate:
    auto_pick_id: int
    phase_name: str
    time_epoch: float
    residual_s: float
    phase_prob: Optional[float]
    snr: Optional[float]


@dataclass
class _MatchingState:
    tp_count: int
    matched_count: int
    residual_cost: float
    parent: int
    label_idx: int
    auto_idx: int


def match_labels_one_to_one(
    conn: sqlite3.Connection,
    labels: Sequence[LabelPick],
    auto_phases: Sequence[str],
    search_window_s: float,
    min_prob: Optional[float] = None,
    tp_tolerance_s: Optional[float] = None,
) -> Dict[int, AutoPickCandidate]:
    """Assign automatic picks once within one station--phase label group.

    Candidate edges form a sparse, time-ordered bipartite graph. A Fenwick-tree
    dynamic program first maximizes the number of assignments within
    ``tp_tolerance_s``, then the number within ``search_window_s``, and finally
    minimizes total absolute residual. The returned dictionary is keyed by the
    original local label index. No automatic-pick row can be assigned more than
    once.
    """
    if not labels:
        return {}
    station_ids = {label.station_id for label in labels}
    if len(station_ids) != 1:
        raise ValueError("one-to-one matching requires one station_id per group")
    station_id = next(iter(station_ids))
    t_min = min(label.label_time_epoch for label in labels) - search_window_s
    t_max = max(label.label_time_epoch for label in labels) + search_window_s
    sec0 = int(math.floor(t_min))
    sec1 = int(math.floor(t_max))
    placeholders = ",".join("?" for _ in auto_phases)
    params: List[Any] = [station_id, *auto_phases, sec0, sec1]
    prob_clause = ""
    if min_prob is not None:
        prob_clause = " AND phase_prob >= ?"
        params.append(float(min_prob))

    sql = f"""
        SELECT id, phase_name, time_epoch, phase_prob, snr
        FROM auto_picks
        WHERE station_id = ?
          AND phase_name IN ({placeholders})
          AND sec_key BETWEEN ? AND ?
          {prob_clause}
        ORDER BY time_epoch, id
    """
    rows = conn.execute(sql, params).fetchall()
    if not rows:
        return {}

    auto_times = [float(row[2]) for row in rows]
    tp_tolerance = (
        float(search_window_s)
        if tp_tolerance_s is None else float(tp_tolerance_s)
    )
    if tp_tolerance < 0 or tp_tolerance > search_window_s:
        raise ValueError("tp_tolerance_s must be within search_window_s")

    ordered_labels = sorted(
        enumerate(labels), key=lambda item: (item[1].label_time_epoch, item[0])
    )
    states: List[_MatchingState] = [
        _MatchingState(0, 0, 0.0, -1, -1, -1)
    ]
    fenwick = [0] * (len(rows) + 1)

    def better(left_id: int, right_id: int) -> int:
        left = states[left_id]
        right = states[right_id]
        left_key = (left.tp_count, left.matched_count, -left.residual_cost)
        right_key = (right.tp_count, right.matched_count, -right.residual_cost)
        if left_key != right_key:
            return left_id if left_key > right_key else right_id
        left_tie = (left.auto_idx, left.label_idx, left_id)
        right_tie = (right.auto_idx, right.label_idx, right_id)
        return left_id if left_tie < right_tie else right_id

    def query(auto_idx_exclusive: int) -> int:
        best_id = 0
        idx = auto_idx_exclusive
        while idx > 0:
            best_id = better(best_id, fenwick[idx])
            idx -= idx & -idx
        return best_id

    def update(auto_idx: int, state_id: int) -> None:
        idx = auto_idx + 1
        while idx < len(fenwick):
            fenwick[idx] = better(fenwick[idx], state_id)
            idx += idx & -idx

    for original_label_idx, label in ordered_labels:
        left = bisect.bisect_left(auto_times, label.label_time_epoch - search_window_s)
        right = bisect.bisect_right(auto_times, label.label_time_epoch + search_window_s)
        pending: List[Tuple[int, int]] = []
        for auto_idx in range(left, right):
            residual = auto_times[auto_idx] - label.label_time_epoch
            previous_id = query(auto_idx)
            previous = states[previous_id]
            state_id = len(states)
            states.append(
                _MatchingState(
                    tp_count=previous.tp_count + int(abs(residual) <= tp_tolerance),
                    matched_count=previous.matched_count + 1,
                    residual_cost=previous.residual_cost + abs(residual),
                    parent=previous_id,
                    label_idx=original_label_idx,
                    auto_idx=auto_idx,
                )
            )
            pending.append((auto_idx, state_id))
        # Defer updates until every candidate for this label has been scored;
        # this prevents two picks from being assigned to the same label.
        for auto_idx, state_id in pending:
            update(auto_idx, state_id)

    assignments: Dict[int, AutoPickCandidate] = {}
    state_id = query(len(rows))
    while state_id != 0:
        state = states[state_id]
        label_idx = state.label_idx
        auto_idx = state.auto_idx
        row = rows[auto_idx]
        residual = float(row[2]) - labels[label_idx].label_time_epoch
        assignments[label_idx] = AutoPickCandidate(
            auto_pick_id=int(row[0]),
            phase_name=str(row[1]),
            time_epoch=float(row[2]),
            residual_s=residual,
            phase_prob=row[3],
            snr=row[4],
        )
        state_id = state.parent
    return assignments


def evaluate(
    label_json: Path,
    db_path: Path,
    outdir: Path,
    phase_map: Dict[str, List[str]],
    tp_tol: float = 1.5,
    err_window: float = 5.0,
    min_prob: Optional[float] = None,
    waveform_db: Optional[Path] = None,
    coverage_channel_families: Sequence[str] = ("HH", "BH", "EH", "HN"),
    validate_finite_samples: bool = True,
) -> Tuple[List[MatchResult], Dict[str, Any]]:
    outdir = Path(outdir).expanduser().resolve()
    outdir.mkdir(parents=True, exist_ok=True)
    db_path = Path(db_path).expanduser().resolve()
    if not db_path.exists():
        raise FileNotFoundError(
            f"SQLite index DB not found: {db_path}. "
            "Run once with --build-index, or check --index-db."
        )
    conn = connect_db(db_path)

    # Optional waveform coverage filter
    cov_index: Optional[WaveformCoverageIndex] = None
    if waveform_db is not None:
        cov_index = WaveformCoverageIndex(
            Path(waveform_db),
            channel_families=coverage_channel_families,
            validate_finite_samples=validate_finite_samples,
        )

    results: List[MatchResult] = []
    label_counter = Counter()
    label_status_counter = Counter()
    labels = [lab for lab in iter_label_picks(label_json) if lab.label_phase in phase_map]
    coverage_cache: Dict[int, Optional[bool]] = {}
    for label_idx, lab in enumerate(labels):
        if lab.label_phase not in phase_map:
            continue
        label_counter[lab.label_phase] += 1
        label_status_counter[(lab.status, lab.label_phase)] += 1
        coverage_cache[label_idx] = (
            cov_index.has_coverage(lab.station_id, lab.label_time_epoch)
            if cov_index is not None else None
        )

    for subset in ("all", "manual", "automatic"):
        subset_labels = [
            (idx, lab)
            for idx, lab in enumerate(labels)
            if subset == "all" or lab.status == subset
        ]
        grouped: Dict[Tuple[str, str], List[Tuple[int, LabelPick]]] = defaultdict(list)
        for global_idx, lab in subset_labels:
            grouped[(lab.station_id, lab.label_phase)].append((global_idx, lab))

        assigned: Dict[int, AutoPickCandidate] = {}
        for (_, label_phase), group in grouped.items():
            local_labels = [lab for _, lab in group]
            local_assignments = match_labels_one_to_one(
                conn,
                local_labels,
                phase_map[label_phase],
                search_window_s=err_window,
                min_prob=min_prob,
                tp_tolerance_s=tp_tol,
            )
            for local_idx, candidate in local_assignments.items():
                assigned[group[local_idx][0]] = candidate

        for global_idx, lab in subset_labels:
            candidate = assigned.get(global_idx)
            has_waveform = coverage_cache[global_idx]
            if candidate is None:
                results.append(MatchResult(
                    subset=subset, label_phase=lab.label_phase, station_id=lab.station_id,
                    event_id=lab.event_id, label_time_epoch=lab.label_time_epoch,
                    matched=False, distance_km=lab.distance_km,
                    has_waveform=has_waveform,
                ))
            else:
                results.append(MatchResult(
                    subset=subset, label_phase=lab.label_phase, station_id=lab.station_id,
                    event_id=lab.event_id, label_time_epoch=lab.label_time_epoch,
                    matched=abs(candidate.residual_s) <= tp_tol,
                    auto_pick_id=candidate.auto_pick_id,
                    auto_phase=candidate.phase_name,
                    auto_time_epoch=candidate.time_epoch,
                    residual_s=candidate.residual_s,
                    phase_prob=candidate.phase_prob,
                    snr=candidate.snr,
                    distance_km=lab.distance_km, has_waveform=has_waveform,
                ))

    conn.close()
    if cov_index is not None:
        cov_index.close()

    summary = summarize_results(results, label_counter, label_status_counter, tp_tol, err_window)
    summary["auto_pick_count"] = get_auto_counts(db_path, min_prob=min_prob, phase_map=phase_map)
    add_pick_centered_metrics(summary, results, summary["auto_pick_count"], phase_map)
    summary["matching_policy"] = (
        "deterministic time-ordered one-to-one assignment that maximizes TP "
        "matches, then diagnostic-window matches, and then minimizes total "
        "absolute residual within each station, reference phase, and reported "
        "label subset"
    )
    summary["phase_map"] = phase_map
    summary["coverage_policy"] = {
        "source": str(Path(waveform_db)) if waveform_db is not None else None,
        "definition": (
            "point coverage from exact NSLC segment intervals with finite-sample "
            "validation for floating-point HDF5 arrays"
            if validate_finite_samples
            else "point coverage from exact NSLC segment intervals only"
        ),
        "channel_families": list(coverage_channel_families),
        "finite_sample_validation": bool(validate_finite_samples),
        "unspecified_location": "match one released location without combining locations",
    }
    write_outputs(results, summary, outdir)
    return results, summary


def fit_student_t(residuals: np.ndarray) -> Dict[str, Optional[float]]:
    if residuals.size < 3 or scipy_stats is None:
        return {"df": None, "loc": None, "scale": None}
    try:
        df, loc, scale = scipy_stats.t.fit(residuals)
        return {"df": float(df), "loc": float(loc), "scale": float(scale)}
    except Exception:
        return {"df": None, "loc": None, "scale": None}


def fit_gaussian(residuals: np.ndarray) -> Dict[str, Optional[float]]:
    """Maximum-likelihood Gaussian fit for residuals."""
    if residuals.size < 2:
        return {"mean": None, "std_mle": None, "std_unbiased": None}
    return {
        "mean": float(np.mean(residuals)),
        "std_mle": float(np.std(residuals, ddof=0)),
        "std_unbiased": float(np.std(residuals, ddof=1)),
    }


def get_auto_counts(
    db_path: Path,
    min_prob: Optional[float] = None,
    phase_map: Optional[Dict[str, List[str]]] = None,
) -> Dict[str, Any]:
    """Count automatic picks in the SQLite index.

    Returns original automatic phase counts, e.g. Pg/Sg, plus optional counts
    mapped to label phases, e.g. P->Pg and S->Sg. If min_prob is set, the
    counts are computed after applying phase_prob >= min_prob.
    """
    conn = connect_db(db_path)

    where = ""
    params: List[Any] = []
    if min_prob is not None:
        where = "WHERE phase_prob >= ?"
        params.append(float(min_prob))

    rows = conn.execute(
        f"SELECT phase_name, COUNT(*) FROM auto_picks {where} GROUP BY phase_name ORDER BY phase_name",
        params,
    ).fetchall()
    by_auto_phase = {str(ph): int(c) for ph, c in rows}
    total = int(sum(by_auto_phase.values()))

    mapped: Dict[str, int] = {}
    if phase_map:
        for label_phase, auto_phases in phase_map.items():
            mapped[label_phase] = int(sum(by_auto_phase.get(ap, 0) for ap in auto_phases))

    conn.close()
    return {
        "filter": {"min_prob": min_prob},
        "total": total,
        "by_auto_phase": by_auto_phase,
        "mapped_to_label_phase": mapped,
    }


def add_pick_centered_metrics(
    summary: Dict[str, Any],
    results: Sequence[MatchResult],
    auto_counts: Dict[str, Any],
    phase_map: Dict[str, List[str]],
) -> None:
    """Add pick-centered matched fractions to label-centered summaries.

    One-to-one assignment makes the matched-pick numerator unambiguous within
    each reported subset. The denominator contains all automatic picks whose
    normalized phase is eligible for that row after the probability filter.
    """
    by_auto_phase = auto_counts.get("by_auto_phase", {})
    for subset, subset_summary in summary["subsets"].items():
        subset_results = [result for result in results if result.subset == subset]
        reported_phases = [
            phase for phase in subset_summary if phase != "P_S_combined"
        ]
        for phase in reported_phases:
            eligible_phases = set(phase_map.get(phase, []))
            n_eligible = sum(int(by_auto_phase.get(name, 0)) for name in eligible_phases)
            matched_ids = {
                result.auto_pick_id
                for result in subset_results
                if result.label_phase == phase
                and result.matched
                and result.auto_pick_id is not None
            }
            phase_summary = subset_summary[phase]
            phase_summary["n_eligible_auto_picks"] = int(n_eligible)
            phase_summary["n_unique_auto_picks_matched_within_tp_tol"] = len(matched_ids)
            phase_summary["pick_matched_fraction"] = (
                len(matched_ids) / n_eligible if n_eligible else None
            )

        combined_auto_phases = {
            auto_phase
            for phase in reported_phases
            for auto_phase in phase_map.get(phase, [])
        }
        n_eligible_combined = sum(
            int(by_auto_phase.get(name, 0)) for name in combined_auto_phases
        )
        combined_matched_ids = {
            result.auto_pick_id
            for result in subset_results
            if result.label_phase in reported_phases
            and result.matched
            and result.auto_pick_id is not None
        }
        combined = subset_summary["P_S_combined"]
        combined["n_eligible_auto_picks"] = int(n_eligible_combined)
        combined["n_unique_auto_picks_matched_within_tp_tol"] = len(
            combined_matched_ids
        )
        combined["pick_matched_fraction"] = (
            len(combined_matched_ids) / n_eligible_combined
            if n_eligible_combined
            else None
        )


def summarize_results(
    results: List[MatchResult],
    label_counter: Counter,
    label_status_counter: Counter,
    tp_tol: float,
    err_window: float,
) -> Dict[str, Any]:
    summary: Dict[str, Any] = {
        "tp_tolerance_s": tp_tol,
        "residual_window_s": err_window,
        "label_phase_count_all_status": dict(label_counter),
        "label_phase_count_by_status": {f"{k[0]}:{k[1]}": v for k, v in label_status_counter.items()},
        "subsets": {},
    }

    for subset in sorted({r.subset for r in results}):
        subset_results = [r for r in results if r.subset == subset]
        phases = sorted({r.label_phase for r in subset_results})
        subset_summary: Dict[str, Any] = {}
        for ph in phases:
            ph_results = [r for r in subset_results if r.label_phase == ph]
            n_label = len(ph_results)
            n_tp = sum(1 for r in ph_results if r.matched)
            residuals = np.array([r.residual_s for r in ph_results if r.residual_s is not None and abs(r.residual_s) <= err_window], dtype=float)
            tp_residuals = np.array([r.residual_s for r in ph_results if r.matched and r.residual_s is not None], dtype=float)

            # Waveform-coverage-corrected recall: denominator is only labels that
            # have waveform data available (has_waveform=True). Labels where
            # has_waveform is None (waveform_db not supplied) are excluded from
            # the covered subset so the field stays None rather than 0/1.
            cov_results = [r for r in ph_results if r.has_waveform is True]
            n_label_cov = len(cov_results)
            n_tp_cov = sum(1 for r in cov_results if r.matched)
            # Distinguish "waveform_db not used" (all None) from "used but 0 covered"
            use_cov = any(r.has_waveform is not None for r in ph_results)

            phase_summary = {
                "n_label": int(n_label),
                "n_matched_within_tp_tol": int(n_tp),
                "recall": float(n_tp / n_label) if n_label else None,
                # Coverage-corrected metrics (only present when --waveform-db is used)
                "n_label_with_waveform": int(n_label_cov) if use_cov else None,
                "n_tp_with_waveform": int(n_tp_cov) if use_cov else None,
                "recall_covered": float(n_tp_cov / n_label_cov) if (use_cov and n_label_cov) else None,
                "n_residual_within_err_window": int(residuals.size),
                "residual_mean_s": float(np.mean(residuals)) if residuals.size else None,
                "residual_std_s": float(np.std(residuals, ddof=1)) if residuals.size > 1 else None,
                "residual_median_s": float(np.median(residuals)) if residuals.size else None,
                "residual_abs_p90_s": float(np.percentile(np.abs(residuals), 90)) if residuals.size else None,
                "residual_abs_p95_s": float(np.percentile(np.abs(residuals), 95)) if residuals.size else None,
                "tp_residual_std_s": float(np.std(tp_residuals, ddof=1)) if tp_residuals.size > 1 else None,
                "gaussian_fit_all_within_err_window": fit_gaussian(residuals),
                "student_t_fit_all_within_err_window": fit_student_t(residuals),
            }
            subset_summary[ph] = phase_summary

        # Combined P+S / Pg+Sg style summary
        n_label_all = len(subset_results)
        n_tp_all = sum(1 for r in subset_results if r.matched)
        cov_all = [r for r in subset_results if r.has_waveform is True]
        n_label_cov_all = len(cov_all)
        n_tp_cov_all = sum(1 for r in cov_all if r.matched)
        use_cov_all = any(r.has_waveform is not None for r in subset_results)
        subset_summary["P_S_combined"] = {
            "n_label": int(n_label_all),
            "n_matched_within_tp_tol": int(n_tp_all),
            "recall": float(n_tp_all / n_label_all) if n_label_all else None,
            "n_label_with_waveform": int(n_label_cov_all) if use_cov_all else None,
            "n_tp_with_waveform": int(n_tp_cov_all) if use_cov_all else None,
            "recall_covered": float(n_tp_cov_all / n_label_cov_all) if (use_cov_all and n_label_cov_all) else None,
        }
        summary["subsets"][subset] = subset_summary
    return summary


def write_outputs(results: List[MatchResult], summary: Dict[str, Any], outdir: Path) -> None:
    with (outdir / "summary.json").open("w", encoding="utf-8") as f:
        json.dump(summary, f, ensure_ascii=False, indent=2)

    with (outdir / "matches.jsonl").open("w", encoding="utf-8") as f:
        for r in results:
            f.write(json.dumps(r.__dict__, ensure_ascii=False) + "\n")

    with (outdir / "summary.tsv").open("w", encoding="utf-8") as f:
        f.write("subset\tphase\tn_label\tn_tp\trecall\tn_label_with_waveform\tn_tp_with_waveform\trecall_covered\tn_eligible_auto_picks\tn_unique_auto_picks_matched\tpick_matched_fraction\tn_residual\tmean_s\tstd_s\tmedian_s\tabs_p90_s\tabs_p95_s\tgauss_mean\tgauss_std_mle\tgauss_std_unbiased\tt_df\tt_loc\tt_scale\n")
        for subset, ss in summary["subsets"].items():
            for phase, d in ss.items():
                if phase == "P_S_combined":
                    continue
                gfit = d.get("gaussian_fit_all_within_err_window", {}) or {}
                tfit = d.get("student_t_fit_all_within_err_window", {}) or {}
                f.write("\t".join([
                    subset, phase,
                    str(d.get("n_label")), str(d.get("n_matched_within_tp_tol")), str(d.get("recall")),
                    str(d.get("n_label_with_waveform")), str(d.get("n_tp_with_waveform")), str(d.get("recall_covered")),
                    str(d.get("n_eligible_auto_picks")),
                    str(d.get("n_unique_auto_picks_matched_within_tp_tol")),
                    str(d.get("pick_matched_fraction")),
                    str(d.get("n_residual_within_err_window")), str(d.get("residual_mean_s")),
                    str(d.get("residual_std_s")), str(d.get("residual_median_s")),
                    str(d.get("residual_abs_p90_s")), str(d.get("residual_abs_p95_s")),
                    str(gfit.get("mean")), str(gfit.get("std_mle")), str(gfit.get("std_unbiased")),
                    str(tfit.get("df")), str(tfit.get("loc")), str(tfit.get("scale")),
                ]) + "\n")


def load_matches(path: Path) -> List[Dict[str, Any]]:
    rows = []
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            if line.strip():
                rows.append(json.loads(line))
    return rows


def plot_results(outdir: Path) -> None:
    import matplotlib.pyplot as plt

    matches_path = outdir / "matches.jsonl"
    if not matches_path.exists():
        print(f"[PLOT] missing {matches_path}", file=sys.stderr)
        return
    rows = load_matches(matches_path)
    plot_dir = outdir / "figures"
    plot_dir.mkdir(parents=True, exist_ok=True)

    # Residual distribution by subset and phase
    for subset in sorted({r["subset"] for r in rows}):
        for phase in sorted({r["label_phase"] for r in rows if r["subset"] == subset}):
            vals = np.array([
                r["residual_s"] for r in rows
                if r["subset"] == subset and r["label_phase"] == phase and r.get("residual_s") is not None
            ], dtype=float)
            if vals.size == 0:
                continue
            vals = vals[np.isfinite(vals)]
            if vals.size == 0:
                continue

            fig = plt.figure(figsize=(7.5, 4.8))
            plt.hist(vals, bins=100, density=True, alpha=0.55, label=f"Residuals (n={vals.size:,})")

            x_min, x_max = float(np.min(vals)), float(np.max(vals))
            if x_min == x_max:
                x_min -= 1.0
                x_max += 1.0
            x = np.linspace(x_min, x_max, 800)

            mu = float(np.mean(vals))
            sigma = float(np.std(vals, ddof=0)) if vals.size > 1 else 0.0
            if scipy_stats is not None and sigma > 0:
                gauss_pdf = scipy_stats.norm.pdf(x, loc=mu, scale=sigma)
                plt.plot(x, gauss_pdf, linewidth=2, label=f"Gaussian μ={mu:.3f}, σ={sigma:.3f}")

                if vals.size >= 3:
                    try:
                        df, loc, scale = scipy_stats.t.fit(vals)
                        if scale > 0:
                            t_pdf = scipy_stats.t.pdf(x, df, loc=loc, scale=scale)
                            plt.plot(x, t_pdf, linewidth=2, label=f"Student-t df={df:.2f}, loc={loc:.3f}, scale={scale:.3f}")
                    except Exception as exc:
                        print(f"[PLOT] Student-t fit failed for {subset}/{phase}: {exc}", file=sys.stderr)
            else:
                plt.text(
                    0.02, 0.95,
                    "Install scipy to overlay Gaussian/Student-t PDFs",
                    transform=plt.gca().transAxes,
                    va="top",
                )

            plt.axvline(0.0, linestyle="--", linewidth=1)
            plt.xlabel("Residual time: automatic - label (s)")
            plt.ylabel("Probability density")
            plt.title(f"Residual distribution with fits: {subset}, {phase}")
            plt.legend(fontsize=8)
            plt.tight_layout()
            fig.savefig(plot_dir / f"residual_fit_{subset}_{phase}.png", dpi=220)
            plt.close(fig)

    # Recall bar chart
    summary = json.loads((outdir / "summary.json").read_text(encoding="utf-8"))
    labels, vals = [], []
    for subset, ss in summary["subsets"].items():
        for phase, d in ss.items():
            if phase == "P_S_combined":
                continue
            if d.get("recall") is not None:
                labels.append(f"{subset}-{phase}")
                vals.append(d["recall"])
    if labels:
        fig = plt.figure(figsize=(max(7, 0.8 * len(labels)), 4.5))
        plt.bar(labels, vals)
        plt.ylim(0, 1)
        plt.ylabel("Recall")
        plt.title("Phase-pick recall")
        plt.xticks(rotation=45, ha="right")
        plt.tight_layout()
        fig.savefig(plot_dir / "recall_bar.png", dpi=200)
        plt.close(fig)


    # Automatic pick counts by original automatic phase
    auto_counts = summary.get("auto_pick_count", {}).get("by_auto_phase", {})
    if auto_counts:
        phases = list(auto_counts.keys())
        counts = [auto_counts[p] for p in phases]
        fig = plt.figure(figsize=(max(7, 0.8 * len(phases)), 4.5))
        plt.bar(phases, counts)
        plt.ylabel("Number of automatic picks")
        plt.title("Automatic pick counts by phase")
        plt.xticks(rotation=45, ha="right")
        plt.tight_layout()
        fig.savefig(plot_dir / "auto_pick_count_bar.png", dpi=220)
        plt.close(fig)
    print(f"[PLOT] saved figures to {plot_dir}")


# -----------------------------
# Optional utilities
# -----------------------------

def print_db_info(db_path: Path) -> None:
    db_path = Path(db_path).expanduser().resolve()
    if not db_path.exists():
        raise FileNotFoundError(f"SQLite index DB not found: {db_path}")
    conn = connect_db(db_path)
    n = conn.execute("SELECT COUNT(*) FROM auto_picks").fetchone()[0]
    print(f"auto_picks: {n:,}")
    print("phase counts:")
    for ph, c in conn.execute("SELECT phase_name, COUNT(*) FROM auto_picks GROUP BY phase_name ORDER BY COUNT(*) DESC"):
        print(f"  {ph}: {c:,}")
    conn.close()


# -----------------------------
# CLI
# -----------------------------

def main() -> None:
    parser = argparse.ArgumentParser(description="Evaluate automatic phase picks against continuous-HDF5 annotation JSON.")
    parser.add_argument("--auto-jsonl", type=Path, default=Path("data/picks/skynet.phase.jsonl"))
    parser.add_argument("--label-json", type=Path, default=Path("data/label/annotations_for_continuous_hdf5.json"))
    parser.add_argument("--index-db", type=Path, default=Path("~/skynet.pick.index.sqlite"))
    parser.add_argument("--outdir", type=Path, default=Path("eval_skynet"))
    parser.add_argument("--build-index", action="store_true", help="Build or update SQLite index from auto JSONL.")
    parser.add_argument("--drop-existing", action="store_true", help="Drop existing index table before rebuilding.")
    parser.add_argument("--keep-raw-json", action="store_true", help="Store raw JSON in SQLite. Not recommended for 40GB files.")
    parser.add_argument("--batch-size", type=int, default=50000)
    parser.add_argument("--tp-tol", type=float, default=1.5, help="TP tolerance in seconds.")
    parser.add_argument("--err-window", type=float, default=5.0, help="Window for residual distribution in seconds.")
    parser.add_argument("--min-prob", type=float, default=None, help="Optional minimum automatic pick probability.")
    parser.add_argument(
        "--phase-map", type=str, default=None,
        help="Override the default normalization 'P:P,Pg,Pn;S:S,Sg,Sn'.",
    )
    parser.add_argument("--waveform-db", type=Path, default=None,
                        help="Waveform coverage SQLite index (built by hdf5_waveform_index.py). "
                             "When supplied, each label is checked against exact NSLC segment intervals.")
    parser.add_argument(
        "--coverage-channel-families",
        default="HH,BH,EH,HN",
        help="Comma-separated seismic channel families used for point coverage.",
    )
    parser.add_argument(
        "--skip-finite-sample-check",
        action="store_true",
        help=(
            "Use indexed NSLC intervals without opening HDF5 samples. This is "
            "appropriate for download planning only, not coverage-qualified reporting."
        ),
    )
    parser.add_argument("--plot", action="store_true", help="Generate figures after evaluation.")
    parser.add_argument("--db-info", action="store_true", help="Only print index database info.")
    args = parser.parse_args()
    if not args.label_json.exists():
        mini_label = Path("data/label/annotations_mini_two_hours.json")
        if mini_label.exists():
            args.label_json = mini_label
    if not args.auto_jsonl.exists():
        mini_auto = Path("data/picks/pnsn_v3_diff.mini.phase.jsonl")
        if mini_auto.exists():
            args.auto_jsonl = mini_auto

    if args.build_index:
        build_auto_pick_index(
            args.auto_jsonl, args.index_db,
            batch_size=args.batch_size,
            drop_existing=args.drop_existing,
            keep_raw_json=args.keep_raw_json,
        )

    if args.db_info:
        print_db_info(args.index_db)
        return

    phase_map = parse_phase_map(args.phase_map)
    coverage_channel_families = tuple(
        value.strip().upper()
        for value in args.coverage_channel_families.split(",")
        if value.strip()
    )
    results, summary = evaluate(
        label_json=args.label_json,
        db_path=args.index_db,
        outdir=args.outdir,
        phase_map=phase_map,
        tp_tol=args.tp_tol,
        err_window=args.err_window,
        min_prob=args.min_prob,
        waveform_db=args.waveform_db,
        coverage_channel_families=coverage_channel_families,
        validate_finite_samples=not args.skip_finite_sample_check,
    )
    print(json.dumps(summary, ensure_ascii=False, indent=2))

    if args.plot:
        plot_results(args.outdir)


if __name__ == "__main__":
    main()