#!/usr/bin/env python3 """Same-output denominator diagnostic for association experiments. The script supports a narrow paired experiment: 1. Build a selected-window picker JSONL from the same continuous picker output. Windows are station-time intervals centered on waveform-covered catalog arrivals from an existing pick-evaluation ``matches.jsonl`` file. 2. Summarize two REAL association runs that differ only in the pick file sent to the associator: full continuous output versus selected-window output. This is not a full association benchmark. It is a controlled diagnostic for how the evaluation object changes pre-association and association burden. """ from __future__ import annotations import argparse import bisect import json from collections import Counter, defaultdict from datetime import datetime, timezone from pathlib import Path from typing import Any def parse_utc_to_epoch_seconds(value: str) -> float: text = str(value).strip() if text.endswith("Z"): text = text[:-1] + "+00:00" dt = datetime.fromisoformat(text) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) else: dt = dt.astimezone(timezone.utc) return dt.timestamp() def norm_location(value: str | None) -> str: if value is None or value == "": return "--" return str(value) 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)}" def iter_jsonl(path: Path): with path.open("r", encoding="utf-8", errors="replace") as handle: for line in handle: line = line.strip() if line: yield json.loads(line) def merge_intervals(intervals: list[tuple[float, float]]) -> list[tuple[float, float]]: if not intervals: return [] intervals = sorted(intervals) merged = [intervals[0]] for start, end in intervals[1:]: prev_start, prev_end = merged[-1] if start <= prev_end: merged[-1] = (prev_start, max(prev_end, end)) else: merged.append((start, end)) return merged def load_station_time_windows( matches_jsonl: Path, half_width_s: float, start_epoch: float | None, end_epoch: float | None, ) -> dict[str, list[tuple[float, float]]]: windows: dict[str, list[tuple[float, float]]] = defaultdict(list) for rec in iter_jsonl(matches_jsonl): if rec.get("subset") != "all": continue if not rec.get("has_waveform"): continue try: label_epoch = float(rec["label_time_epoch"]) except Exception: continue if start_epoch is not None and label_epoch < start_epoch: continue if end_epoch is not None and label_epoch >= end_epoch: continue station_id = norm_station_id(str(rec.get("station_id") or "")) windows[station_id].append((label_epoch - half_width_s, label_epoch + half_width_s)) return {station_id: merge_intervals(vals) for station_id, vals in windows.items()} def seconds_in_windows(windows: dict[str, list[tuple[float, float]]]) -> float: return sum(end - start for intervals in windows.values() for start, end in intervals) def in_windows( station_id: str, epoch: float, windows: dict[str, list[tuple[float, float]]], starts_by_station: dict[str, list[float]], ) -> bool: intervals = windows.get(station_id) if not intervals: return False starts = starts_by_station[station_id] idx = bisect.bisect_right(starts, epoch) - 1 return idx >= 0 and intervals[idx][0] <= epoch <= intervals[idx][1] def filter_selected(args: argparse.Namespace) -> None: start_epoch = parse_utc_to_epoch_seconds(args.starttime) if args.starttime else None end_epoch = parse_utc_to_epoch_seconds(args.endtime) if args.endtime else None windows = load_station_time_windows( matches_jsonl=args.matches_jsonl, half_width_s=args.half_width_s, start_epoch=start_epoch, end_epoch=end_epoch, ) starts_by_station = { station_id: [start for start, _end in intervals] for station_id, intervals in windows.items() } args.output_jsonl.parent.mkdir(parents=True, exist_ok=True) stats = Counter() by_phase = Counter() selected_by_phase = Counter() selected_by_station = Counter() with args.output_jsonl.open("w", encoding="utf-8") as out: for rec in iter_jsonl(args.picks_jsonl): stats["input_records"] += 1 if rec.get("record_type") != "phase_pick": stats[f"skip_record_type:{rec.get('record_type', '')}"] += 1 continue stats["phase_pick_records"] += 1 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"), ) try: epoch = parse_utc_to_epoch_seconds(rec["phase_time"]) except Exception: stats["skip_bad_time"] += 1 continue if start_epoch is not None and epoch < start_epoch: stats["skip_before_starttime"] += 1 continue if end_epoch is not None and epoch >= end_epoch: stats["skip_after_endtime"] += 1 continue phase = str(rec.get("phase_name") or "") by_phase[phase] += 1 if not in_windows(station_id, epoch, windows, starts_by_station): stats["skip_outside_selected_windows"] += 1 continue stats["selected_records"] += 1 selected_by_phase[phase] += 1 selected_by_station[station_id] += 1 out.write(json.dumps(rec, ensure_ascii=False, separators=(",", ":")) + "\n") summary = { "diagnostic": "selected_window_pick_filter", "picks_jsonl": str(args.picks_jsonl), "matches_jsonl": str(args.matches_jsonl), "output_jsonl": str(args.output_jsonl), "time_window": { "starttime": args.starttime, "endtime": args.endtime, }, "selected_window_definition": { "window_type": "station-time windows centered on waveform-covered catalog arrivals", "half_width_s": args.half_width_s, "full_width_s": 2.0 * args.half_width_s, "subset": "all", "requires_has_waveform": True, }, "window_count": sum(len(v) for v in windows.values()), "station_count": len(windows), "selected_window_seconds_station_time": seconds_in_windows(windows), "raw_pick_counts_in_time_window": { "total": int(sum(by_phase.values())), "by_phase": dict(sorted(by_phase.items())), }, "selected_pick_counts": { "total": int(stats["selected_records"]), "by_phase": dict(sorted(selected_by_phase.items())), "station_count": len(selected_by_station), }, "stats": dict(sorted(stats.items())), } args.summary_json.parent.mkdir(parents=True, exist_ok=True) args.summary_json.write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8") print(f"[OK] selected picks: {stats['selected_records']}") print(f"[OK] selected stations: {len(selected_by_station)}") print(f"[OK] station-time seconds: {summary['selected_window_seconds_station_time']:.3f}") print(f"[OK] wrote: {args.output_jsonl}") print(f"[OK] summary: {args.summary_json}") def load_json(path: Path) -> dict[str, Any]: return json.loads(path.read_text(encoding="utf-8")) def safe_div(num: float, den: float) -> float | None: if den == 0: return None return num / den def ratio(full_value: float | None, selected_value: float | None) -> float | None: if full_value is None or selected_value in (None, 0): return None return full_value / selected_value def association_row( label: str, pick_filter_summary: dict[str, Any] | None, real_summary: dict[str, Any], event_summary: dict[str, Any], ) -> dict[str, Any]: counts = event_summary["counts"] n_pred = int(counts["predicted_events"]) n_tp = int(counts["catalogue_matched_events"]) n_catalog_unmatched = int(counts["catalogue_unmatched_events"]) real_input = int(real_summary["real_input_pick_count"]) unique_assoc = int(real_summary["unique_associated_input_pick_count"]) if pick_filter_summary is None: raw_pick_count = int(real_summary.get("picks_before_nms", 0)) raw_phase_count = {} else: raw_pick_count = int(pick_filter_summary["selected_pick_counts"]["total"]) raw_phase_count = pick_filter_summary["selected_pick_counts"].get("by_phase", {}) return { "evaluation_object": label, "raw_candidate_picks_before_real_threshold": raw_pick_count, "raw_candidate_picks_by_phase": raw_phase_count, "real_threshold": real_summary.get("raw_pick_stats", {}).get("accepted"), "real_input_picks_after_nms": real_input, "station_count_net_sta": int(real_summary["station_count_net_sta"]), "real_event_hypotheses": int(real_summary["event_count"]), "associated_pick_count": int(real_summary["associated_pick_count"]), "unique_associated_input_picks": unique_assoc, "unassociated_input_picks": int(real_summary["unassociated_input_pick_count"]), "input_pick_associated_fraction": safe_div(unique_assoc, real_input), "catalogue_reference_events": int(counts["reference_events"]), "catalogue_matched_event_hypotheses": n_tp, "catalogue_unmatched_event_hypotheses": n_catalog_unmatched, "catalogue_match_fraction": safe_div(n_tp, n_pred), "catalogue_event_recall": safe_div(n_tp, int(counts["reference_events"])), } def summarize_association(args: argparse.Namespace) -> None: full_real = load_json(args.full_real_summary) selected_real = load_json(args.selected_real_summary) full_event = load_json(args.full_event_summary) selected_event = load_json(args.selected_event_summary) selected_filter = load_json(args.selected_filter_summary) full_row = association_row("full_continuous_stream", None, full_real, full_event) full_row["raw_candidate_picks_before_real_threshold"] = int( selected_filter["raw_pick_counts_in_time_window"]["total"] ) full_row["raw_candidate_picks_by_phase"] = selected_filter["raw_pick_counts_in_time_window"].get( "by_phase", {} ) selected_row = association_row( "selected_station_time_windows", selected_filter, selected_real, selected_event, ) comparison_keys = [ "raw_candidate_picks_before_real_threshold", "real_threshold", "real_input_picks_after_nms", "real_event_hypotheses", "associated_pick_count", "unassociated_input_picks", "catalog_matched_event_hypotheses", "catalog_unmatched_event_hypotheses", ] ratios = { key: ratio(float(full_row[key]), float(selected_row[key])) for key in comparison_keys } out = { "diagnostic": "same_output_association_denominator_diagnostic", "controlled_quantities": [ "picker output", "REAL association parameters", "phase mapping", "waveform coverage source", "event matching protocol", "catalog", "time window", ], "changed_quantity": "evaluation object: full continuous stream versus selected station-time windows", "selected_window_definition": selected_filter.get("selected_window_definition", {}), "rows": [full_row, selected_row], "full_to_selected_ratios": ratios, "interpretation_guardrail": ( "Catalog-unmatched event hypotheses are not asserted false events; " "they are catalog-relative association burden under the fixed protocol." ), } args.output_json.parent.mkdir(parents=True, exist_ok=True) args.output_json.write_text(json.dumps(out, indent=2, ensure_ascii=False), encoding="utf-8") print("[OK] same-output association diagnostic") print(f"[OK] full REAL events: {full_row['real_event_hypotheses']}") print(f"[OK] selected-window REAL events: {selected_row['real_event_hypotheses']}") print(f"[OK] full/selected REAL input pick ratio: {ratios['real_input_picks_after_nms']}") print(f"[OK] full/selected catalog-unmatched event ratio: {ratios['catalog_unmatched_event_hypotheses']}") print(f"[OK] wrote: {args.output_json}") def build_arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) p_filter = sub.add_parser("filter-selected", help="Write selected-window pick JSONL.") p_filter.add_argument("--picks-jsonl", type=Path, required=True) p_filter.add_argument("--matches-jsonl", type=Path, required=True) p_filter.add_argument("--output-jsonl", type=Path, required=True) p_filter.add_argument("--summary-json", type=Path, required=True) p_filter.add_argument("--starttime", required=True) p_filter.add_argument("--endtime", required=True) p_filter.add_argument("--half-width-s", type=float, default=30.0) p_filter.set_defaults(func=filter_selected) p_sum = sub.add_parser("summarize", help="Summarize full versus selected REAL runs.") p_sum.add_argument("--full-real-summary", type=Path, required=True) p_sum.add_argument("--selected-real-summary", type=Path, required=True) p_sum.add_argument("--full-event-summary", type=Path, required=True) p_sum.add_argument("--selected-event-summary", type=Path, required=True) p_sum.add_argument("--selected-filter-summary", type=Path, required=True) p_sum.add_argument("--output-json", type=Path, required=True) p_sum.set_defaults(func=summarize_association) return parser def main() -> None: args = build_arg_parser().parse_args() args.func(args) if __name__ == "__main__": main()