cangyeone commited on
Commit
72ad5a3
·
verified ·
1 Parent(s): 275dd1e

Upload essd_scripts/audit_manuscript_numbers.py

Browse files
essd_scripts/audit_manuscript_numbers.py CHANGED
@@ -13,6 +13,7 @@ import json
13
  import math
14
  import sqlite3
15
  import statistics
 
16
  from collections import Counter, defaultdict
17
  from pathlib import Path
18
  from typing import Any
@@ -26,9 +27,15 @@ except Exception: # pragma: no cover
26
 
27
 
28
  ROOT = Path(__file__).resolve().parents[1]
 
 
 
 
 
29
  LABEL_JSON = ROOT / "data" / "label" / "annotations_for_continuous_hdf5.json"
30
  CONSENSUS_JSON = ROOT / "data" / "label" / "consensus_nn_picks.json"
31
  WAVEFORM_DB = ROOT / "data" / "index" / "waveform_index.sqlite"
 
32
  H5_DIR = ROOT / "data" / "hdf5"
33
  EVAL_DIR = ROOT / "eval_picks"
34
 
@@ -192,38 +199,133 @@ def waveform_inventory() -> dict[str, Any]:
192
  }
193
 
194
 
195
- def label_coverage_from_matches() -> dict[str, Any]:
196
- matches = EVAL_DIR / "eval_phasenet" / "matches.jsonl"
 
 
 
197
  counts: Counter = Counter()
198
  by_period: dict[str, Counter] = defaultdict(Counter)
199
  by_period_subset: dict[str, Counter] = defaultdict(Counter)
200
- with matches.open() as f:
201
- for line in f:
202
- rec = json.loads(line)
203
- period = "2019" if rec["label_time_epoch"] < 1600000000 else "2021"
204
- phase = rec.get("label_phase")
205
- subset = rec.get("subset")
206
- if subset == "all":
207
- counts["labels"] += 1
208
- counts[f"{phase}_labels"] += 1
209
- by_period[period]["labels"] += 1
210
- by_period[period][f"{phase}_labels"] += 1
211
- if rec.get("has_waveform"):
212
- counts["covered_labels"] += 1
213
- counts[f"{phase}_covered_labels"] += 1
214
- by_period[period]["covered_labels"] += 1
215
- by_period[period][f"{phase}_covered_labels"] += 1
216
- if subset in {"manual", "automatic"}:
217
- key = f"{subset}_{phase}"
218
- by_period_subset[period][f"{key}_labels"] += 1
219
- if rec.get("has_waveform"):
220
- by_period_subset[period][f"{key}_covered_labels"] += 1
221
 
222
- return {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  "overall": dict(sorted(counts.items())),
224
  "by_period": {k: dict(v) for k, v in sorted(by_period.items())},
225
  "by_period_and_label_status": {k: dict(v) for k, v in sorted(by_period_subset.items())},
226
- "source": str(matches.relative_to(ROOT)),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  }
228
 
229
 
@@ -351,29 +453,35 @@ def consensus_audit() -> dict[str, Any]:
351
  }
352
 
353
 
354
- def build_report() -> dict[str, Any]:
355
  annotation = load_json(LABEL_JSON)
356
- return {
357
  "sources": {
358
  "annotation_json": str(LABEL_JSON.relative_to(ROOT)),
359
  "waveform_index": str(WAVEFORM_DB.relative_to(ROOT)),
360
  "hdf5_directory": str(H5_DIR.relative_to(ROOT)),
361
- "evaluation_directory": str(EVAL_DIR.relative_to(ROOT)),
362
  },
363
  "annotation_inventory": annotation_inventory(annotation),
364
  "waveform_inventory": waveform_inventory(),
365
- "label_coverage": label_coverage_from_matches(),
366
- "operational_diagnostics": operational_diagnostics(),
367
- "baseline_table": baseline_table(),
368
- "consensus_audit": consensus_audit(),
369
  }
 
 
 
 
 
 
 
 
 
 
370
 
371
 
372
  def print_text(report: dict[str, Any]) -> None:
373
  inv = report["waveform_inventory"]
374
  ann = report["annotation_inventory"]
375
  cov = report["label_coverage"]["overall"]
376
- ops = report["operational_diagnostics"]
377
  print("ESSD manuscript number audit")
378
  print(f"HDF5 files: {inv['daily_hdf5_files']}")
379
  print(f"Compressed waveform size: {inv['compressed_waveform_size_gib']:.1f} GiB")
@@ -386,14 +494,22 @@ def print_text(report: dict[str, Any]) -> None:
386
  print(f"Manual labels: {ann['status_counts']['manual']:,}")
387
  print(f"Automatic labels: {ann['status_counts']['automatic']:,}")
388
  print(f"Covered arrivals: {cov['covered_labels']:,}")
 
389
  print(
390
- "Operational diagnostics: "
391
- f"recall max={ops['coverage_aware_recall_max']:.2f}, "
392
- f"matched fraction={100*ops['catalog_matched_fraction_min']:.1f}-"
393
- f"{100*ops['catalog_matched_fraction_max']:.1f}%, "
394
- f"pick volume={ops['automatic_picks_per_day_min']:.1e}-"
395
- f"{ops['automatic_picks_per_day_max']:.1e} picks/day"
396
  )
 
 
 
 
 
 
 
 
 
 
397
 
398
 
399
  def print_latex_baseline(report: dict[str, Any]) -> None:
@@ -423,14 +539,79 @@ def print_latex_baseline(report: dict[str, Any]) -> None:
423
  print("\\middlehline")
424
 
425
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426
  def main() -> None:
427
  parser = argparse.ArgumentParser(description=__doc__)
428
- parser.add_argument("--format", choices=("json", "text", "latex-baseline"), default="text")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  args = parser.parse_args()
430
-
431
- report = build_report()
432
- if args.format == "json":
 
 
 
 
 
 
 
 
433
  print(json.dumps(report, indent=2, sort_keys=True))
 
 
434
  elif args.format == "latex-baseline":
435
  print_latex_baseline(report)
436
  else:
 
13
  import math
14
  import sqlite3
15
  import statistics
16
+ import sys
17
  from collections import Counter, defaultdict
18
  from pathlib import Path
19
  from typing import Any
 
27
 
28
 
29
  ROOT = Path(__file__).resolve().parents[1]
30
+ if str(ROOT) not in sys.path:
31
+ sys.path.insert(0, str(ROOT))
32
+
33
+ from scripts.evaluate_picks import WaveformCoverageIndex, parse_utc_to_epoch_seconds
34
+
35
  LABEL_JSON = ROOT / "data" / "label" / "annotations_for_continuous_hdf5.json"
36
  CONSENSUS_JSON = ROOT / "data" / "label" / "consensus_nn_picks.json"
37
  WAVEFORM_DB = ROOT / "data" / "index" / "waveform_index.sqlite"
38
+ REFERENCE_DB = ROOT / "data" / "label" / "reference_arrivals.sqlite"
39
  H5_DIR = ROOT / "data" / "hdf5"
40
  EVAL_DIR = ROOT / "eval_picks"
41
 
 
199
  }
200
 
201
 
202
+ def label_coverage_from_index(annotation: dict[str, Any]) -> dict[str, Any]:
203
+ """Compute point coverage from exact NSLC segments and finite HDF5 samples."""
204
+ coverage = WaveformCoverageIndex(
205
+ WAVEFORM_DB, channel_families=("HH", "BH", "EH", "HN")
206
+ )
207
  counts: Counter = Counter()
208
  by_period: dict[str, Counter] = defaultdict(Counter)
209
  by_period_subset: dict[str, Counter] = defaultdict(Counter)
210
+ by_family: Counter = Counter()
211
+ by_components: Counter = Counter()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
+ for day, _, station_id, pick in iter_picks(annotation):
214
+ period = period_from_day(day)
215
+ phase = str(pick.get("phase"))
216
+ status = str(pick.get("status", "unknown"))
217
+ time_epoch = parse_utc_to_epoch_seconds(pick.get("time"))
218
+ details = coverage.coverage_details(station_id, time_epoch)
219
+
220
+ counts["labels"] += 1
221
+ counts[f"{phase}_labels"] += 1
222
+ by_period[period]["labels"] += 1
223
+ by_period[period][f"{phase}_labels"] += 1
224
+ status_key = f"{status}_{phase}"
225
+ by_period_subset[period][f"{status_key}_labels"] += 1
226
+
227
+ if details["point_covered"]:
228
+ counts["covered_labels"] += 1
229
+ counts[f"{phase}_covered_labels"] += 1
230
+ by_period[period]["covered_labels"] += 1
231
+ by_period[period][f"{phase}_covered_labels"] += 1
232
+ by_period_subset[period][f"{status_key}_covered_labels"] += 1
233
+ by_family[str(details["channel_family"])] += 1
234
+ by_components[str(details["component_count"])] += 1
235
+
236
+ result = {
237
  "overall": dict(sorted(counts.items())),
238
  "by_period": {k: dict(v) for k, v in sorted(by_period.items())},
239
  "by_period_and_label_status": {k: dict(v) for k, v in sorted(by_period_subset.items())},
240
+ "covered_by_selected_family": dict(sorted(by_family.items())),
241
+ "covered_by_component_count": dict(sorted(by_components.items())),
242
+ "definition": {
243
+ "coverage_level": "C0 point coverage",
244
+ "channel_families": ["HH", "BH", "EH", "HN"],
245
+ "interval_source": (
246
+ "exact NSLC waveform_segments rows with finite-sample checks "
247
+ "for floating-point HDF5 arrays"
248
+ ),
249
+ "location_rule": (
250
+ "explicit locations match exactly; '--' annotations are treated as "
251
+ "unspecified and match one released location without combining locations"
252
+ ),
253
+ },
254
+ "sources": [
255
+ str(LABEL_JSON.relative_to(ROOT)),
256
+ str(WAVEFORM_DB.relative_to(ROOT)),
257
+ str(H5_DIR.relative_to(ROOT)),
258
+ ],
259
+ }
260
+ coverage.close()
261
+ return result
262
+
263
+
264
+ def reference_arrival_composition() -> dict[str, Any]:
265
+ """Summarize C0--C3 eligibility by period, phase, and provenance."""
266
+ con = sqlite3.connect(REFERENCE_DB)
267
+ rows = con.execute(
268
+ """
269
+ SELECT period, phase, status, COUNT(*) AS total,
270
+ SUM(c0_point_covered) AS c0,
271
+ SUM(c1_window_covered) AS c1,
272
+ SUM(c2_component_covered) AS c2,
273
+ SUM(c3_processing_ready) AS c3
274
+ FROM reference_arrivals
275
+ GROUP BY period, phase, status
276
+ ORDER BY CAST(period AS INTEGER),
277
+ CASE phase WHEN 'P' THEN 0 ELSE 1 END,
278
+ CASE status WHEN 'manual' THEN 0 ELSE 1 END
279
+ """
280
+ ).fetchall()
281
+ total = con.execute(
282
+ """
283
+ SELECT COUNT(*), SUM(c0_point_covered), SUM(c1_window_covered),
284
+ SUM(c2_component_covered), SUM(c3_processing_ready)
285
+ FROM reference_arrivals
286
+ """
287
+ ).fetchone()
288
+ con.close()
289
+
290
+ groups = []
291
+ for period, phase, status, n_total, c0, c1, c2, c3 in rows:
292
+ role = "primary" if status == "manual" else "expanded only"
293
+ groups.append(
294
+ {
295
+ "period": str(period),
296
+ "phase": str(phase),
297
+ "status": str(status),
298
+ "total_labels": int(n_total),
299
+ "C0": int(c0),
300
+ "without_C0": int(n_total - c0),
301
+ "C0_fraction": float(c0 / n_total),
302
+ "C1": int(c1),
303
+ "C2": int(c2),
304
+ "C3": int(c3),
305
+ "reference_role": role,
306
+ }
307
+ )
308
+
309
+ n_total, c0, c1, c2, c3 = map(int, total)
310
+ return {
311
+ "groups": groups,
312
+ "full_release": {
313
+ "total_labels": n_total,
314
+ "C0": c0,
315
+ "without_C0": n_total - c0,
316
+ "C0_fraction": c0 / n_total,
317
+ "C1": c1,
318
+ "C2": c2,
319
+ "C3": c3,
320
+ "reference_role": "primary plus expanded",
321
+ },
322
+ "sequential_attrition": {
323
+ "annotation_to_C0": n_total - c0,
324
+ "C0_to_C1": c0 - c1,
325
+ "C1_to_C2": c1 - c2,
326
+ "C2_to_C3": c2 - c3,
327
+ },
328
+ "source": str(REFERENCE_DB.relative_to(ROOT)),
329
  }
330
 
331
 
 
453
  }
454
 
455
 
456
+ def build_report(include_example_outputs: bool = False) -> dict[str, Any]:
457
  annotation = load_json(LABEL_JSON)
458
+ report = {
459
  "sources": {
460
  "annotation_json": str(LABEL_JSON.relative_to(ROOT)),
461
  "waveform_index": str(WAVEFORM_DB.relative_to(ROOT)),
462
  "hdf5_directory": str(H5_DIR.relative_to(ROOT)),
 
463
  },
464
  "annotation_inventory": annotation_inventory(annotation),
465
  "waveform_inventory": waveform_inventory(),
466
+ "label_coverage": label_coverage_from_index(annotation),
467
+ "reference_arrival_composition": reference_arrival_composition(),
 
 
468
  }
469
+ if include_example_outputs:
470
+ report["sources"]["evaluation_directory"] = str(EVAL_DIR.relative_to(ROOT))
471
+ report["operational_diagnostics"] = operational_diagnostics()
472
+ report["baseline_table"] = baseline_table()
473
+ report["consensus_audit"] = consensus_audit()
474
+ report["example_output_warning"] = (
475
+ "These stored outputs predate the current one-to-one matching policy "
476
+ "unless they have been regenerated with the current evaluate_picks.py."
477
+ )
478
+ return report
479
 
480
 
481
  def print_text(report: dict[str, Any]) -> None:
482
  inv = report["waveform_inventory"]
483
  ann = report["annotation_inventory"]
484
  cov = report["label_coverage"]["overall"]
 
485
  print("ESSD manuscript number audit")
486
  print(f"HDF5 files: {inv['daily_hdf5_files']}")
487
  print(f"Compressed waveform size: {inv['compressed_waveform_size_gib']:.1f} GiB")
 
494
  print(f"Manual labels: {ann['status_counts']['manual']:,}")
495
  print(f"Automatic labels: {ann['status_counts']['automatic']:,}")
496
  print(f"Covered arrivals: {cov['covered_labels']:,}")
497
+ ref = report["reference_arrival_composition"]["full_release"]
498
  print(
499
+ "Configured reference eligibility: "
500
+ f"C0={ref['C0']:,}, C1={ref['C1']:,}, "
501
+ f"C2={ref['C2']:,}, C3={ref['C3']:,}"
 
 
 
502
  )
503
+ if "operational_diagnostics" in report:
504
+ ops = report["operational_diagnostics"]
505
+ print(
506
+ "Example-output diagnostics: "
507
+ f"recall max={ops['coverage_aware_recall_max']:.2f}, "
508
+ f"matched fraction={100*ops['catalog_matched_fraction_min']:.1f}-"
509
+ f"{100*ops['catalog_matched_fraction_max']:.1f}%, "
510
+ f"pick volume={ops['automatic_picks_per_day_min']:.1e}-"
511
+ f"{ops['automatic_picks_per_day_max']:.1e} picks/day"
512
+ )
513
 
514
 
515
  def print_latex_baseline(report: dict[str, Any]) -> None:
 
539
  print("\\middlehline")
540
 
541
 
542
+ def print_latex_reference(report: dict[str, Any]) -> None:
543
+ composition = report["reference_arrival_composition"]
544
+ for row in composition["groups"]:
545
+ period = "2019 Ridgecrest" if row["period"] == "2019" else "2021 background"
546
+ provenance = (
547
+ f"{row['status'].capitalize()} {row['phase']}"
548
+ if row["status"] == "manual"
549
+ else f"Operational automatic {row['phase']}"
550
+ )
551
+ role = "Primary" if row["reference_role"] == "primary" else "Expanded only"
552
+ values = [
553
+ period,
554
+ provenance,
555
+ f"{row['total_labels']:,}".replace(",", r"\,"),
556
+ f"{row['C0']:,}".replace(",", r"\,"),
557
+ f"{row['without_C0']:,}".replace(",", r"\,"),
558
+ f"{100 * row['C0_fraction']:.1f}\\,\\%",
559
+ f"{row['C1']:,}".replace(",", r"\,"),
560
+ f"{row['C2']:,}".replace(",", r"\,"),
561
+ f"{row['C3']:,}".replace(",", r"\,"),
562
+ role,
563
+ ]
564
+ print(" & ".join(values) + r" \\")
565
+ total = composition["full_release"]
566
+ values = [
567
+ "Full release",
568
+ "All P/S labels",
569
+ f"{total['total_labels']:,}".replace(",", r"\,"),
570
+ f"{total['C0']:,}".replace(",", r"\,"),
571
+ f"{total['without_C0']:,}".replace(",", r"\,"),
572
+ f"{100 * total['C0_fraction']:.1f}\\,\\%",
573
+ f"{total['C1']:,}".replace(",", r"\,"),
574
+ f"{total['C2']:,}".replace(",", r"\,"),
575
+ f"{total['C3']:,}".replace(",", r"\,"),
576
+ "Primary + expanded",
577
+ ]
578
+ print("\\middlehline")
579
+ print(" & ".join(values) + r" \\")
580
+
581
+
582
  def main() -> None:
583
  parser = argparse.ArgumentParser(description=__doc__)
584
+ parser.add_argument(
585
+ "--format",
586
+ choices=(
587
+ "json",
588
+ "json-reference",
589
+ "text",
590
+ "latex-reference",
591
+ "latex-baseline",
592
+ ),
593
+ default="text",
594
+ )
595
+ parser.add_argument(
596
+ "--include-example-outputs",
597
+ action="store_true",
598
+ help="Also read stored non-standardized picker and consensus outputs.",
599
+ )
600
  args = parser.parse_args()
601
+ if args.format == "latex-baseline" and not args.include_example_outputs:
602
+ parser.error("--format latex-baseline requires --include-example-outputs")
603
+
604
+ if args.format in {"latex-reference", "json-reference"}:
605
+ report = {
606
+ "sources": {"reference_arrival_table": str(REFERENCE_DB.relative_to(ROOT))},
607
+ "reference_arrival_composition": reference_arrival_composition(),
608
+ }
609
+ else:
610
+ report = build_report(include_example_outputs=args.include_example_outputs)
611
+ if args.format in {"json", "json-reference"}:
612
  print(json.dumps(report, indent=2, sort_keys=True))
613
+ elif args.format == "latex-reference":
614
+ print_latex_reference(report)
615
  elif args.format == "latex-baseline":
616
  print_latex_baseline(report)
617
  else: