#!/usr/bin/env python3 """Check that ESSD manuscript numbers agree with regenerated audit outputs.""" from __future__ import annotations import argparse import json import re from pathlib import Path from typing import Any from audit_manuscript_numbers import build_report ROOT = Path(__file__).resolve().parents[1] DEFAULT_TEX = ( ROOT / "overleaf-essd" / "template.tex" if (ROOT / "overleaf-essd" / "template.tex").exists() else ROOT / "essd" / "template.tex" ) def tex_int(value: int) -> str: return f"{value:,}".replace(",", r"\,") def norm(text: str) -> str: text = text.replace(r"\,", "") text = text.replace("~", "") text = text.replace(" ", "") return re.sub(r"\s+", "", text) def require(label: str, manuscript: str, snippet: str, failures: list[dict[str, str]]) -> None: if norm(snippet) not in manuscript: failures.append({"label": label, "expected_snippet": snippet}) def build_checks( report: dict[str, Any] ) -> list[tuple[str, str]]: inv = report["waveform_inventory"] ann = report["annotation_inventory"] cov = report["label_coverage"]["overall"] composition = report["reference_arrival_composition"] checks = [ ("daily HDF5 files", f"{inv['daily_hdf5_files']} daily HDF5 files"), ( "compressed waveform size", f"{inv['compressed_waveform_size_gib_rounded']}\\,GiB", ), ( "unique station keys", f"{inv['unique_network_station_keys']} unique network--station keys", ), ( "indexed waveform segments", f"{tex_int(inv['indexed_waveform_segments'])} indexed segments", ), ( "all-channel component-days", f"{tex_int(inv['all_channel_component_days_rounded'])} component-days", ), ( "main-family waveform segments", f"{tex_int(inv['main_family_segments'])} indexed segments", ), ( "main-family component-days", f"{tex_int(inv['main_family_component_days_rounded'])} component-days", ), ( "main-family station-day-family samples", f"{tex_int(inv['main_family_station_day_family_samples'])} station-day-family entries", ), ("events", f"{ann['summary']['event_count']} events"), ("P/S phase arrivals", f"{tex_int(ann['summary']['pick_count'])} P/S arrivals"), ( "C0 covered arrivals", f"{tex_int(cov['covered_labels'])} C0 point-covered source readings", ), ( "2019 period inventory", ( f"contains {tex_int(ann['periods']['2019']['events'])} catalogued events " f"and {tex_int(ann['periods']['2019']['phase_arrivals'])} P- and S-wave arrivals" ), ), ( "2021 period inventory", ( f"contains {tex_int(ann['periods']['2021']['events'])} catalogued events " f"and {tex_int(ann['periods']['2021']['phase_arrivals'])} P- and S-wave arrivals" ), ), ("automatic labels", tex_int(ann["status_counts"]["automatic"])), ("source records", tex_int(ann["summary"]["record_count"])), ("event-station associations", tex_int(ann["summary"]["station_event_count"])), ] period_names = {"2019": "2019 Ridgecrest", "2021": "2021 lower-seismicity"} for row in composition["groups"]: provenance = ( f"Manual {row['phase']}" if row["status"] == "manual" else f"Operational automatic {row['phase']}" ) values = [ period_names[row["period"]], provenance, tex_int(row["total_labels"]), tex_int(row["C0"]), f"{100 * row['C0_fraction']:.1f}", tex_int(row["C1"]), tex_int(row["C2"]), tex_int(row["C3"]), ] checks.append( ( f"reference composition {row['period']} {row['status']} {row['phase']}", " & ".join(values), ) ) total = composition["full_release"] checks.append( ( "full reference composition", " & ".join( [ "Full release", "All P/S arrivals", tex_int(total["total_labels"]), tex_int(total["C0"]), f"{100 * total['C0_fraction']:.1f}", tex_int(total["C1"]), tex_int(total["C2"]), tex_int(total["C3"]), ] ), ) ) canonical = composition["canonical_manual"] checks.extend( [ ( "canonical C0 manual denominator", f"{tex_int(canonical['C0'])} C0-qualified manual references", ), ( "canonical C1 manual denominator", f"{tex_int(canonical['C1'])} at C1", ), ( "canonical C2 manual denominator", f"{tex_int(canonical['C2'])} at both C2 and C3", ), ( "canonical expanded C0 denominator", f"{tex_int(composition['canonical_expanded']['C0'])} unique C0 references", ), ] ) return checks def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--tex", type=Path, default=DEFAULT_TEX) parser.add_argument("--format", choices=("text", "json"), default="text") args = parser.parse_args() report = build_report() manuscript = norm(args.tex.read_text(encoding="utf-8")) failures: list[dict[str, str]] = [] checks = build_checks(report) for label, snippet in checks: require(label, manuscript, snippet, failures) result = { "tex": str(args.tex.relative_to(ROOT) if args.tex.is_relative_to(ROOT) else args.tex), "status": "pass" if not failures else "fail", "checked_core_items": len(checks), "failures": failures, } if args.format == "json": print(json.dumps(result, indent=2, ensure_ascii=False)) else: if failures: print("[FAIL] Manuscript number consistency check") for item in failures: print(f"- {item['label']}: missing {item['expected_snippet']}") else: print("[OK] Manuscript numbers match regenerated ESSD audit outputs.") print(f"Core items checked: {result['checked_core_items']}") raise SystemExit(1 if failures else 0) if __name__ == "__main__": main()