#!/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 optional reference-window output match fractions. 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) def reference_coverage_key( event_id: Optional[str], station_id: str, phase: str, status: str, time_epoch: float, ) -> Tuple[str, str, str, str, int]: """Return a stable key shared by annotation JSON and reference SQLite rows.""" return ( "" if event_id is None else str(event_id), norm_station_id(station_id), str(phase), str(status), int(round(float(time_epoch) * 1_000_000)), ) REFERENCE_COVERAGE_FIELDS = { "C0": "c0_point_covered", "C1": "c1_window_covered", "C2": "c2_component_covered", "C3": "c3_processing_ready", } def load_reference_coverage( path: Path, coverage_level: str = "C0", ) -> Tuple[Dict[Tuple[str, str, str, str, int], bool], Dict[str, Any]]: """Load one declared precomputed coverage level and its configuration.""" path = Path(path).expanduser().resolve() if not path.exists(): raise FileNotFoundError(f"Reference-arrival SQLite DB not found: {path}") level = str(coverage_level).upper() if level not in REFERENCE_COVERAGE_FIELDS: raise ValueError(f"Unsupported coverage level: {coverage_level}") field = REFERENCE_COVERAGE_FIELDS[level] con = sqlite3.connect(str(path)) rows = con.execute( f""" SELECT event_id, station_id, phase, status, pick_time_epoch, {field} FROM reference_arrivals ORDER BY arrival_id """ ) coverage: Dict[Tuple[str, str, str, str, int], bool] = {} for event_id, station_id, phase, status, time_epoch, covered in rows: key = reference_coverage_key( event_id, station_id, phase, status, float(time_epoch) ) value = bool(covered) if key in coverage and coverage[key] != value: raise ValueError(f"Conflicting {level} flags for reference key: {key}") coverage[key] = value metadata = { str(key): json.loads(value_json) for key, value_json in con.execute("SELECT key, value_json FROM metadata") } con.close() metadata["selected_coverage_level"] = level metadata["selected_coverage_field"] = field return coverage, metadata def load_reference_c0_coverage( path: Path, ) -> Tuple[Dict[Tuple[str, str, str, str, int], bool], Dict[str, Any]]: """Backward-compatible wrapper for the released C0 reporting default.""" return load_reference_coverage(path, "C0") def load_evaluation_reference_labels( path: Path, coverage_level: str = "C0", ) -> Tuple[List[LabelPick], Dict[int, Optional[bool]], Dict[str, Any]]: """Load the canonical station-phase-time evaluation-reference layer. Source readings remain available in ``reference_arrivals`` and ``evaluation_reference_members``. A canonical record is classified as manual when any member is manual; otherwise it retains automatic provenance. This prevents exact repeated readings from competing for one automatic pick during one-to-one evaluation. """ source = Path(path).expanduser().resolve() level = str(coverage_level).upper() if level not in REFERENCE_COVERAGE_FIELDS: raise ValueError(f"Unsupported coverage level: {coverage_level}") field = REFERENCE_COVERAGE_FIELDS[level] con = sqlite3.connect(str(source)) if con.execute( "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='evaluation_references'" ).fetchone()[0] != 1: con.close() raise ValueError( "reference database lacks the canonical evaluation_references table; " "regenerate it with essd_scripts/build_reference_arrivals.py" ) labels: List[LabelPick] = [] coverage_cache: Dict[int, Optional[bool]] = {} rows = con.execute( f""" SELECT evaluation_reference_id, station_id, phase, pick_time_epoch, has_manual_reference, has_automatic_reference, source_arrival_count, source_event_count, {field} FROM evaluation_references ORDER BY evaluation_reference_id """ ) for row in rows: ( reference_id, station_id, phase, time_epoch, has_manual, has_automatic, source_count, event_count, covered, ) = row labels.append( LabelPick( label_phase=str(phase), label_time_epoch=float(time_epoch), station_id=str(station_id), status="manual" if bool(has_manual) else "automatic", event_id=None, distance_km=None, raw={ "evaluation_reference_id": int(reference_id), "has_manual_reference": bool(has_manual), "has_automatic_reference": bool(has_automatic), "source_arrival_count": int(source_count), "source_event_count": int(event_count), }, ) ) coverage_cache[len(labels) - 1] = bool(covered) metadata = { str(key): json.loads(value_json) for key, value_json in con.execute("SELECT key, value_json FROM metadata") } con.close() metadata["selected_coverage_level"] = level metadata["selected_coverage_field"] = field metadata["reference_layer"] = "evaluation_references" return labels, coverage_cache, metadata # ----------------------------- # 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, allowed_intervals: Optional[Sequence[Tuple[float, 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 allowed_intervals is not None: intervals = list(allowed_intervals) filtered = [] interval_index = 0 for row in rows: value = float(row[2]) while ( interval_index < len(intervals) and value > intervals[interval_index][1] ): interval_index += 1 if interval_index >= len(intervals): break if intervals[interval_index][0] <= value <= intervals[interval_index][1]: filtered.append(row) rows = filtered 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, reference_db: Optional[Path] = None, automatic_pick_source: Optional[Path] = None, coverage_channel_families: Sequence[str] = ("HH", "BH", "EH", "HN"), validate_finite_samples: bool = True, coverage_level: str = "C0", reference_windows_s: Sequence[float] = (), output_eligibility_db: Optional[Path] = None, output_id: Optional[int] = None, output_name: Optional[str] = None, ) -> 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) if waveform_db is not None and reference_db is not None: raise ValueError("Use either waveform_db or reference_db for coverage, not both") coverage_level = str(coverage_level).upper() if coverage_level not in REFERENCE_COVERAGE_FIELDS: raise ValueError(f"Unsupported coverage level: {coverage_level}") if waveform_db is not None and coverage_level != "C0": raise ValueError("C1-C3 reporting requires --reference-db") if reference_windows_s and output_eligibility_db is None: raise ValueError( "Reference-window reporting requires --output-eligibility-db" ) eligibility = None if reference_windows_s: eligibility = load_workflow_eligibility( Path(output_eligibility_db), output_id=output_id, output_name=output_name ) # Optional waveform coverage filter cov_index: Optional[WaveformCoverageIndex] = None reference_coverage = None reference_metadata: Dict[str, Any] = {} if waveform_db is not None: cov_index = WaveformCoverageIndex( Path(waveform_db), channel_families=coverage_channel_families, validate_finite_samples=validate_finite_samples, ) elif reference_db is not None: # Loaded with the canonical labels below; the raw source-reading table # remains available for provenance and inventory reporting. reference_coverage = None results: List[MatchResult] = [] label_counter = Counter() label_status_counter = Counter() if reference_db is not None: loaded_labels, loaded_coverage, reference_metadata = load_evaluation_reference_labels( Path(reference_db), coverage_level ) selected = [ (idx, lab) for idx, lab in enumerate(loaded_labels) if lab.label_phase in phase_map ] labels = [lab for _, lab in selected] coverage_cache = { new_idx: loaded_coverage[old_idx] for new_idx, (old_idx, _) in enumerate(selected) } else: labels = [lab for lab in iter_label_picks(label_json) if lab.label_phase in phase_map] coverage_cache = {} 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 if cov_index is not None: coverage_cache[label_idx] = cov_index.has_coverage( lab.station_id, lab.label_time_epoch ) elif reference_coverage is not None: key = reference_coverage_key( lab.event_id, lab.station_id, lab.label_phase, lab.status, lab.label_time_epoch, ) if key not in reference_coverage: raise KeyError(f"Label is absent from reference-arrival DB: {key}") coverage_cache[label_idx] = reference_coverage[key] else: coverage_cache.setdefault(label_idx, 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, )) if reference_windows_s and eligibility is None: raise RuntimeError("workflow eligibility was not initialized") reference_window_matches = [ compute_reference_window_match_fraction( conn=conn, indexed_labels=list(enumerate(labels)), coverage_cache=coverage_cache, phase_map=phase_map, window_half_width_s=float(window_s), tp_tolerance_s=tp_tol, eligibility=eligibility, coverage_level=coverage_level, min_prob=min_prob, ) for window_s in reference_windows_s ] 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["input_sources"] = { "annotation_json": Path(label_json).as_posix(), "evaluation_reference_layer": ( str(Path(reference_db)) if reference_db is not None else None ), "automatic_pick_jsonl": ( Path(automatic_pick_source).as_posix() if automatic_pick_source is not None else None ), } 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 if reference_window_matches: summary["reference_window_match"] = reference_window_matches if reference_db is not None: coverage_config = reference_metadata.get("coverage", {}) summary["coverage_policy"] = { "source": str(Path(reference_db)), "reference_field": REFERENCE_COVERAGE_FIELDS[coverage_level], "coverage_level": coverage_level, "definition": coverage_config.get( coverage_level, f"precomputed {coverage_level} coverage" ), "channel_families": coverage_config.get( "channel_families", list(coverage_channel_families) ), "finite_sample_validation": coverage_config.get( "finite_sample_validation", True ), "unspecified_location": ( "use the deterministic location/family selection recorded by " "the versioned reference-arrival table" ), } elif waveform_db is not None: summary["coverage_policy"] = { "source": str(Path(waveform_db)), "coverage_level": "C0", "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", } else: summary["coverage_policy"] = { "source": None, "definition": "coverage qualification not applied", } 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 merge_reference_windows( reference_times: Sequence[float], window_half_width_s: float ) -> List[Tuple[float, float]]: """Return the disjoint union of reference-centred time windows.""" half_width = float(window_half_width_s) if half_width <= 0.0: raise ValueError("window_half_width_s must be positive") intervals: List[Tuple[float, float]] = [] for value in sorted(float(item) for item in reference_times): left, right = value - half_width, value + half_width if intervals and left <= intervals[-1][1]: intervals[-1] = (intervals[-1][0], max(intervals[-1][1], right)) else: intervals.append((left, right)) return intervals def _auto_rows_in_windows( conn: sqlite3.Connection, station_id: str, auto_phases: Sequence[str], intervals: Sequence[Tuple[float, float]], min_prob: Optional[float], ) -> List[Tuple[int, float]]: if not intervals: return [] placeholders = ",".join("?" for _ in auto_phases) params: List[Any] = [ station_id, *auto_phases, int(math.floor(intervals[0][0])), int(math.floor(intervals[-1][1])), ] prob_clause = "" if min_prob is not None: prob_clause = " AND phase_prob >= ?" params.append(float(min_prob)) rows = conn.execute( f""" SELECT id, time_epoch FROM auto_picks WHERE station_id = ? AND phase_name IN ({placeholders}) AND sec_key BETWEEN ? AND ? {prob_clause} ORDER BY time_epoch, id """, params, ) selected: List[Tuple[int, float]] = [] interval_idx = 0 for pick_id, time_epoch in rows: value = float(time_epoch) while interval_idx < len(intervals) and value > intervals[interval_idx][1]: interval_idx += 1 if interval_idx >= len(intervals): break if intervals[interval_idx][0] <= value <= intervals[interval_idx][1]: selected.append((int(pick_id), value)) return selected @dataclass(frozen=True) class WorkflowEligibility: source: str output_id: int output_name: str intervals: Dict[Tuple[str, str], List[Tuple[float, float]]] starts: Dict[Tuple[str, str], List[float]] def eligible_intervals(self, station_id: str, phase: str) -> List[Tuple[float, float]]: return self.intervals.get((norm_station_id(station_id), phase), []) def contains(self, station_id: str, phase: str, time_epoch: float) -> bool: key = (norm_station_id(station_id), phase) intervals = self.intervals.get(key, []) starts = self.starts.get(key, []) index = bisect.bisect_right(starts, float(time_epoch)) - 1 return index >= 0 and intervals[index][1] >= float(time_epoch) def _merge_intervals( intervals: Sequence[Tuple[float, float]], ) -> List[Tuple[float, float]]: merged: List[Tuple[float, float]] = [] for left, right in sorted((float(a), float(b)) for a, b in intervals): if right < left: raise ValueError(f"invalid interval: {left} > {right}") if merged and left <= merged[-1][1] + 1.0e-6: merged[-1] = (merged[-1][0], max(merged[-1][1], right)) else: merged.append((left, right)) return merged def intersect_intervals( left_intervals: Sequence[Tuple[float, float]], right_intervals: Sequence[Tuple[float, float]], ) -> List[Tuple[float, float]]: """Return the disjoint intersection of two sorted interval unions.""" result: List[Tuple[float, float]] = [] left_index = right_index = 0 while left_index < len(left_intervals) and right_index < len(right_intervals): left = max(left_intervals[left_index][0], right_intervals[right_index][0]) right = min(left_intervals[left_index][1], right_intervals[right_index][1]) if left <= right: result.append((left, right)) if left_intervals[left_index][1] <= right_intervals[right_index][1]: left_index += 1 else: right_index += 1 return _merge_intervals(result) if result else [] def load_workflow_eligibility( path: Path, output_id: Optional[int] = None, output_name: Optional[str] = None, ) -> WorkflowEligibility: """Load one workflow's valid station-time and phase processing domain.""" if (output_id is None) == (output_name is None): raise ValueError("Specify exactly one of output_id or output_name") source = Path(path).expanduser().resolve() if not source.exists(): raise FileNotFoundError(f"Output eligibility DB not found: {source}") con = sqlite3.connect(str(source)) if output_id is not None: row = con.execute( "SELECT output_id, output_name FROM outputs WHERE output_id=?", (int(output_id),), ).fetchone() else: row = con.execute( "SELECT output_id, output_name FROM outputs WHERE output_name=?", (str(output_name),), ).fetchone() if row is None: con.close() raise KeyError(f"Output is absent from eligibility DB: {output_id or output_name}") selected_id, selected_name = int(row[0]), str(row[1]) grouped: Dict[Tuple[str, str], List[Tuple[float, float]]] = defaultdict(list) rows = con.execute( """ SELECT station_id, processed_start_us, processed_end_us, phase_mask FROM eligibility_intervals WHERE output_id=? AND valid_input=1 ORDER BY station_id, processed_start_us, processed_end_us """, (selected_id,), ) for station_id, start_us, end_us, phase_mask in rows: interval = (int(start_us) / 1_000_000, int(end_us) / 1_000_000) if int(phase_mask) & 1: grouped[(norm_station_id(str(station_id)), "P")].append(interval) if int(phase_mask) & 2: grouped[(norm_station_id(str(station_id)), "S")].append(interval) con.close() intervals = {key: _merge_intervals(values) for key, values in grouped.items()} starts = {key: [left for left, _ in values] for key, values in intervals.items()} return WorkflowEligibility( source=str(source), output_id=selected_id, output_name=selected_name, intervals=intervals, starts=starts, ) def compute_reference_window_match_fraction( conn: sqlite3.Connection, indexed_labels: Sequence[Tuple[int, LabelPick]], coverage_cache: Dict[int, Optional[bool]], phase_map: Dict[str, List[str]], window_half_width_s: float, tp_tolerance_s: float, eligibility: WorkflowEligibility, coverage_level: str, min_prob: Optional[float] = None, ) -> Dict[str, Any]: """Calculate a catalogue-conditioned reference-window match fraction. Automatic picks are counted once in the union of +/-T windows around manual references, intersected with the assessed workflow's valid processing domain for each exact station-location and normalized phase. The numerator uses deterministic one-to-one matches within epsilon. Catalogue-unmatched picks are not confirmed false detections. """ window_s = float(window_half_width_s) epsilon_s = float(tp_tolerance_s) if epsilon_s <= 0.0: raise ValueError("tp_tolerance_s must be positive") if window_s < epsilon_s: raise ValueError("window_half_width_s must be at least tp_tolerance_s") coverage_applied = any(value is not None for value in coverage_cache.values()) if not coverage_applied: raise ValueError( "Reference-window reporting requires a declared C0-C3 coverage level" ) references = [ (idx, label) for idx, label in indexed_labels if label.status == "manual" and label.label_phase in phase_map and (not coverage_applied or coverage_cache.get(idx) is True) ] grouped: Dict[Tuple[str, str], List[LabelPick]] = defaultdict(list) for _, label in references: grouped[(label.station_id, label.label_phase)].append(label) by_phase: Dict[str, Dict[str, Any]] = { phase: { "n_coverage_qualified_manual_references": 0, "n_workflow_eligible_manual_references": 0, "n_merged_reference_windows": 0, "n_effective_processed_windows": 0, "reference_window_union_s": 0.0, "effective_processed_window_s": 0.0, "n_reported_picks_in_effective_windows": 0, "n_matched_one_to_one": 0, } for phase in phase_map } for (station_id, phase), group in sorted(grouped.items()): group = sorted(group, key=lambda item: item.label_time_epoch) target = by_phase[phase] target["n_coverage_qualified_manual_references"] += len(group) eligible_group = [ label for label in group if eligibility.contains(station_id, phase, label.label_time_epoch) ] target["n_workflow_eligible_manual_references"] += len(eligible_group) if not eligible_group: continue reference_intervals = merge_reference_windows( [label.label_time_epoch for label in eligible_group], window_s ) effective_intervals = intersect_intervals( reference_intervals, eligibility.eligible_intervals(station_id, phase), ) if not effective_intervals: continue auto_rows = _auto_rows_in_windows( conn, station_id, phase_map[phase], effective_intervals, min_prob ) assignments = match_labels_one_to_one( conn, eligible_group, phase_map[phase], search_window_s=window_s, min_prob=min_prob, tp_tolerance_s=epsilon_s, allowed_intervals=effective_intervals, ) matched_ids = { candidate.auto_pick_id for candidate in assignments.values() if abs(candidate.residual_s) <= epsilon_s } selected_ids = {pick_id for pick_id, _ in auto_rows} if not matched_ids.issubset(selected_ids): raise RuntimeError("matched automatic pick lies outside merged windows") target["n_merged_reference_windows"] += len(reference_intervals) target["n_effective_processed_windows"] += len(effective_intervals) target["reference_window_union_s"] += sum( right - left for left, right in reference_intervals ) target["effective_processed_window_s"] += sum( right - left for left, right in effective_intervals ) target["n_reported_picks_in_effective_windows"] += len(auto_rows) target["n_matched_one_to_one"] += len(matched_ids) for values in by_phase.values(): reported = int(values["n_reported_picks_in_effective_windows"]) matched = int(values["n_matched_one_to_one"]) references_count = int(values["n_workflow_eligible_manual_references"]) values["reference_window_union_s"] = round( float(values["reference_window_union_s"]), 6 ) values["effective_processed_window_s"] = round( float(values["effective_processed_window_s"]), 6 ) values["n_catalogue_unmatched_in_effective_windows"] = reported - matched values["reference_window_match_fraction"] = ( matched / reported if reported else None ) values["reference_recovery_fraction"] = ( matched / references_count if references_count else None ) auto_phase_owners: Dict[str, List[str]] = defaultdict(list) for phase, auto_phases in phase_map.items(): for auto_phase in auto_phases: auto_phase_owners[auto_phase].append(phase) overlaps = { phase: owners for phase, owners in auto_phase_owners.items() if len(owners) > 1 } combined = None if not overlaps: combined = {} for field in ( "n_coverage_qualified_manual_references", "n_workflow_eligible_manual_references", "n_merged_reference_windows", "n_effective_processed_windows", "reference_window_union_s", "effective_processed_window_s", "n_reported_picks_in_effective_windows", "n_matched_one_to_one", "n_catalogue_unmatched_in_effective_windows", ): combined[field] = sum(values[field] for values in by_phase.values()) reported = int(combined["n_reported_picks_in_effective_windows"]) matched = int(combined["n_matched_one_to_one"]) references_count = int(combined["n_workflow_eligible_manual_references"]) combined["reference_window_match_fraction"] = ( matched / reported if reported else None ) combined["reference_recovery_fraction"] = ( matched / references_count if references_count else None ) return { "window_half_width_s": window_s, "matching_tolerance_epsilon_s": epsilon_s, "reference_subset": f"{coverage_level}-covered manual arrivals", "coverage_level": str(coverage_level).upper(), "workflow_eligibility": { "source": eligibility.source, "output_id": eligibility.output_id, "output_name": eligibility.output_name, "valid_input_required": True, }, "probability_filter": {"min_prob": min_prob}, "window_definition": ( "union of closed +/-T windows around workflow-eligible, coverage-" "qualified manual references by exact station-location and normalized " "phase; overlaps are merged and intersected with the workflow's " "valid processing intervals" ), "interpretation": ( "catalogue-conditioned reference-window output match fraction; a " "precision-oriented diagnostic, not an estimator of conventional " "full-stream precision; catalogue-unmatched picks are not confirmed " "false detections" ), "by_phase": by_phase, "combined": combined, "combined_omitted_for_overlapping_phase_map": overlaps, } 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( "--reference-window-s", type=float, action="append", default=[], help=( "Half-width T for a catalogue-conditioned reference-window output " "match fraction. Repeat for sensitivity analysis; each T must be " ">= --tp-tol and workflow eligibility must be supplied." ), ) 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( "--reference-db", type=Path, default=None, help=( "Versioned reference-arrival SQLite table containing precomputed " "C0-C3 flags. This avoids reopening HDF5 files and is mutually " "exclusive with --waveform-db." ), ) parser.add_argument( "--coverage-level", choices=tuple(REFERENCE_COVERAGE_FIELDS), default="C0", help="Coverage configuration used for recall and reference-window reporting.", ) parser.add_argument( "--output-eligibility-db", type=Path, default=None, help="SQLite station-time processing domain for the assessed workflow.", ) output_selector = parser.add_mutually_exclusive_group() output_selector.add_argument("--output-id", type=int, default=None) output_selector.add_argument("--output-name", default=None) 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 any(value < args.tp_tol for value in args.reference_window_s): parser.error("every --reference-window-s value must be >= --tp-tol") if args.reference_window_s: if args.reference_db is None: parser.error("--reference-window-s requires --reference-db") if args.output_eligibility_db is None: parser.error("--reference-window-s requires --output-eligibility-db") if (args.output_id is None) == (args.output_name is None): parser.error( "--reference-window-s requires exactly one of --output-id or --output-name" ) 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, reference_db=args.reference_db, automatic_pick_source=args.auto_jsonl, coverage_channel_families=coverage_channel_families, validate_finite_samples=not args.skip_finite_sample_check, coverage_level=args.coverage_level, reference_windows_s=args.reference_window_s, output_eligibility_db=args.output_eligibility_db, output_id=args.output_id, output_name=args.output_name, ) print(json.dumps(summary, ensure_ascii=False, indent=2)) if args.plot: plot_results(args.outdir) if __name__ == "__main__": main()