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 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Post-hoc paired snippet/stream diagnostic for SeismicX-Cont outputs.
|
| 3 |
+
|
| 4 |
+
This script keeps the automatic picker output, thresholds, phase mapping, and
|
| 5 |
+
matching tolerance fixed, then changes only the evaluation object:
|
| 6 |
+
|
| 7 |
+
1. full continuous stream;
|
| 8 |
+
2. phase-centered station-time short windows around waveform-covered catalog
|
| 9 |
+
picks.
|
| 10 |
+
|
| 11 |
+
It does not rerun inference on extracted snippets. It is a fast diagnostic for
|
| 12 |
+
how much the selected-window evaluation object suppresses pick-volume burden.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import bisect
|
| 19 |
+
import csv
|
| 20 |
+
import json
|
| 21 |
+
import math
|
| 22 |
+
from collections import Counter, defaultdict
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
from datetime import datetime, timezone
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
PHASE_MAP = {
|
| 30 |
+
"P": ["Pg"],
|
| 31 |
+
"S": ["Sg"],
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def parse_utc_to_epoch_seconds(value: str) -> float:
|
| 36 |
+
s = str(value).strip()
|
| 37 |
+
if s.endswith("Z"):
|
| 38 |
+
s = s[:-1] + "+00:00"
|
| 39 |
+
dt = datetime.fromisoformat(s)
|
| 40 |
+
if dt.tzinfo is None:
|
| 41 |
+
dt = dt.replace(tzinfo=timezone.utc)
|
| 42 |
+
else:
|
| 43 |
+
dt = dt.astimezone(timezone.utc)
|
| 44 |
+
return dt.timestamp()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def norm_location(loc: str | None) -> str:
|
| 48 |
+
if loc is None or loc == "":
|
| 49 |
+
return "--"
|
| 50 |
+
return str(loc)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def norm_station_id(
|
| 54 |
+
station_id: str | None = None,
|
| 55 |
+
network: str | None = None,
|
| 56 |
+
station: str | None = None,
|
| 57 |
+
location: str | None = None,
|
| 58 |
+
) -> str:
|
| 59 |
+
if station_id:
|
| 60 |
+
parts = str(station_id).split(".")
|
| 61 |
+
if len(parts) >= 3:
|
| 62 |
+
return f"{parts[0]}.{parts[1]}.{norm_location(parts[2])}"
|
| 63 |
+
return str(station_id)
|
| 64 |
+
return f"{network}.{station}.{norm_location(location)}"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass(frozen=True)
|
| 68 |
+
class LabelRow:
|
| 69 |
+
label_phase: str
|
| 70 |
+
station_id: str
|
| 71 |
+
label_time_epoch: float
|
| 72 |
+
matched: bool
|
| 73 |
+
has_waveform: bool
|
| 74 |
+
residual_s: float | None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def iter_jsonl(path: Path):
|
| 78 |
+
with path.open("r", encoding="utf-8", errors="replace") as f:
|
| 79 |
+
for line in f:
|
| 80 |
+
line = line.strip()
|
| 81 |
+
if line:
|
| 82 |
+
yield json.loads(line)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def load_labels_from_matches(matches_jsonl: Path) -> list[LabelRow]:
|
| 86 |
+
labels: list[LabelRow] = []
|
| 87 |
+
for rec in iter_jsonl(matches_jsonl):
|
| 88 |
+
if rec.get("subset") != "all":
|
| 89 |
+
continue
|
| 90 |
+
phase = str(rec.get("label_phase"))
|
| 91 |
+
if phase not in PHASE_MAP:
|
| 92 |
+
continue
|
| 93 |
+
labels.append(
|
| 94 |
+
LabelRow(
|
| 95 |
+
label_phase=phase,
|
| 96 |
+
station_id=str(rec.get("station_id")),
|
| 97 |
+
label_time_epoch=float(rec.get("label_time_epoch")),
|
| 98 |
+
matched=bool(rec.get("matched")),
|
| 99 |
+
has_waveform=bool(rec.get("has_waveform")),
|
| 100 |
+
residual_s=rec.get("residual_s"),
|
| 101 |
+
)
|
| 102 |
+
)
|
| 103 |
+
return labels
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def merge_intervals(intervals: list[tuple[float, float]]) -> list[tuple[float, float]]:
|
| 107 |
+
if not intervals:
|
| 108 |
+
return []
|
| 109 |
+
intervals = sorted(intervals)
|
| 110 |
+
merged = [intervals[0]]
|
| 111 |
+
for t0, t1 in intervals[1:]:
|
| 112 |
+
last0, last1 = merged[-1]
|
| 113 |
+
if t0 <= last1:
|
| 114 |
+
merged[-1] = (last0, max(last1, t1))
|
| 115 |
+
else:
|
| 116 |
+
merged.append((t0, t1))
|
| 117 |
+
return merged
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def build_phase_centered_station_windows(
|
| 121 |
+
labels: list[LabelRow],
|
| 122 |
+
half_width_s: float,
|
| 123 |
+
) -> dict[str, list[tuple[float, float]]]:
|
| 124 |
+
windows: dict[str, list[tuple[float, float]]] = defaultdict(list)
|
| 125 |
+
for lab in labels:
|
| 126 |
+
if not lab.has_waveform:
|
| 127 |
+
continue
|
| 128 |
+
windows[lab.station_id].append(
|
| 129 |
+
(lab.label_time_epoch - half_width_s, lab.label_time_epoch + half_width_s)
|
| 130 |
+
)
|
| 131 |
+
return {key: merge_intervals(vals) for key, vals in windows.items()}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def count_picks_in_window_sets(
|
| 135 |
+
auto_jsonl: Path,
|
| 136 |
+
window_sets: dict[str, dict[str, list[tuple[float, float]]]],
|
| 137 |
+
) -> dict[str, tuple[int, dict[str, int]]]:
|
| 138 |
+
starts_by_mode = {
|
| 139 |
+
mode: {key: [x[0] for x in vals] for key, vals in windows.items()}
|
| 140 |
+
for mode, windows in window_sets.items()
|
| 141 |
+
}
|
| 142 |
+
totals = {mode: 0 for mode in window_sets}
|
| 143 |
+
by_phase = {mode: Counter() for mode in window_sets}
|
| 144 |
+
for rec in iter_jsonl(auto_jsonl):
|
| 145 |
+
if rec.get("record_type") != "phase_pick":
|
| 146 |
+
continue
|
| 147 |
+
station_info = rec.get("station_info") or {}
|
| 148 |
+
station_id = norm_station_id(
|
| 149 |
+
rec.get("station_id") or station_info.get("station_id"),
|
| 150 |
+
station_info.get("network"),
|
| 151 |
+
station_info.get("station"),
|
| 152 |
+
station_info.get("location"),
|
| 153 |
+
)
|
| 154 |
+
phase = str(rec.get("phase_name"))
|
| 155 |
+
t = parse_utc_to_epoch_seconds(rec.get("phase_time"))
|
| 156 |
+
for mode, windows in window_sets.items():
|
| 157 |
+
intervals = windows.get(station_id)
|
| 158 |
+
if not intervals:
|
| 159 |
+
continue
|
| 160 |
+
starts = starts_by_mode[mode][station_id]
|
| 161 |
+
idx = bisect.bisect_right(starts, t) - 1
|
| 162 |
+
if idx >= 0 and intervals[idx][0] <= t <= intervals[idx][1]:
|
| 163 |
+
totals[mode] += 1
|
| 164 |
+
by_phase[mode][phase] += 1
|
| 165 |
+
return {mode: (totals[mode], dict(by_phase[mode])) for mode in window_sets}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def load_summary(summary_json: Path) -> dict[str, Any]:
|
| 169 |
+
return json.loads(summary_json.read_text(encoding="utf-8"))
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def load_total_duration_s(label_json: Path) -> float:
|
| 173 |
+
data = json.loads(label_json.read_text(encoding="utf-8"))
|
| 174 |
+
total = 0.0
|
| 175 |
+
for window in data.get("subset_windows", []):
|
| 176 |
+
total += parse_utc_to_epoch_seconds(window["endtime"]) - parse_utc_to_epoch_seconds(window["starttime"])
|
| 177 |
+
if total > 0:
|
| 178 |
+
return total
|
| 179 |
+
for year_obj in data.get("years", {}).values():
|
| 180 |
+
total += 86400.0 * len(year_obj.get("days", {}))
|
| 181 |
+
return total
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def summarize_residuals(labels: list[LabelRow]) -> dict[str, float | int | None]:
|
| 185 |
+
vals = [abs(float(x.residual_s)) for x in labels if x.residual_s is not None and math.isfinite(float(x.residual_s))]
|
| 186 |
+
if not vals:
|
| 187 |
+
return {"n_residual": 0, "abs_p95_s": None, "tail_gt_1p5_fraction": None}
|
| 188 |
+
vals.sort()
|
| 189 |
+
n = len(vals)
|
| 190 |
+
p95_idx = min(n - 1, int(math.ceil(0.95 * n)) - 1)
|
| 191 |
+
return {
|
| 192 |
+
"n_residual": n,
|
| 193 |
+
"abs_p95_s": vals[p95_idx],
|
| 194 |
+
"tail_gt_1p5_fraction": sum(v > 1.5 for v in vals) / n,
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def row_metrics(
|
| 199 |
+
mode: str,
|
| 200 |
+
n_label_cov: int,
|
| 201 |
+
n_tp_cov: int,
|
| 202 |
+
n_auto_picks: int,
|
| 203 |
+
duration_s: float | None,
|
| 204 |
+
selected_window_seconds: float | None,
|
| 205 |
+
residual_summary: dict[str, Any],
|
| 206 |
+
auto_by_phase: dict[str, int] | None = None,
|
| 207 |
+
) -> dict[str, Any]:
|
| 208 |
+
return {
|
| 209 |
+
"mode": mode,
|
| 210 |
+
"n_label_with_waveform": n_label_cov,
|
| 211 |
+
"n_tp_with_waveform": n_tp_cov,
|
| 212 |
+
"coverage_aware_recall": n_tp_cov / n_label_cov if n_label_cov else None,
|
| 213 |
+
"automatic_picks": n_auto_picks,
|
| 214 |
+
"automatic_picks_per_day": (n_auto_picks / duration_s * 86400.0) if duration_s else None,
|
| 215 |
+
"catalog_relative_explained_fraction": n_tp_cov / n_auto_picks if n_auto_picks else None,
|
| 216 |
+
"automatic_picks_per_covered_tp": n_auto_picks / n_tp_cov if n_tp_cov else None,
|
| 217 |
+
"selected_window_seconds_station_time": selected_window_seconds,
|
| 218 |
+
"automatic_pick_counts_by_phase": auto_by_phase or {},
|
| 219 |
+
**residual_summary,
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def main() -> None:
|
| 224 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 225 |
+
root = Path(__file__).resolve().parents[1]
|
| 226 |
+
parser.add_argument("--auto-jsonl", type=Path, default=root / "publish_mini/data/picks/pnsn_v3_diff.mini.phase.jsonl")
|
| 227 |
+
parser.add_argument("--matches-jsonl", type=Path, default=root / "publish_mini/eval_picks/example/matches.jsonl")
|
| 228 |
+
parser.add_argument("--summary-json", type=Path, default=root / "publish_mini/eval_picks/example/summary.json")
|
| 229 |
+
parser.add_argument("--label-json", type=Path, default=root / "publish_mini/data/label/annotations_mini_two_hours.json")
|
| 230 |
+
parser.add_argument("--outdir", type=Path, default=root / "paired_eval_mini")
|
| 231 |
+
parser.add_argument("--half-width-s", type=float, nargs="+", default=[10.0, 30.0])
|
| 232 |
+
args = parser.parse_args()
|
| 233 |
+
|
| 234 |
+
labels_all = load_labels_from_matches(args.matches_jsonl)
|
| 235 |
+
covered = [x for x in labels_all if x.has_waveform]
|
| 236 |
+
n_label_cov = len(covered)
|
| 237 |
+
n_tp_cov = sum(x.matched for x in covered)
|
| 238 |
+
residual_summary = summarize_residuals(covered)
|
| 239 |
+
|
| 240 |
+
full_summary = load_summary(args.summary_json)
|
| 241 |
+
n_auto_stream = int(full_summary["auto_pick_count"]["total"])
|
| 242 |
+
duration_s = load_total_duration_s(args.label_json)
|
| 243 |
+
|
| 244 |
+
rows: list[dict[str, Any]] = [
|
| 245 |
+
row_metrics(
|
| 246 |
+
"continuous_stream",
|
| 247 |
+
n_label_cov,
|
| 248 |
+
n_tp_cov,
|
| 249 |
+
n_auto_stream,
|
| 250 |
+
duration_s,
|
| 251 |
+
None,
|
| 252 |
+
residual_summary,
|
| 253 |
+
full_summary["auto_pick_count"].get("by_auto_phase", {}),
|
| 254 |
+
)
|
| 255 |
+
]
|
| 256 |
+
|
| 257 |
+
window_sets = {
|
| 258 |
+
f"phase_centered_snippets_pm{half_width:g}s": build_phase_centered_station_windows(labels_all, half_width)
|
| 259 |
+
for half_width in args.half_width_s
|
| 260 |
+
}
|
| 261 |
+
window_counts = count_picks_in_window_sets(args.auto_jsonl, window_sets)
|
| 262 |
+
|
| 263 |
+
for half_width in args.half_width_s:
|
| 264 |
+
mode = f"phase_centered_snippets_pm{half_width:g}s"
|
| 265 |
+
windows = window_sets[mode]
|
| 266 |
+
selected_seconds = sum(t1 - t0 for vals in windows.values() for t0, t1 in vals)
|
| 267 |
+
n_auto_snippet, by_phase = window_counts[mode]
|
| 268 |
+
rows.append(
|
| 269 |
+
row_metrics(
|
| 270 |
+
mode,
|
| 271 |
+
n_label_cov,
|
| 272 |
+
n_tp_cov,
|
| 273 |
+
n_auto_snippet,
|
| 274 |
+
None,
|
| 275 |
+
selected_seconds,
|
| 276 |
+
residual_summary,
|
| 277 |
+
by_phase,
|
| 278 |
+
)
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
args.outdir.mkdir(parents=True, exist_ok=True)
|
| 282 |
+
(args.outdir / "paired_snippet_stream_summary.json").write_text(
|
| 283 |
+
json.dumps(
|
| 284 |
+
{
|
| 285 |
+
"note": (
|
| 286 |
+
"Post-hoc paired evaluation-object diagnostic. The automatic "
|
| 287 |
+
"picker output is fixed; only the evaluation object changes. "
|
| 288 |
+
"Snippet denominators count all automatic picks inside the "
|
| 289 |
+
"selected station-time windows, not only matched phases."
|
| 290 |
+
),
|
| 291 |
+
"phase_map": PHASE_MAP,
|
| 292 |
+
"tp_tolerance_s": full_summary.get("tp_tolerance_s"),
|
| 293 |
+
"total_stream_duration_s": duration_s,
|
| 294 |
+
"rows": rows,
|
| 295 |
+
},
|
| 296 |
+
indent=2,
|
| 297 |
+
),
|
| 298 |
+
encoding="utf-8",
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
tsv_path = args.outdir / "paired_snippet_stream_summary.tsv"
|
| 302 |
+
fields = [
|
| 303 |
+
"mode",
|
| 304 |
+
"n_label_with_waveform",
|
| 305 |
+
"n_tp_with_waveform",
|
| 306 |
+
"coverage_aware_recall",
|
| 307 |
+
"automatic_picks",
|
| 308 |
+
"automatic_picks_per_day",
|
| 309 |
+
"catalog_relative_explained_fraction",
|
| 310 |
+
"automatic_picks_per_covered_tp",
|
| 311 |
+
"selected_window_seconds_station_time",
|
| 312 |
+
"n_residual",
|
| 313 |
+
"abs_p95_s",
|
| 314 |
+
"tail_gt_1p5_fraction",
|
| 315 |
+
]
|
| 316 |
+
with tsv_path.open("w", encoding="utf-8", newline="") as f:
|
| 317 |
+
writer = csv.DictWriter(f, fieldnames=fields, delimiter="\t", extrasaction="ignore")
|
| 318 |
+
writer.writeheader()
|
| 319 |
+
writer.writerows(rows)
|
| 320 |
+
|
| 321 |
+
print(json.dumps(rows, indent=2))
|
| 322 |
+
print(f"[OUT] {args.outdir}")
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
if __name__ == "__main__":
|
| 326 |
+
main()
|