cangyeone commited on
Commit
2a8a916
·
verified ·
1 Parent(s): 7ece918

Upload scripts/evaluate_picks.py

Browse files
Files changed (1) hide show
  1. scripts/evaluate_picks.py +875 -0
scripts/evaluate_picks.py ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Evaluate PhaseNet/AI picks against continuous-HDF5 annotation JSON.
5
+
6
+ Main features
7
+ -------------
8
+ 1. Stream-read huge JSONL auto-pick files, e.g. >40 GB.
9
+ 2. Build a fast per-station / per-phase / per-second SQLite index for auto picks.
10
+ 3. Compare human/label picks with auto picks using a configurable TP tolerance.
11
+ 4. Report P/S recall where labels P/S map to auto Pg/Sg by default.
12
+ 5. Report travel-time residual distribution within a wider error window.
13
+ 6. Separate statistics for manual labels only and all labels.
14
+ 7. Count automatic picks in the SQLite index.
15
+ 8. Fit Gaussian and Student-t residual models.
16
+ 9. Plot residual histograms with fitted Gaussian and Student-t PDFs.
17
+
18
+ Typical usage
19
+ -------------
20
+ python scripts/evaluate_picks.py \
21
+ --auto-jsonl data/picks/phasenet.pick.jsonl \
22
+ --label-json data/label/annotations_for_continuous_hdf5.json \
23
+ --index-db ~/phasenet.pick.index.sqlite \
24
+ --outdir eval_picks/eval_phasenet \
25
+ --build-index \
26
+ --tp-tol 1.5 \
27
+ --err-window 5.0
28
+
29
+ If the SQLite index already exists, omit --build-index.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import math
37
+ import os
38
+ import sqlite3
39
+ import sys
40
+ from collections import Counter, defaultdict
41
+ from dataclasses import dataclass
42
+ from datetime import datetime, timezone
43
+ from pathlib import Path
44
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
45
+
46
+ import bisect
47
+
48
+ import numpy as np
49
+
50
+ # matplotlib is only needed for --plot. Keep import lazy in plot_results().
51
+
52
+ try:
53
+ from scipy import stats as scipy_stats
54
+ except Exception: # pragma: no cover
55
+ scipy_stats = None
56
+
57
+
58
+ # -----------------------------
59
+ # Time and phase normalization
60
+ # -----------------------------
61
+
62
+ def parse_utc_to_epoch_seconds(value: str) -> float:
63
+ """Parse ISO UTC string to epoch seconds.
64
+
65
+ Supports strings with or without trailing Z. Naive timestamps are treated as UTC.
66
+ """
67
+ if value is None:
68
+ raise ValueError("time value is None")
69
+ s = str(value).strip()
70
+ if s.endswith("Z"):
71
+ s = s[:-1] + "+00:00"
72
+ dt = datetime.fromisoformat(s)
73
+ if dt.tzinfo is None:
74
+ dt = dt.replace(tzinfo=timezone.utc)
75
+ else:
76
+ dt = dt.astimezone(timezone.utc)
77
+ return dt.timestamp()
78
+
79
+
80
+ def norm_location(loc: Optional[str]) -> str:
81
+ if loc is None or loc == "":
82
+ return "--"
83
+ return str(loc)
84
+
85
+
86
+ def norm_station_id(station_id: Optional[str], network: Optional[str] = None,
87
+ station: Optional[str] = None, location: Optional[str] = None) -> str:
88
+ """Normalize station id to network.station.location, using -- for empty location."""
89
+ if station_id:
90
+ parts = str(station_id).split(".")
91
+ if len(parts) >= 3:
92
+ return f"{parts[0]}.{parts[1]}.{norm_location(parts[2])}"
93
+ return str(station_id)
94
+ return f"{network}.{station}.{norm_location(location)}"
95
+
96
+
97
+ DEFAULT_PHASE_MAP = {
98
+ "P": ["Pg"],
99
+ "S": ["Sg"],
100
+ "Pg": ["Pg"],
101
+ "Sg": ["Sg"],
102
+ "Pn": ["Pg", "Pn", "P"],
103
+ "Sn": ["Sg", "Sn", "S"],
104
+ }
105
+
106
+
107
+ def parse_phase_map(text: Optional[str]) -> Dict[str, List[str]]:
108
+ """Parse phase map string like 'P:Pg,Pn;S:Sg,Sn'."""
109
+ if not text:
110
+ return dict(DEFAULT_PHASE_MAP)
111
+ phase_map: Dict[str, List[str]] = {}
112
+ for item in text.split(";"):
113
+ item = item.strip()
114
+ if not item:
115
+ continue
116
+ left, right = item.split(":", 1)
117
+ phase_map[left.strip()] = [x.strip() for x in right.split(",") if x.strip()]
118
+ return phase_map
119
+
120
+
121
+ # -----------------------------
122
+ # SQLite index for huge JSONL
123
+ # -----------------------------
124
+
125
+ def connect_db(db_path: Path) -> sqlite3.Connection:
126
+ """Open SQLite DB and automatically create its parent directory."""
127
+ db_path = Path(db_path).expanduser().resolve()
128
+ db_path.parent.mkdir(parents=True, exist_ok=True)
129
+ conn = sqlite3.connect(str(db_path))
130
+ conn.execute("PRAGMA journal_mode=WAL;")
131
+ conn.execute("PRAGMA synchronous=NORMAL;")
132
+ conn.execute("PRAGMA temp_store=MEMORY;")
133
+ conn.execute("PRAGMA cache_size=-200000;") # about 200 MB
134
+ return conn
135
+
136
+
137
+ def init_pick_index(conn: sqlite3.Connection, drop_existing: bool = False) -> None:
138
+ cur = conn.cursor()
139
+ if drop_existing:
140
+ cur.execute("DROP TABLE IF EXISTS auto_picks")
141
+ cur.execute(
142
+ """
143
+ CREATE TABLE IF NOT EXISTS auto_picks (
144
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
145
+ station_id TEXT NOT NULL,
146
+ network TEXT,
147
+ station TEXT,
148
+ location TEXT,
149
+ phase_name TEXT NOT NULL,
150
+ time_epoch REAL NOT NULL,
151
+ sec_key INTEGER NOT NULL,
152
+ phase_prob REAL,
153
+ polarity TEXT,
154
+ polarity_prob REAL,
155
+ snr REAL,
156
+ amplitude REAL,
157
+ h5_file TEXT,
158
+ raw_json TEXT
159
+ )
160
+ """
161
+ )
162
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_station_phase_sec ON auto_picks(station_id, phase_name, sec_key)")
163
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_station_sec ON auto_picks(station_id, sec_key)")
164
+ cur.execute("CREATE INDEX IF NOT EXISTS idx_time ON auto_picks(time_epoch)")
165
+ conn.commit()
166
+
167
+
168
+ def iter_jsonl(path: Path) -> Iterable[Dict[str, Any]]:
169
+ with path.open("r", encoding="utf-8", errors="replace") as f:
170
+ for line_no, line in enumerate(f, 1):
171
+ line = line.strip()
172
+ if not line:
173
+ continue
174
+ try:
175
+ yield json.loads(line)
176
+ except json.JSONDecodeError as exc:
177
+ print(f"[WARN] skip bad JSONL line {line_no}: {exc}", file=sys.stderr)
178
+
179
+
180
+ def build_auto_pick_index(
181
+ auto_jsonl: Path,
182
+ db_path: Path,
183
+ batch_size: int = 50000,
184
+ drop_existing: bool = False,
185
+ keep_raw_json: bool = False,
186
+ progress_every: int = 200000,
187
+ ) -> None:
188
+ auto_jsonl = Path(auto_jsonl).expanduser().resolve()
189
+ db_path = Path(db_path).expanduser().resolve()
190
+ if not auto_jsonl.exists():
191
+ raise FileNotFoundError(f"auto JSONL not found: {auto_jsonl}")
192
+
193
+ conn = connect_db(db_path)
194
+ init_pick_index(conn, drop_existing=drop_existing)
195
+ cur = conn.cursor()
196
+
197
+ insert_sql = (
198
+ "INSERT INTO auto_picks "
199
+ "(station_id, network, station, location, phase_name, time_epoch, sec_key, "
200
+ "phase_prob, polarity, polarity_prob, snr, amplitude, h5_file, raw_json) "
201
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
202
+ )
203
+
204
+ batch = []
205
+ n = 0
206
+ skipped = 0
207
+ for rec in iter_jsonl(auto_jsonl):
208
+ if rec.get("record_type") != "phase_pick":
209
+ continue
210
+ try:
211
+ station_info = rec.get("station_info") or {}
212
+ station_id = norm_station_id(
213
+ station_info.get("station_id"),
214
+ station_info.get("network"),
215
+ station_info.get("station"),
216
+ station_info.get("location"),
217
+ )
218
+ phase_name = str(rec.get("phase_name"))
219
+ t = parse_utc_to_epoch_seconds(rec.get("phase_time"))
220
+ sec_key = int(math.floor(t))
221
+ raw_json = json.dumps(rec, ensure_ascii=False) if keep_raw_json else None
222
+ batch.append((
223
+ station_id,
224
+ station_info.get("network"),
225
+ station_info.get("station"),
226
+ norm_location(station_info.get("location")),
227
+ phase_name,
228
+ t,
229
+ sec_key,
230
+ rec.get("phase_prob"),
231
+ rec.get("polarity"),
232
+ rec.get("polarity_prob"),
233
+ rec.get("snr"),
234
+ rec.get("amplitude"),
235
+ rec.get("h5_file"),
236
+ raw_json,
237
+ ))
238
+ except Exception as exc:
239
+ skipped += 1
240
+ if skipped <= 10:
241
+ print(f"[WARN] skip record: {exc}", file=sys.stderr)
242
+ continue
243
+
244
+ if len(batch) >= batch_size:
245
+ cur.executemany(insert_sql, batch)
246
+ conn.commit()
247
+ n += len(batch)
248
+ batch.clear()
249
+ if n % progress_every < batch_size:
250
+ print(f"[INDEX] inserted {n:,} picks, skipped {skipped:,}")
251
+
252
+ if batch:
253
+ cur.executemany(insert_sql, batch)
254
+ conn.commit()
255
+ n += len(batch)
256
+
257
+ conn.execute("ANALYZE")
258
+ conn.commit()
259
+ conn.close()
260
+ print(f"[INDEX] done. inserted {n:,} picks, skipped {skipped:,}. db={db_path}")
261
+
262
+
263
+ # -----------------------------
264
+ # Label loading
265
+ # -----------------------------
266
+
267
+ @dataclass
268
+ class LabelPick:
269
+ label_phase: str
270
+ label_time_epoch: float
271
+ station_id: str
272
+ status: str
273
+ event_id: Optional[str]
274
+ distance_km: Optional[float]
275
+ raw: Dict[str, Any]
276
+
277
+
278
+ def iter_label_picks(label_json: Path) -> Iterable[LabelPick]:
279
+ with label_json.open("r", encoding="utf-8") as f:
280
+ data = json.load(f)
281
+
282
+ years = data.get("years", {})
283
+ for _year_id, year_obj in years.items():
284
+ for _day_id, day_obj in (year_obj.get("days") or {}).items():
285
+ for event_id, event_obj in (day_obj.get("events") or {}).items():
286
+ for station_id0, sta_obj in (event_obj.get("stations") or {}).items():
287
+ for p in (sta_obj.get("picks") or []):
288
+ try:
289
+ station_id = norm_station_id(
290
+ p.get("station_id") or station_id0,
291
+ p.get("network"),
292
+ p.get("station"),
293
+ p.get("location"),
294
+ )
295
+ yield LabelPick(
296
+ label_phase=str(p.get("phase")),
297
+ label_time_epoch=parse_utc_to_epoch_seconds(p.get("time")),
298
+ station_id=station_id,
299
+ status=str(p.get("status", "unknown")),
300
+ event_id=p.get("event_id") or event_id,
301
+ distance_km=p.get("distance_km"),
302
+ raw=p,
303
+ )
304
+ except Exception as exc:
305
+ print(f"[WARN] skip label pick in event={event_id}, station={station_id0}: {exc}", file=sys.stderr)
306
+
307
+
308
+ # -----------------------------
309
+ # Matching and statistics
310
+ # -----------------------------
311
+
312
+ # -----------------------------
313
+ # Waveform coverage index
314
+ # -----------------------------
315
+
316
+ class WaveformCoverageIndex:
317
+ """In-memory coverage index built from the waveform SQLite index.
318
+
319
+ For each station_key (network.station), stores a sorted list of
320
+ (start_epoch, end_epoch) tuples. Coverage queries use bisect for
321
+ O(log N) lookup, so the 290 k label-pick loop stays fast.
322
+
323
+ Station matching ignores the location code, because the waveform index
324
+ uses 2-part keys (e.g. 'CI.AVM') while label station_ids are 3-part
325
+ (e.g. 'CI.AVM.--').
326
+ """
327
+
328
+ def __init__(self, waveform_db: Path) -> None:
329
+ waveform_db = Path(waveform_db).expanduser().resolve()
330
+ if not waveform_db.exists():
331
+ raise FileNotFoundError(f"Waveform index DB not found: {waveform_db}")
332
+ self._index: Dict[str, List[Tuple[float, float]]] = {}
333
+ self._load(waveform_db)
334
+
335
+ def _load(self, db_path: Path) -> None:
336
+ """Load all waveform segments into memory, merging by station_key."""
337
+ conn = sqlite3.connect(str(db_path))
338
+ # Load one row per (station_key, start_epoch, end_epoch); channel/location
339
+ # don't matter for coverage — any channel present means the station was processed.
340
+ sql = """
341
+ SELECT station_key, MIN(start_epoch) AS t0, MAX(end_epoch) AS t1
342
+ FROM waveform_segments
343
+ GROUP BY station_key, CAST(start_epoch / 86400 AS INTEGER)
344
+ ORDER BY station_key, t0
345
+ """
346
+ raw: Dict[str, List[Tuple[float, float]]] = {}
347
+ for row in conn.execute(sql):
348
+ key, t0, t1 = str(row[0]), float(row[1]), float(row[2])
349
+ raw.setdefault(key, []).append((t0, t1))
350
+ conn.close()
351
+
352
+ # Merge overlapping/adjacent intervals per station
353
+ for key, segs in raw.items():
354
+ segs.sort()
355
+ merged: List[Tuple[float, float]] = []
356
+ for t0, t1 in segs:
357
+ if merged and t0 <= merged[-1][1] + 1.0: # 1 s gap tolerance
358
+ merged[-1] = (merged[-1][0], max(merged[-1][1], t1))
359
+ else:
360
+ merged.append((t0, t1))
361
+ self._index[key] = merged
362
+
363
+ n_sta = len(self._index)
364
+ n_seg = sum(len(v) for v in self._index.values())
365
+ print(f"[COVERAGE] loaded {n_sta} stations, {n_seg} merged segments from {db_path.name}")
366
+
367
+ @staticmethod
368
+ def _station_key_from_id(station_id: str) -> str:
369
+ """Extract 'network.station' from a 3-part 'network.station.location' id."""
370
+ parts = station_id.split(".")
371
+ if len(parts) >= 2:
372
+ return f"{parts[0]}.{parts[1]}"
373
+ return station_id
374
+
375
+ def has_coverage(self, station_id: str, time_epoch: float) -> bool:
376
+ """Return True if any waveform segment covers *time_epoch* for this station."""
377
+ key = self._station_key_from_id(station_id)
378
+ segs = self._index.get(key)
379
+ if not segs:
380
+ return False
381
+ # Find the last segment whose start <= time_epoch
382
+ starts = [s[0] for s in segs]
383
+ idx = bisect.bisect_right(starts, time_epoch) - 1
384
+ if idx < 0:
385
+ return False
386
+ return segs[idx][1] >= time_epoch
387
+
388
+ def covered_networks(self) -> List[str]:
389
+ return sorted({k.split(".")[0] for k in self._index})
390
+
391
+
392
+ @dataclass
393
+ class MatchResult:
394
+ subset: str
395
+ label_phase: str
396
+ station_id: str
397
+ event_id: Optional[str]
398
+ label_time_epoch: float
399
+ matched: bool
400
+ auto_phase: Optional[str] = None
401
+ auto_time_epoch: Optional[float] = None
402
+ residual_s: Optional[float] = None # auto - label
403
+ phase_prob: Optional[float] = None
404
+ snr: Optional[float] = None
405
+ distance_km: Optional[float] = None
406
+ has_waveform: Optional[bool] = None # True/False when waveform_db used; None otherwise
407
+
408
+
409
+ def query_nearest_auto_pick(
410
+ conn: sqlite3.Connection,
411
+ station_id: str,
412
+ auto_phases: Sequence[str],
413
+ label_time_epoch: float,
414
+ search_window_s: float,
415
+ min_prob: Optional[float] = None,
416
+ ) -> Optional[Tuple[str, float, float, Optional[float], Optional[float]]]:
417
+ """Return nearest auto pick as (phase, time_epoch, residual, prob, snr)."""
418
+ sec0 = int(math.floor(label_time_epoch - search_window_s))
419
+ sec1 = int(math.floor(label_time_epoch + search_window_s))
420
+ placeholders = ",".join("?" for _ in auto_phases)
421
+ params: List[Any] = [station_id, *auto_phases, sec0, sec1]
422
+ prob_clause = ""
423
+ if min_prob is not None:
424
+ prob_clause = " AND phase_prob >= ?"
425
+ params.append(float(min_prob))
426
+
427
+ sql = f"""
428
+ SELECT phase_name, time_epoch, phase_prob, snr
429
+ FROM auto_picks
430
+ WHERE station_id = ?
431
+ AND phase_name IN ({placeholders})
432
+ AND sec_key BETWEEN ? AND ?
433
+ {prob_clause}
434
+ ORDER BY ABS(time_epoch - ?) ASC
435
+ LIMIT 1
436
+ """
437
+ params.append(float(label_time_epoch))
438
+ row = conn.execute(sql, params).fetchone()
439
+ if row is None:
440
+ return None
441
+ phase, t, prob, snr = row
442
+ residual = float(t) - float(label_time_epoch)
443
+ if abs(residual) > search_window_s:
444
+ return None
445
+ return phase, float(t), residual, prob, snr
446
+
447
+
448
+ def evaluate(
449
+ label_json: Path,
450
+ db_path: Path,
451
+ outdir: Path,
452
+ phase_map: Dict[str, List[str]],
453
+ tp_tol: float = 1.5,
454
+ err_window: float = 5.0,
455
+ min_prob: Optional[float] = None,
456
+ waveform_db: Optional[Path] = None,
457
+ ) -> Tuple[List[MatchResult], Dict[str, Any]]:
458
+ outdir = Path(outdir).expanduser().resolve()
459
+ outdir.mkdir(parents=True, exist_ok=True)
460
+ db_path = Path(db_path).expanduser().resolve()
461
+ if not db_path.exists():
462
+ raise FileNotFoundError(
463
+ f"SQLite index DB not found: {db_path}. "
464
+ "Run once with --build-index, or check --index-db."
465
+ )
466
+ conn = connect_db(db_path)
467
+
468
+ # Optional waveform coverage filter
469
+ cov_index: Optional[WaveformCoverageIndex] = None
470
+ if waveform_db is not None:
471
+ cov_index = WaveformCoverageIndex(Path(waveform_db))
472
+
473
+ results: List[MatchResult] = []
474
+ label_counter = Counter()
475
+ label_status_counter = Counter()
476
+
477
+ for lab in iter_label_picks(label_json):
478
+ if lab.label_phase not in phase_map:
479
+ continue
480
+ label_counter[lab.label_phase] += 1
481
+ label_status_counter[(lab.status, lab.label_phase)] += 1
482
+
483
+ # Waveform coverage check
484
+ has_waveform: Optional[bool] = None
485
+ if cov_index is not None:
486
+ has_waveform = cov_index.has_coverage(lab.station_id, lab.label_time_epoch)
487
+
488
+ auto_phases = phase_map[lab.label_phase]
489
+ # Search by wider window for residual distribution. TP uses tp_tol later.
490
+ nearest = query_nearest_auto_pick(
491
+ conn, lab.station_id, auto_phases, lab.label_time_epoch,
492
+ search_window_s=err_window, min_prob=min_prob,
493
+ )
494
+
495
+ for subset in ("all", "manual", "automatic"):
496
+ if subset == "manual" and lab.status != "manual":
497
+ continue
498
+ if subset == "automatic" and lab.status != "automatic":
499
+ continue
500
+ if nearest is None:
501
+ results.append(MatchResult(
502
+ subset=subset, label_phase=lab.label_phase, station_id=lab.station_id,
503
+ event_id=lab.event_id, label_time_epoch=lab.label_time_epoch,
504
+ matched=False, distance_km=lab.distance_km,
505
+ has_waveform=has_waveform,
506
+ ))
507
+ else:
508
+ auto_phase, auto_time, residual, prob, snr = nearest
509
+ results.append(MatchResult(
510
+ subset=subset, label_phase=lab.label_phase, station_id=lab.station_id,
511
+ event_id=lab.event_id, label_time_epoch=lab.label_time_epoch,
512
+ matched=abs(residual) <= tp_tol,
513
+ auto_phase=auto_phase, auto_time_epoch=auto_time,
514
+ residual_s=residual, phase_prob=prob, snr=snr,
515
+ distance_km=lab.distance_km, has_waveform=has_waveform,
516
+ ))
517
+
518
+ conn.close()
519
+
520
+ summary = summarize_results(results, label_counter, label_status_counter, tp_tol, err_window)
521
+ summary["auto_pick_count"] = get_auto_counts(db_path, min_prob=min_prob, phase_map=phase_map)
522
+ write_outputs(results, summary, outdir)
523
+ return results, summary
524
+
525
+
526
+ def fit_student_t(residuals: np.ndarray) -> Dict[str, Optional[float]]:
527
+ if residuals.size < 3 or scipy_stats is None:
528
+ return {"df": None, "loc": None, "scale": None}
529
+ try:
530
+ df, loc, scale = scipy_stats.t.fit(residuals)
531
+ return {"df": float(df), "loc": float(loc), "scale": float(scale)}
532
+ except Exception:
533
+ return {"df": None, "loc": None, "scale": None}
534
+
535
+
536
+ def fit_gaussian(residuals: np.ndarray) -> Dict[str, Optional[float]]:
537
+ """Maximum-likelihood Gaussian fit for residuals."""
538
+ if residuals.size < 2:
539
+ return {"mean": None, "std_mle": None, "std_unbiased": None}
540
+ return {
541
+ "mean": float(np.mean(residuals)),
542
+ "std_mle": float(np.std(residuals, ddof=0)),
543
+ "std_unbiased": float(np.std(residuals, ddof=1)),
544
+ }
545
+
546
+
547
+ def get_auto_counts(
548
+ db_path: Path,
549
+ min_prob: Optional[float] = None,
550
+ phase_map: Optional[Dict[str, List[str]]] = None,
551
+ ) -> Dict[str, Any]:
552
+ """Count automatic picks in the SQLite index.
553
+
554
+ Returns original automatic phase counts, e.g. Pg/Sg, plus optional counts
555
+ mapped to label phases, e.g. P->Pg and S->Sg. If min_prob is set, the
556
+ counts are computed after applying phase_prob >= min_prob.
557
+ """
558
+ conn = connect_db(db_path)
559
+
560
+ where = ""
561
+ params: List[Any] = []
562
+ if min_prob is not None:
563
+ where = "WHERE phase_prob >= ?"
564
+ params.append(float(min_prob))
565
+
566
+ rows = conn.execute(
567
+ f"SELECT phase_name, COUNT(*) FROM auto_picks {where} GROUP BY phase_name ORDER BY phase_name",
568
+ params,
569
+ ).fetchall()
570
+ by_auto_phase = {str(ph): int(c) for ph, c in rows}
571
+ total = int(sum(by_auto_phase.values()))
572
+
573
+ mapped: Dict[str, int] = {}
574
+ if phase_map:
575
+ for label_phase, auto_phases in phase_map.items():
576
+ mapped[label_phase] = int(sum(by_auto_phase.get(ap, 0) for ap in auto_phases))
577
+
578
+ conn.close()
579
+ return {
580
+ "filter": {"min_prob": min_prob},
581
+ "total": total,
582
+ "by_auto_phase": by_auto_phase,
583
+ "mapped_to_label_phase": mapped,
584
+ }
585
+
586
+
587
+ def summarize_results(
588
+ results: List[MatchResult],
589
+ label_counter: Counter,
590
+ label_status_counter: Counter,
591
+ tp_tol: float,
592
+ err_window: float,
593
+ ) -> Dict[str, Any]:
594
+ summary: Dict[str, Any] = {
595
+ "tp_tolerance_s": tp_tol,
596
+ "residual_window_s": err_window,
597
+ "label_phase_count_all_status": dict(label_counter),
598
+ "label_phase_count_by_status": {f"{k[0]}:{k[1]}": v for k, v in label_status_counter.items()},
599
+ "subsets": {},
600
+ }
601
+
602
+ for subset in sorted({r.subset for r in results}):
603
+ subset_results = [r for r in results if r.subset == subset]
604
+ phases = sorted({r.label_phase for r in subset_results})
605
+ subset_summary: Dict[str, Any] = {}
606
+ for ph in phases:
607
+ ph_results = [r for r in subset_results if r.label_phase == ph]
608
+ n_label = len(ph_results)
609
+ n_tp = sum(1 for r in ph_results if r.matched)
610
+ 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)
611
+ tp_residuals = np.array([r.residual_s for r in ph_results if r.matched and r.residual_s is not None], dtype=float)
612
+
613
+ # Waveform-coverage-corrected recall: denominator is only labels that
614
+ # have waveform data available (has_waveform=True). Labels where
615
+ # has_waveform is None (waveform_db not supplied) are excluded from
616
+ # the covered subset so the field stays None rather than 0/1.
617
+ cov_results = [r for r in ph_results if r.has_waveform is True]
618
+ n_label_cov = len(cov_results)
619
+ n_tp_cov = sum(1 for r in cov_results if r.matched)
620
+ # Distinguish "waveform_db not used" (all None) from "used but 0 covered"
621
+ use_cov = any(r.has_waveform is not None for r in ph_results)
622
+
623
+ phase_summary = {
624
+ "n_label": int(n_label),
625
+ "n_matched_within_tp_tol": int(n_tp),
626
+ "recall": float(n_tp / n_label) if n_label else None,
627
+ # Coverage-corrected metrics (only present when --waveform-db is used)
628
+ "n_label_with_waveform": int(n_label_cov) if use_cov else None,
629
+ "n_tp_with_waveform": int(n_tp_cov) if use_cov else None,
630
+ "recall_covered": float(n_tp_cov / n_label_cov) if (use_cov and n_label_cov) else None,
631
+ "n_residual_within_err_window": int(residuals.size),
632
+ "residual_mean_s": float(np.mean(residuals)) if residuals.size else None,
633
+ "residual_std_s": float(np.std(residuals, ddof=1)) if residuals.size > 1 else None,
634
+ "residual_median_s": float(np.median(residuals)) if residuals.size else None,
635
+ "residual_abs_p90_s": float(np.percentile(np.abs(residuals), 90)) if residuals.size else None,
636
+ "residual_abs_p95_s": float(np.percentile(np.abs(residuals), 95)) if residuals.size else None,
637
+ "tp_residual_std_s": float(np.std(tp_residuals, ddof=1)) if tp_residuals.size > 1 else None,
638
+ "gaussian_fit_all_within_err_window": fit_gaussian(residuals),
639
+ "student_t_fit_all_within_err_window": fit_student_t(residuals),
640
+ }
641
+ subset_summary[ph] = phase_summary
642
+
643
+ # Combined P+S / Pg+Sg style summary
644
+ n_label_all = len(subset_results)
645
+ n_tp_all = sum(1 for r in subset_results if r.matched)
646
+ cov_all = [r for r in subset_results if r.has_waveform is True]
647
+ n_label_cov_all = len(cov_all)
648
+ n_tp_cov_all = sum(1 for r in cov_all if r.matched)
649
+ use_cov_all = any(r.has_waveform is not None for r in subset_results)
650
+ subset_summary["P_S_combined"] = {
651
+ "n_label": int(n_label_all),
652
+ "n_matched_within_tp_tol": int(n_tp_all),
653
+ "recall": float(n_tp_all / n_label_all) if n_label_all else None,
654
+ "n_label_with_waveform": int(n_label_cov_all) if use_cov_all else None,
655
+ "n_tp_with_waveform": int(n_tp_cov_all) if use_cov_all else None,
656
+ "recall_covered": float(n_tp_cov_all / n_label_cov_all) if (use_cov_all and n_label_cov_all) else None,
657
+ }
658
+ summary["subsets"][subset] = subset_summary
659
+ return summary
660
+
661
+
662
+ def write_outputs(results: List[MatchResult], summary: Dict[str, Any], outdir: Path) -> None:
663
+ with (outdir / "summary.json").open("w", encoding="utf-8") as f:
664
+ json.dump(summary, f, ensure_ascii=False, indent=2)
665
+
666
+ with (outdir / "matches.jsonl").open("w", encoding="utf-8") as f:
667
+ for r in results:
668
+ f.write(json.dumps(r.__dict__, ensure_ascii=False) + "\n")
669
+
670
+ with (outdir / "summary.tsv").open("w", encoding="utf-8") as f:
671
+ f.write("subset\tphase\tn_label\tn_tp\trecall\tn_label_with_waveform\tn_tp_with_waveform\trecall_covered\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")
672
+ for subset, ss in summary["subsets"].items():
673
+ for phase, d in ss.items():
674
+ if phase == "P_S_combined":
675
+ continue
676
+ gfit = d.get("gaussian_fit_all_within_err_window", {}) or {}
677
+ tfit = d.get("student_t_fit_all_within_err_window", {}) or {}
678
+ f.write("\t".join([
679
+ subset, phase,
680
+ str(d.get("n_label")), str(d.get("n_matched_within_tp_tol")), str(d.get("recall")),
681
+ str(d.get("n_label_with_waveform")), str(d.get("n_tp_with_waveform")), str(d.get("recall_covered")),
682
+ str(d.get("n_residual_within_err_window")), str(d.get("residual_mean_s")),
683
+ str(d.get("residual_std_s")), str(d.get("residual_median_s")),
684
+ str(d.get("residual_abs_p90_s")), str(d.get("residual_abs_p95_s")),
685
+ str(gfit.get("mean")), str(gfit.get("std_mle")), str(gfit.get("std_unbiased")),
686
+ str(tfit.get("df")), str(tfit.get("loc")), str(tfit.get("scale")),
687
+ ]) + "\n")
688
+
689
+
690
+ def load_matches(path: Path) -> List[Dict[str, Any]]:
691
+ rows = []
692
+ with path.open("r", encoding="utf-8") as f:
693
+ for line in f:
694
+ if line.strip():
695
+ rows.append(json.loads(line))
696
+ return rows
697
+
698
+
699
+ def plot_results(outdir: Path) -> None:
700
+ import matplotlib.pyplot as plt
701
+
702
+ matches_path = outdir / "matches.jsonl"
703
+ if not matches_path.exists():
704
+ print(f"[PLOT] missing {matches_path}", file=sys.stderr)
705
+ return
706
+ rows = load_matches(matches_path)
707
+ plot_dir = outdir / "figures"
708
+ plot_dir.mkdir(parents=True, exist_ok=True)
709
+
710
+ # Residual distribution by subset and phase
711
+ for subset in sorted({r["subset"] for r in rows}):
712
+ for phase in sorted({r["label_phase"] for r in rows if r["subset"] == subset}):
713
+ vals = np.array([
714
+ r["residual_s"] for r in rows
715
+ if r["subset"] == subset and r["label_phase"] == phase and r.get("residual_s") is not None
716
+ ], dtype=float)
717
+ if vals.size == 0:
718
+ continue
719
+ vals = vals[np.isfinite(vals)]
720
+ if vals.size == 0:
721
+ continue
722
+
723
+ fig = plt.figure(figsize=(7.5, 4.8))
724
+ plt.hist(vals, bins=100, density=True, alpha=0.55, label=f"Residuals (n={vals.size:,})")
725
+
726
+ x_min, x_max = float(np.min(vals)), float(np.max(vals))
727
+ if x_min == x_max:
728
+ x_min -= 1.0
729
+ x_max += 1.0
730
+ x = np.linspace(x_min, x_max, 800)
731
+
732
+ mu = float(np.mean(vals))
733
+ sigma = float(np.std(vals, ddof=0)) if vals.size > 1 else 0.0
734
+ if scipy_stats is not None and sigma > 0:
735
+ gauss_pdf = scipy_stats.norm.pdf(x, loc=mu, scale=sigma)
736
+ plt.plot(x, gauss_pdf, linewidth=2, label=f"Gaussian μ={mu:.3f}, σ={sigma:.3f}")
737
+
738
+ if vals.size >= 3:
739
+ try:
740
+ df, loc, scale = scipy_stats.t.fit(vals)
741
+ if scale > 0:
742
+ t_pdf = scipy_stats.t.pdf(x, df, loc=loc, scale=scale)
743
+ plt.plot(x, t_pdf, linewidth=2, label=f"Student-t df={df:.2f}, loc={loc:.3f}, scale={scale:.3f}")
744
+ except Exception as exc:
745
+ print(f"[PLOT] Student-t fit failed for {subset}/{phase}: {exc}", file=sys.stderr)
746
+ else:
747
+ plt.text(
748
+ 0.02, 0.95,
749
+ "Install scipy to overlay Gaussian/Student-t PDFs",
750
+ transform=plt.gca().transAxes,
751
+ va="top",
752
+ )
753
+
754
+ plt.axvline(0.0, linestyle="--", linewidth=1)
755
+ plt.xlabel("Residual time: automatic - label (s)")
756
+ plt.ylabel("Probability density")
757
+ plt.title(f"Residual distribution with fits: {subset}, {phase}")
758
+ plt.legend(fontsize=8)
759
+ plt.tight_layout()
760
+ fig.savefig(plot_dir / f"residual_fit_{subset}_{phase}.png", dpi=220)
761
+ plt.close(fig)
762
+
763
+ # Recall bar chart
764
+ summary = json.loads((outdir / "summary.json").read_text(encoding="utf-8"))
765
+ labels, vals = [], []
766
+ for subset, ss in summary["subsets"].items():
767
+ for phase, d in ss.items():
768
+ if phase == "P_S_combined":
769
+ continue
770
+ if d.get("recall") is not None:
771
+ labels.append(f"{subset}-{phase}")
772
+ vals.append(d["recall"])
773
+ if labels:
774
+ fig = plt.figure(figsize=(max(7, 0.8 * len(labels)), 4.5))
775
+ plt.bar(labels, vals)
776
+ plt.ylim(0, 1)
777
+ plt.ylabel("Recall")
778
+ plt.title("Phase-pick recall")
779
+ plt.xticks(rotation=45, ha="right")
780
+ plt.tight_layout()
781
+ fig.savefig(plot_dir / "recall_bar.png", dpi=200)
782
+ plt.close(fig)
783
+
784
+
785
+ # Automatic pick counts by original automatic phase
786
+ auto_counts = summary.get("auto_pick_count", {}).get("by_auto_phase", {})
787
+ if auto_counts:
788
+ phases = list(auto_counts.keys())
789
+ counts = [auto_counts[p] for p in phases]
790
+ fig = plt.figure(figsize=(max(7, 0.8 * len(phases)), 4.5))
791
+ plt.bar(phases, counts)
792
+ plt.ylabel("Number of automatic picks")
793
+ plt.title("Automatic pick counts by phase")
794
+ plt.xticks(rotation=45, ha="right")
795
+ plt.tight_layout()
796
+ fig.savefig(plot_dir / "auto_pick_count_bar.png", dpi=220)
797
+ plt.close(fig)
798
+ print(f"[PLOT] saved figures to {plot_dir}")
799
+
800
+
801
+ # -----------------------------
802
+ # Optional utilities
803
+ # -----------------------------
804
+
805
+ def print_db_info(db_path: Path) -> None:
806
+ db_path = Path(db_path).expanduser().resolve()
807
+ if not db_path.exists():
808
+ raise FileNotFoundError(f"SQLite index DB not found: {db_path}")
809
+ conn = connect_db(db_path)
810
+ n = conn.execute("SELECT COUNT(*) FROM auto_picks").fetchone()[0]
811
+ print(f"auto_picks: {n:,}")
812
+ print("phase counts:")
813
+ for ph, c in conn.execute("SELECT phase_name, COUNT(*) FROM auto_picks GROUP BY phase_name ORDER BY COUNT(*) DESC"):
814
+ print(f" {ph}: {c:,}")
815
+ conn.close()
816
+
817
+
818
+ # -----------------------------
819
+ # CLI
820
+ # -----------------------------
821
+
822
+ def main() -> None:
823
+ parser = argparse.ArgumentParser(description="Evaluate automatic phase picks against continuous-HDF5 annotation JSON.")
824
+ parser.add_argument("--auto-jsonl", type=Path, default=Path("data/picks/skynet.phase.jsonl"))
825
+ parser.add_argument("--label-json", type=Path, default=Path("data/label/annotations_for_continuous_hdf5.json"))
826
+ parser.add_argument("--index-db", type=Path, default=Path("~/skynet.pick.index.sqlite"))
827
+ parser.add_argument("--outdir", type=Path, default=Path("eval_picks/eval_skynet"))
828
+ parser.add_argument("--build-index", action="store_true", help="Build or update SQLite index from auto JSONL.")
829
+ parser.add_argument("--drop-existing", action="store_true", help="Drop existing index table before rebuilding.")
830
+ parser.add_argument("--keep-raw-json", action="store_true", help="Store raw JSON in SQLite. Not recommended for 40GB files.")
831
+ parser.add_argument("--batch-size", type=int, default=50000)
832
+ parser.add_argument("--tp-tol", type=float, default=1.5, help="TP tolerance in seconds.")
833
+ parser.add_argument("--err-window", type=float, default=5.0, help="Window for residual distribution in seconds.")
834
+ parser.add_argument("--min-prob", type=float, default=None, help="Optional minimum automatic pick probability.")
835
+ parser.add_argument("--phase-map", type=str, default=None, help="Example: 'P:Pg;S:Sg' or 'P:Pg,Pn;S:Sg,Sn'.")
836
+ parser.add_argument("--waveform-db", type=Path, default=None,
837
+ help="Waveform coverage SQLite index (built by hdf5_waveform_index.py). "
838
+ "When supplied, each label pick is checked for waveform availability. "
839
+ "recall_covered is computed over the subset that has waveform data, "
840
+ "so labels from un-processed stations/days are excluded from the denominator.")
841
+ parser.add_argument("--plot", action="store_true", help="Generate figures after evaluation.")
842
+ parser.add_argument("--db-info", action="store_true", help="Only print index database info.")
843
+ args = parser.parse_args()
844
+
845
+ if args.build_index:
846
+ build_auto_pick_index(
847
+ args.auto_jsonl, args.index_db,
848
+ batch_size=args.batch_size,
849
+ drop_existing=args.drop_existing,
850
+ keep_raw_json=args.keep_raw_json,
851
+ )
852
+
853
+ if args.db_info:
854
+ print_db_info(args.index_db)
855
+ return
856
+
857
+ phase_map = parse_phase_map(args.phase_map)
858
+ results, summary = evaluate(
859
+ label_json=args.label_json,
860
+ db_path=args.index_db,
861
+ outdir=args.outdir,
862
+ phase_map=phase_map,
863
+ tp_tol=args.tp_tol,
864
+ err_window=args.err_window,
865
+ min_prob=args.min_prob,
866
+ waveform_db=args.waveform_db,
867
+ )
868
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
869
+
870
+ if args.plot:
871
+ plot_results(args.outdir)
872
+
873
+
874
+ if __name__ == "__main__":
875
+ main()