cangyeone commited on
Commit
45fd53d
·
verified ·
1 Parent(s): 44cdb96

Upload essd_scripts/snr_filter_diagnostic.py

Browse files
Files changed (1) hide show
  1. essd_scripts/snr_filter_diagnostic.py +399 -0
essd_scripts/snr_filter_diagnostic.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """SNR-threshold diagnostics for continuous picker outputs.
3
+
4
+ This script tests a narrow claim: SNR filtering changes the operating point, but
5
+ it is not a substitute for continuous, denominator-aware evaluation. It reports
6
+ how SNR thresholds trade recall against continuous pick burden, and can write
7
+ SNR-filtered picker JSONL files for downstream association checks.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import bisect
14
+ import csv
15
+ import json
16
+ import math
17
+ from collections import Counter, defaultdict
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+
23
+ PHASE_MAP = {
24
+ "P": ["Pg"],
25
+ "S": ["Sg"],
26
+ }
27
+
28
+
29
+ def parse_utc_to_epoch_seconds(value: str) -> float:
30
+ text = str(value).strip()
31
+ if text.endswith("Z"):
32
+ text = text[:-1] + "+00:00"
33
+ dt = datetime.fromisoformat(text)
34
+ if dt.tzinfo is None:
35
+ dt = dt.replace(tzinfo=timezone.utc)
36
+ else:
37
+ dt = dt.astimezone(timezone.utc)
38
+ return dt.timestamp()
39
+
40
+
41
+ def norm_location(value: str | None) -> str:
42
+ if value is None or value == "":
43
+ return "--"
44
+ return str(value)
45
+
46
+
47
+ def norm_station_id(
48
+ station_id: str | None = None,
49
+ network: str | None = None,
50
+ station: str | None = None,
51
+ location: str | None = None,
52
+ ) -> str:
53
+ if station_id:
54
+ parts = str(station_id).split(".")
55
+ if len(parts) >= 3:
56
+ return f"{parts[0]}.{parts[1]}.{norm_location(parts[2])}"
57
+ return str(station_id)
58
+ return f"{network}.{station}.{norm_location(location)}"
59
+
60
+
61
+ def iter_jsonl(path: Path):
62
+ with path.open("r", encoding="utf-8", errors="replace") as handle:
63
+ for line in handle:
64
+ line = line.strip()
65
+ if line:
66
+ yield json.loads(line)
67
+
68
+
69
+ def in_time_window(epoch: float, start_epoch: float | None, end_epoch: float | None) -> bool:
70
+ if start_epoch is not None and epoch < start_epoch:
71
+ return False
72
+ if end_epoch is not None and epoch >= end_epoch:
73
+ return False
74
+ return True
75
+
76
+
77
+ def label_key(rec: dict[str, Any], ordinal: int) -> str:
78
+ return "|".join(
79
+ [
80
+ str(ordinal),
81
+ str(rec.get("event_id")),
82
+ str(rec.get("station_id")),
83
+ str(rec.get("label_phase")),
84
+ f"{float(rec.get('label_time_epoch')):.3f}",
85
+ ]
86
+ )
87
+
88
+
89
+ def load_labels(
90
+ matches_jsonl: Path,
91
+ start_epoch: float | None,
92
+ end_epoch: float | None,
93
+ ) -> list[dict[str, Any]]:
94
+ labels = []
95
+ ordinal = 0
96
+ for rec in iter_jsonl(matches_jsonl):
97
+ if rec.get("subset") != "all":
98
+ continue
99
+ if not rec.get("has_waveform"):
100
+ continue
101
+ phase = str(rec.get("label_phase"))
102
+ if phase not in PHASE_MAP:
103
+ continue
104
+ try:
105
+ epoch = float(rec["label_time_epoch"])
106
+ except Exception:
107
+ continue
108
+ if not in_time_window(epoch, start_epoch, end_epoch):
109
+ continue
110
+ ordinal += 1
111
+ key = label_key(rec, ordinal)
112
+ labels.append(
113
+ {
114
+ "key": key,
115
+ "event_id": rec.get("event_id"),
116
+ "station_id": norm_station_id(str(rec.get("station_id") or "")),
117
+ "label_phase": phase,
118
+ "label_time_epoch": epoch,
119
+ }
120
+ )
121
+ return labels
122
+
123
+
124
+ def percentile(values: list[float], q: float) -> float | None:
125
+ if not values:
126
+ return None
127
+ values = sorted(values)
128
+ if len(values) == 1:
129
+ return values[0]
130
+ pos = (len(values) - 1) * q
131
+ lo = math.floor(pos)
132
+ hi = math.ceil(pos)
133
+ if lo == hi:
134
+ return values[int(pos)]
135
+ return values[lo] * (hi - pos) + values[hi] * (pos - lo)
136
+
137
+
138
+ def nearest_pick(
139
+ picks: list[dict[str, Any]],
140
+ starts: list[float],
141
+ label_time_epoch: float,
142
+ threshold: float,
143
+ err_window_s: float,
144
+ ) -> dict[str, Any] | None:
145
+ left = bisect.bisect_left(starts, label_time_epoch - err_window_s)
146
+ right = bisect.bisect_right(starts, label_time_epoch + err_window_s)
147
+ best = None
148
+ best_abs = None
149
+ for item in picks[left:right]:
150
+ if item["snr"] < threshold:
151
+ continue
152
+ residual = item["time_epoch"] - label_time_epoch
153
+ abs_residual = abs(residual)
154
+ if best is None or abs_residual < best_abs:
155
+ best = {**item, "residual_s": residual}
156
+ best_abs = abs_residual
157
+ return best
158
+
159
+
160
+ def sweep_pick_metrics(args: argparse.Namespace) -> None:
161
+ thresholds = sorted(set(float(x) for x in args.thresholds))
162
+ start_epoch = parse_utc_to_epoch_seconds(args.starttime) if args.starttime else None
163
+ end_epoch = parse_utc_to_epoch_seconds(args.endtime) if args.endtime else None
164
+ labels = load_labels(args.matches_jsonl, start_epoch, end_epoch)
165
+
166
+ auto_counts = {threshold: Counter() for threshold in thresholds}
167
+ indexed: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
168
+ stats = Counter()
169
+
170
+ auto_to_label_phase = {}
171
+ for label_phase, auto_phases in PHASE_MAP.items():
172
+ for auto_phase in auto_phases:
173
+ auto_to_label_phase[auto_phase] = label_phase
174
+
175
+ for rec in iter_jsonl(args.picks_jsonl):
176
+ if rec.get("record_type") != "phase_pick":
177
+ stats[f"skip_record_type:{rec.get('record_type', '')}"] += 1
178
+ continue
179
+ stats["phase_pick_records"] += 1
180
+ try:
181
+ epoch = parse_utc_to_epoch_seconds(rec["phase_time"])
182
+ snr = float(rec["snr"])
183
+ except Exception:
184
+ stats["skip_bad_time_or_snr"] += 1
185
+ continue
186
+ if not in_time_window(epoch, start_epoch, end_epoch):
187
+ stats["skip_outside_time_window"] += 1
188
+ continue
189
+ phase = str(rec.get("phase_name") or "")
190
+ for threshold in thresholds:
191
+ if snr >= threshold:
192
+ auto_counts[threshold][phase] += 1
193
+ label_phase = auto_to_label_phase.get(phase)
194
+ if label_phase is None:
195
+ continue
196
+ station_info = rec.get("station_info") or {}
197
+ station_id = norm_station_id(
198
+ rec.get("station_id") or station_info.get("station_id"),
199
+ station_info.get("network"),
200
+ station_info.get("station"),
201
+ station_info.get("location"),
202
+ )
203
+ indexed[(station_id, label_phase)].append(
204
+ {
205
+ "time_epoch": epoch,
206
+ "snr": snr,
207
+ "phase_prob": rec.get("phase_prob"),
208
+ "phase_name": phase,
209
+ }
210
+ )
211
+
212
+ starts_by_key = {}
213
+ for key, values in indexed.items():
214
+ values.sort(key=lambda item: item["time_epoch"])
215
+ starts_by_key[key] = [item["time_epoch"] for item in values]
216
+
217
+ baseline_keys: set[str] = set()
218
+ rows = []
219
+ for threshold in thresholds:
220
+ tp = 0
221
+ matched_keys = set()
222
+ residuals = []
223
+ tp_snr = []
224
+ for lab in labels:
225
+ key = (lab["station_id"], lab["label_phase"])
226
+ pick = nearest_pick(
227
+ indexed.get(key, []),
228
+ starts_by_key.get(key, []),
229
+ lab["label_time_epoch"],
230
+ threshold,
231
+ args.err_window_s,
232
+ )
233
+ if pick is None:
234
+ continue
235
+ residual = float(pick["residual_s"])
236
+ if abs(residual) <= args.tp_tol_s:
237
+ tp += 1
238
+ matched_keys.add(lab["key"])
239
+ residuals.append(abs(residual))
240
+ tp_snr.append(float(pick["snr"]))
241
+ if threshold == thresholds[0]:
242
+ baseline_keys = set(matched_keys)
243
+ total_auto = int(sum(auto_counts[threshold].values()))
244
+ lost_from_baseline = len(baseline_keys - matched_keys) if baseline_keys else 0
245
+ row = {
246
+ "snr_threshold": threshold,
247
+ "automatic_picks": total_auto,
248
+ "automatic_pick_counts_by_phase": dict(sorted(auto_counts[threshold].items())),
249
+ "n_label_with_waveform": len(labels),
250
+ "n_tp_with_waveform": tp,
251
+ "coverage_aware_recall": tp / len(labels) if labels else None,
252
+ "catalog_relative_matched_fraction": tp / total_auto if total_auto else None,
253
+ "automatic_picks_per_covered_tp": total_auto / tp if tp else None,
254
+ "tp_retained_from_baseline_fraction": (
255
+ len(matched_keys & baseline_keys) / len(baseline_keys)
256
+ if baseline_keys
257
+ else None
258
+ ),
259
+ "baseline_tp_lost": lost_from_baseline,
260
+ "abs_residual_p95_s": percentile(residuals, 0.95),
261
+ "tp_snr_median": percentile(tp_snr, 0.50),
262
+ }
263
+ rows.append(row)
264
+
265
+ out = {
266
+ "diagnostic": "snr_threshold_pick_sweep",
267
+ "picks_jsonl": str(args.picks_jsonl),
268
+ "matches_jsonl": str(args.matches_jsonl),
269
+ "time_window": {
270
+ "starttime": args.starttime,
271
+ "endtime": args.endtime,
272
+ },
273
+ "matching": {
274
+ "phase_map": PHASE_MAP,
275
+ "tp_tolerance_s": args.tp_tol_s,
276
+ "search_window_s": args.err_window_s,
277
+ "waveform_covered_labels_only": True,
278
+ },
279
+ "stats": dict(sorted(stats.items())),
280
+ "rows": rows,
281
+ }
282
+ args.output_json.parent.mkdir(parents=True, exist_ok=True)
283
+ args.output_json.write_text(json.dumps(out, indent=2, ensure_ascii=False), encoding="utf-8")
284
+
285
+ if args.output_tsv:
286
+ args.output_tsv.parent.mkdir(parents=True, exist_ok=True)
287
+ fields = [
288
+ "snr_threshold",
289
+ "automatic_picks",
290
+ "n_label_with_waveform",
291
+ "n_tp_with_waveform",
292
+ "coverage_aware_recall",
293
+ "catalog_relative_matched_fraction",
294
+ "automatic_picks_per_covered_tp",
295
+ "tp_retained_from_baseline_fraction",
296
+ "baseline_tp_lost",
297
+ "abs_residual_p95_s",
298
+ "tp_snr_median",
299
+ ]
300
+ with args.output_tsv.open("w", encoding="utf-8", newline="") as handle:
301
+ writer = csv.DictWriter(handle, fieldnames=fields, delimiter="\t")
302
+ writer.writeheader()
303
+ for row in rows:
304
+ writer.writerow({field: row.get(field) for field in fields})
305
+
306
+ print(f"[OK] labels with waveform: {len(labels)}")
307
+ print(f"[OK] thresholds: {', '.join(str(x) for x in thresholds)}")
308
+ print(f"[OK] wrote: {args.output_json}")
309
+ if args.output_tsv:
310
+ print(f"[OK] wrote: {args.output_tsv}")
311
+
312
+
313
+ def filter_snr_jsonl(args: argparse.Namespace) -> None:
314
+ start_epoch = parse_utc_to_epoch_seconds(args.starttime) if args.starttime else None
315
+ end_epoch = parse_utc_to_epoch_seconds(args.endtime) if args.endtime else None
316
+ stats = Counter()
317
+ kept_by_phase = Counter()
318
+
319
+ args.output_jsonl.parent.mkdir(parents=True, exist_ok=True)
320
+ with args.output_jsonl.open("w", encoding="utf-8") as out:
321
+ for rec in iter_jsonl(args.picks_jsonl):
322
+ stats["input_records"] += 1
323
+ if rec.get("record_type") != "phase_pick":
324
+ stats[f"skip_record_type:{rec.get('record_type', '')}"] += 1
325
+ continue
326
+ try:
327
+ epoch = parse_utc_to_epoch_seconds(rec["phase_time"])
328
+ snr = float(rec["snr"])
329
+ except Exception:
330
+ stats["skip_bad_time_or_snr"] += 1
331
+ continue
332
+ if not in_time_window(epoch, start_epoch, end_epoch):
333
+ stats["skip_outside_time_window"] += 1
334
+ continue
335
+ stats["phase_pick_records_in_time_window"] += 1
336
+ if snr < args.snr_threshold:
337
+ stats["skip_below_snr_threshold"] += 1
338
+ continue
339
+ stats["kept_records"] += 1
340
+ kept_by_phase[str(rec.get("phase_name") or "")] += 1
341
+ out.write(json.dumps(rec, ensure_ascii=False, separators=(",", ":")) + "\n")
342
+
343
+ summary = {
344
+ "diagnostic": "snr_filtered_pick_jsonl",
345
+ "picks_jsonl": str(args.picks_jsonl),
346
+ "output_jsonl": str(args.output_jsonl),
347
+ "time_window": {
348
+ "starttime": args.starttime,
349
+ "endtime": args.endtime,
350
+ },
351
+ "snr_threshold": args.snr_threshold,
352
+ "kept_pick_counts": {
353
+ "total": int(stats["kept_records"]),
354
+ "by_phase": dict(sorted(kept_by_phase.items())),
355
+ },
356
+ "stats": dict(sorted(stats.items())),
357
+ }
358
+ args.summary_json.parent.mkdir(parents=True, exist_ok=True)
359
+ args.summary_json.write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
360
+ print(f"[OK] SNR >= {args.snr_threshold}: kept {stats['kept_records']} picks")
361
+ print(f"[OK] wrote: {args.output_jsonl}")
362
+ print(f"[OK] summary: {args.summary_json}")
363
+
364
+
365
+ def build_arg_parser() -> argparse.ArgumentParser:
366
+ parser = argparse.ArgumentParser(description=__doc__)
367
+ sub = parser.add_subparsers(dest="command", required=True)
368
+
369
+ p_sweep = sub.add_parser("sweep-pick-metrics", help="Sweep SNR thresholds for pick-level metrics.")
370
+ p_sweep.add_argument("--picks-jsonl", type=Path, required=True)
371
+ p_sweep.add_argument("--matches-jsonl", type=Path, required=True)
372
+ p_sweep.add_argument("--output-json", type=Path, required=True)
373
+ p_sweep.add_argument("--output-tsv", type=Path, default=None)
374
+ p_sweep.add_argument("--thresholds", type=float, nargs="+", default=[0, 1, 1.5, 2, 3, 5])
375
+ p_sweep.add_argument("--starttime", default=None)
376
+ p_sweep.add_argument("--endtime", default=None)
377
+ p_sweep.add_argument("--tp-tol-s", type=float, default=1.5)
378
+ p_sweep.add_argument("--err-window-s", type=float, default=5.0)
379
+ p_sweep.set_defaults(func=sweep_pick_metrics)
380
+
381
+ p_filter = sub.add_parser("filter-snr-jsonl", help="Write a picker JSONL filtered by SNR.")
382
+ p_filter.add_argument("--picks-jsonl", type=Path, required=True)
383
+ p_filter.add_argument("--output-jsonl", type=Path, required=True)
384
+ p_filter.add_argument("--summary-json", type=Path, required=True)
385
+ p_filter.add_argument("--snr-threshold", type=float, required=True)
386
+ p_filter.add_argument("--starttime", default=None)
387
+ p_filter.add_argument("--endtime", default=None)
388
+ p_filter.set_defaults(func=filter_snr_jsonl)
389
+
390
+ return parser
391
+
392
+
393
+ def main() -> None:
394
+ args = build_arg_parser().parse_args()
395
+ args.func(args)
396
+
397
+
398
+ if __name__ == "__main__":
399
+ main()