Upload essd_scripts/paired_snippet_stream_diagnostic.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326#!/usr/bin/env python3"""Post-hoc paired snippet/stream diagnostic for SeismicX-Cont outputs.
This script keeps the automatic picker output, thresholds, phase mapping, andmatching tolerance fixed, then changes only the evaluation object:
1. full continuous stream;2. phase-centered station-time short windows around waveform-covered catalog picks.
It does not rerun inference on extracted snippets. It is a fast diagnostic forhow much the selected-window evaluation object suppresses pick-volume burden."""
from __future__ import annotations
import argparseimport bisectimport csvimport jsonimport mathfrom collections import Counter, defaultdictfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
PHASE_MAP = { "P": ["Pg"], "S": ["Sg"],}
def parse_utc_to_epoch_seconds(value: str) -> float: 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: str | None) -> str: if loc is None or loc == "": return "--" return str(loc)
def norm_station_id( station_id: str | None = None, network: str | None = None, station: str | None = None, location: str | None = None,) -> str: 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)}"
@dataclass(frozen=True)class LabelRow: label_phase: str station_id: str label_time_epoch: float matched: bool has_waveform: bool residual_s: float | None
def iter_jsonl(path: Path): with path.open("r", encoding="utf-8", errors="replace") as f: for line in f: line = line.strip() if line: yield json.loads(line)
def load_labels_from_matches(matches_jsonl: Path) -> list[LabelRow]: labels: list[LabelRow] = [] for rec in iter_jsonl(matches_jsonl): if rec.get("subset") != "all": continue phase = str(rec.get("label_phase")) if phase not in PHASE_MAP: continue labels.append( LabelRow( label_phase=phase, station_id=str(rec.get("station_id")), label_time_epoch=float(rec.get("label_time_epoch")), matched=bool(rec.get("matched")), has_waveform=bool(rec.get("has_waveform")), residual_s=rec.get("residual_s"), ) ) return labels
def merge_intervals(intervals: list[tuple[float, float]]) -> list[tuple[float, float]]: if not intervals: return [] intervals = sorted(intervals) merged = [intervals[0]] for t0, t1 in intervals[1:]: last0, last1 = merged[-1] if t0 <= last1: merged[-1] = (last0, max(last1, t1)) else: merged.append((t0, t1)) return merged
def build_phase_centered_station_windows( labels: list[LabelRow], half_width_s: float,) -> dict[str, list[tuple[float, float]]]: windows: dict[str, list[tuple[float, float]]] = defaultdict(list) for lab in labels: if not lab.has_waveform: continue windows[lab.station_id].append( (lab.label_time_epoch - half_width_s, lab.label_time_epoch + half_width_s) ) return {key: merge_intervals(vals) for key, vals in windows.items()}
def count_picks_in_window_sets( auto_jsonl: Path, window_sets: dict[str, dict[str, list[tuple[float, float]]]],) -> dict[str, tuple[int, dict[str, int]]]: starts_by_mode = { mode: {key: [x[0] for x in vals] for key, vals in windows.items()} for mode, windows in window_sets.items() } totals = {mode: 0 for mode in window_sets} by_phase = {mode: Counter() for mode in window_sets} for rec in iter_jsonl(auto_jsonl): if rec.get("record_type") != "phase_pick": continue station_info = rec.get("station_info") or {} station_id = norm_station_id( rec.get("station_id") or station_info.get("station_id"), station_info.get("network"), station_info.get("station"), station_info.get("location"), ) phase = str(rec.get("phase_name")) t = parse_utc_to_epoch_seconds(rec.get("phase_time")) for mode, windows in window_sets.items(): intervals = windows.get(station_id) if not intervals: continue starts = starts_by_mode[mode][station_id] idx = bisect.bisect_right(starts, t) - 1 if idx >= 0 and intervals[idx][0] <= t <= intervals[idx][1]: totals[mode] += 1 by_phase[mode][phase] += 1 return {mode: (totals[mode], dict(by_phase[mode])) for mode in window_sets}
def load_summary(summary_json: Path) -> dict[str, Any]: return json.loads(summary_json.read_text(encoding="utf-8"))
def load_total_duration_s(label_json: Path) -> float: data = json.loads(label_json.read_text(encoding="utf-8")) total = 0.0 for window in data.get("subset_windows", []): total += parse_utc_to_epoch_seconds(window["endtime"]) - parse_utc_to_epoch_seconds(window["starttime"]) if total > 0: return total for year_obj in data.get("years", {}).values(): total += 86400.0 * len(year_obj.get("days", {})) return total
def summarize_residuals(labels: list[LabelRow]) -> dict[str, float | int | None]: vals = [abs(float(x.residual_s)) for x in labels if x.residual_s is not None and math.isfinite(float(x.residual_s))] if not vals: return {"n_residual": 0, "abs_p95_s": None, "tail_gt_1p5_fraction": None} vals.sort() n = len(vals) p95_idx = min(n - 1, int(math.ceil(0.95 * n)) - 1) return { "n_residual": n, "abs_p95_s": vals[p95_idx], "tail_gt_1p5_fraction": sum(v > 1.5 for v in vals) / n, }
def row_metrics( mode: str, n_label_cov: int, n_tp_cov: int, n_auto_picks: int, duration_s: float | None, selected_window_seconds: float | None, residual_summary: dict[str, Any], auto_by_phase: dict[str, int] | None = None,) -> dict[str, Any]: return { "mode": mode, "n_label_with_waveform": n_label_cov, "n_tp_with_waveform": n_tp_cov, "coverage_aware_recall": n_tp_cov / n_label_cov if n_label_cov else None, "automatic_picks": n_auto_picks, "automatic_picks_per_day": (n_auto_picks / duration_s * 86400.0) if duration_s else None, "catalog_relative_explained_fraction": n_tp_cov / n_auto_picks if n_auto_picks else None, "automatic_picks_per_covered_tp": n_auto_picks / n_tp_cov if n_tp_cov else None, "selected_window_seconds_station_time": selected_window_seconds, "automatic_pick_counts_by_phase": auto_by_phase or {}, **residual_summary, }
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) root = Path(__file__).resolve().parents[1] parser.add_argument("--auto-jsonl", type=Path, default=root / "data/picks/pnsn_v3_diff.mini.phase.jsonl") parser.add_argument("--matches-jsonl", type=Path, default=root / "eval_picks/example/matches.jsonl") parser.add_argument("--summary-json", type=Path, default=root / "eval_picks/example/summary.json") parser.add_argument("--label-json", type=Path, default=root / "data/label/annotations_mini_two_hours.json") parser.add_argument("--outdir", type=Path, default=root / "paired_eval_mini") parser.add_argument("--half-width-s", type=float, nargs="+", default=[10.0, 30.0]) args = parser.parse_args()
labels_all = load_labels_from_matches(args.matches_jsonl) covered = [x for x in labels_all if x.has_waveform] n_label_cov = len(covered) n_tp_cov = sum(x.matched for x in covered) residual_summary = summarize_residuals(covered)
full_summary = load_summary(args.summary_json) n_auto_stream = int(full_summary["auto_pick_count"]["total"]) duration_s = load_total_duration_s(args.label_json)
rows: list[dict[str, Any]] = [ row_metrics( "continuous_stream", n_label_cov, n_tp_cov, n_auto_stream, duration_s, None, residual_summary, full_summary["auto_pick_count"].get("by_auto_phase", {}), ) ]
window_sets = { f"phase_centered_snippets_pm{half_width:g}s": build_phase_centered_station_windows(labels_all, half_width) for half_width in args.half_width_s } window_counts = count_picks_in_window_sets(args.auto_jsonl, window_sets)
for half_width in args.half_width_s: mode = f"phase_centered_snippets_pm{half_width:g}s" windows = window_sets[mode] selected_seconds = sum(t1 - t0 for vals in windows.values() for t0, t1 in vals) n_auto_snippet, by_phase = window_counts[mode] rows.append( row_metrics( mode, n_label_cov, n_tp_cov, n_auto_snippet, None, selected_seconds, residual_summary, by_phase, ) )
args.outdir.mkdir(parents=True, exist_ok=True) (args.outdir / "paired_snippet_stream_summary.json").write_text( json.dumps( { "note": ( "Post-hoc paired evaluation-object diagnostic. The automatic " "picker output is fixed; only the evaluation object changes. " "Snippet denominators count all automatic picks inside the " "selected station-time windows, not only matched phases." ), "phase_map": PHASE_MAP, "tp_tolerance_s": full_summary.get("tp_tolerance_s"), "total_stream_duration_s": duration_s, "rows": rows, }, indent=2, ), encoding="utf-8", )
tsv_path = args.outdir / "paired_snippet_stream_summary.tsv" fields = [ "mode", "n_label_with_waveform", "n_tp_with_waveform", "coverage_aware_recall", "automatic_picks", "automatic_picks_per_day", "catalog_relative_explained_fraction", "automatic_picks_per_covered_tp", "selected_window_seconds_station_time", "n_residual", "abs_p95_s", "tail_gt_1p5_fraction", ] with tsv_path.open("w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=fields, delimiter="\t", extrasaction="ignore") writer.writeheader() writer.writerows(rows)
print(json.dumps(rows, indent=2)) print(f"[OUT] {args.outdir}")
if __name__ == "__main__": main()essd_scripts/paired_snippet_stream_diagnostic.pyAdded+326