tooling(scratch): check file-only setup and note fields against Blastware's XML reports
verify_bw_fields_against_xml.py decodes each Blastware event file the way ingest does, without a report, and compares sample rate, record time, pre-trigger, sample count, the four notes and the job number with the event's _XML.XML report -- Blastware's full event report, which DL2 kept for 70,042 events back to 2016 (ASCII reports exist only for 2025-26). Every disagreement counts against SFM; there is no carve-out list yet. The first piece of the decode checker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
This commit is contained in:
1 parent
b4706a30f0
commit
f46afafdb4
1 file changed
+159
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
Check the setup and note fields SFM reads from a Blastware event file alone
|
||||
(#44/#45) against Blastware's own `_XML.XML` event report.
|
||||
|
||||
python scratch/verify_bw_fields_against_xml.py <binaries dir> <xml dir> [--jobs N]
|
||||
|
||||
Fields: sample rate; for waveforms, record time, pre-trigger (at the 3
|
||||
decimals Blastware prints) and the sample count (the XML's row count); the
|
||||
four user notes, in order. Notes are compared as the ordered list of
|
||||
non-empty values, because Blastware's XML names each one after its label
|
||||
("<Project>", "<Location>", ...), which the operator can change.
|
||||
|
||||
Any disagreement is reported as SFM's -- there is no carve-out list yet.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import html
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from minimateplus.event_file_io import read_blastware_file # noqa: E402
|
||||
|
||||
_BIN = re.compile(r"^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$", re.I)
|
||||
_EPOCH = datetime(1985, 1, 1)
|
||||
_SIMPLE = re.compile(rb"<([A-Za-z][\w.]*)>([^<]*)</\1>")
|
||||
|
||||
|
||||
def _event_year(name: str) -> int:
|
||||
stem, ext = name.upper().split(".")
|
||||
return (_EPOCH + timedelta(seconds=int(stem[4:8], 36) * 1296 + int(ext[:2], 36))).year
|
||||
|
||||
|
||||
def _xml_fields(xml: bytes) -> dict:
|
||||
head = xml[: xml.find(b"<WaveformDataChannels>") if b"<WaveformDataChannels>" in xml
|
||||
else xml.find(b"<HistogramData>")]
|
||||
out: dict = {}
|
||||
m = re.search(rb"<SampleRate>(\d+) sps</SampleRate>", head)
|
||||
out["sample_rate"] = int(m.group(1)) if m else None
|
||||
m = re.search(rb"<RecordTime>([\d.]+)", head)
|
||||
out["record_time"] = float(m.group(1)) if m else None
|
||||
m = re.search(rb"<Pre-triggerLength>(-?[\d.]+)", head)
|
||||
out["pretrig_s"] = float(m.group(1)) if m else None
|
||||
out["rows"] = xml.count(b"<Row>") if b"<WaveformDataChannels>" in xml else None
|
||||
# The notes sit between the top-level <Units> and <GeoRange>.
|
||||
u = head.find(b"</Units>")
|
||||
g = head.find(b"<GeoRange>")
|
||||
notes, out["job_number"] = [], None
|
||||
if u >= 0 and g > u:
|
||||
for tag, val in _SIMPLE.findall(head[u + len(b"</Units>"):g]):
|
||||
v = html.unescape(val.decode("utf-8", "replace")).strip()
|
||||
if tag == b"JobNumber": # its own field, not a note
|
||||
out["job_number"] = v
|
||||
elif v:
|
||||
notes.append(v)
|
||||
out["notes"] = notes
|
||||
return out
|
||||
|
||||
|
||||
def _check(args) -> list:
|
||||
name, bin_path, xml_path = args
|
||||
logging.disable(logging.CRITICAL)
|
||||
rows = []
|
||||
try:
|
||||
ev = read_blastware_file(bin_path)
|
||||
x = _xml_fields(Path(xml_path).read_bytes())
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return [(name, "decode", "error", repr(exc)[:120], None)]
|
||||
kind = name[-1].upper()
|
||||
sr = ev.sample_rate
|
||||
|
||||
def put(field, want, got, ok):
|
||||
rows.append((name, field, "match" if ok else ("SFM blank" if got is None else "MISMATCH"),
|
||||
want, got))
|
||||
|
||||
if x["sample_rate"] is not None:
|
||||
put("sample_rate", x["sample_rate"], sr, sr == x["sample_rate"])
|
||||
if kind == "W":
|
||||
if x["record_time"] is not None:
|
||||
rt = ev.rectime_seconds
|
||||
put("record_time", x["record_time"], rt,
|
||||
rt is not None and abs(rt - x["record_time"]) < 1e-4)
|
||||
if x["pretrig_s"] is not None:
|
||||
# Blastware prints 3 decimals, rounding halves away from zero
|
||||
# (-0.0625 s -> -0.063), so half a unit either way is a match.
|
||||
got = (-ev.pretrig_samples / sr
|
||||
if ev.pretrig_samples is not None and sr else None)
|
||||
put("pretrig", x["pretrig_s"], got,
|
||||
got is not None and abs(got - x["pretrig_s"]) <= 5e-4 + 1e-9)
|
||||
if x["rows"]:
|
||||
put("samples", x["rows"], ev.total_samples, ev.total_samples == x["rows"])
|
||||
pi = ev.project_info
|
||||
got = [v for v in (pi.project, pi.client, pi.operator, pi.sensor_location) if v]
|
||||
put("notes", x["notes"], got, got == x["notes"])
|
||||
if x["job_number"] is not None:
|
||||
jn = getattr(pi, "job_number", None)
|
||||
put("job_number", x["job_number"], jn, jn is not None and str(jn) == x["job_number"])
|
||||
return rows
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("bin_dir")
|
||||
ap.add_argument("xml_dir")
|
||||
ap.add_argument("--jobs", type=int, default=os.cpu_count())
|
||||
a = ap.parse_args()
|
||||
|
||||
xmls = {f.upper(): os.path.join(a.xml_dir, f) for f in os.listdir(a.xml_dir)}
|
||||
work, seen = [], set()
|
||||
for root, _, files in os.walk(a.bin_dir):
|
||||
for f in files:
|
||||
if not _BIN.match(f) or f.upper() in seen:
|
||||
continue
|
||||
seen.add(f.upper())
|
||||
x = xmls.get(f.upper().replace(".", "_") + "_XML.XML")
|
||||
if x:
|
||||
work.append((f, os.path.join(root, f), x))
|
||||
print(f"{len(seen)} event files, {len(work)} with an XML report")
|
||||
|
||||
tally = collections.Counter()
|
||||
examples = collections.defaultdict(list)
|
||||
with ProcessPoolExecutor(a.jobs) as pool:
|
||||
for rows in pool.map(_check, work, chunksize=64):
|
||||
for name, field, verdict, want, got in rows:
|
||||
yr = _event_year(name) if field != "decode" else 0
|
||||
tally[(field, name[-1].upper(), verdict)] += 1
|
||||
tally[(field, yr, verdict)] += 1
|
||||
if verdict != "match" and len(examples[(field, verdict)]) < 8:
|
||||
examples[(field, verdict)].append((name, want, got))
|
||||
|
||||
fields = ("sample_rate", "record_time", "pretrig", "samples", "notes", "job_number", "decode")
|
||||
print("\nfield type match mismatch SFM-blank error")
|
||||
for f in fields:
|
||||
for t in ("W", "H"):
|
||||
m, mm, b, e = (tally[(f, t, v)] for v in ("match", "MISMATCH", "SFM blank", "error"))
|
||||
if m + mm + b + e:
|
||||
print(f"{f:12s} {t:4s} {m:6d} {mm:9d} {b:10d} {e:6d}")
|
||||
years = sorted({k[1] for k in tally if isinstance(k[1], int) and k[1]})
|
||||
print("\nnot matching, by event year:")
|
||||
for f in fields[:-1]:
|
||||
bad = {y: tally[(f, y, "MISMATCH")] + tally[(f, y, "SFM blank")] for y in years}
|
||||
if any(bad.values()):
|
||||
print(f" {f:12s} " + " ".join(f"{y}:{n}" for y, n in bad.items() if n))
|
||||
for (f, v), ex in sorted(examples.items()):
|
||||
print(f"\n{f} -- {v}:")
|
||||
for name, want, got in ex:
|
||||
print(f" {name}: Blastware {want!r} SFM {got!r}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user