""" minimateplus/decode_check.py — SFM's file-only decode, set beside Blastware's report of the same event, field by field. The decode checker's core (`docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`). SFM's side comes from the event bytes alone, through `decode_blastware_bytes(raw, name=None)`: no filename, because SFM's own download and call-in paths have none, and no report overlay. Nothing from the reference reaches it. SFM's own assumptions stay in -- geophone counts become in/s at the Normal range -- because the point is to judge what SFM produces. Pure: no I/O, and no import from `sfm/`. """ from __future__ import annotations import re from dataclasses import dataclass from typing import Callable, Optional, Sequence from .bw_xml_report import XmlReport from .event_file_io import _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_FS_PSI, decode_blastware_bytes from .models import Event from .waveform_codec import mic_count_to_db # SFM's conversion: it cannot yet read the geophone range from the file, and # assumes Normal (10 in/s full scale = 32000 counts). GEO_IPS_PER_COUNT: float = _GEO_NORMAL_FS_INS / _GEO_INT16_FS _CHANNELS = ("Tran", "Vert", "Long", "MicL") _EVENT_TYPE = {"Waveform": "Full Waveform", "Histogram": "Full Histogram"} @dataclass class SfmSide: event: Event values: dict[str, object] # reference tag -> SFM's value; absent or None = blank notes: list[str] # non-empty user-note slots, in order job_number: Optional[str] # None until the decoder reads it channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order counts: dict[str, list[int]] # waveform samples or histogram interval peaks def sfm_side(raw: bytes) -> SfmSide: """What SFM makes of an event from its bytes alone.""" ev = decode_blastware_bytes(raw, name=None) counts = {ch: list((ev.raw_samples or {}).get(ch) or []) for ch in _CHANNELS} pv, pi, ts = ev.peak_values, ev.project_info, ev.timestamp values: dict[str, object] = { "EventType": _EVENT_TYPE.get(ev.record_type, ev.record_type), "SampleRate": ev.sample_rate, "RecordTime": ev.rectime_seconds, "Pre-triggerLength": (-ev.pretrig_samples / ev.sample_rate if ev.pretrig_samples is not None and ev.sample_rate else None), # SFM's interval count is its decoded entry count; the reference # carries this field for histograms only. "NumberofIntervals": len(counts["Tran"]) or None, } if ts is not None: date = f"{ts.year:04d}-{ts.month:02d}-{ts.day:02d}" time = f"{ts.hour:02d}:{ts.minute:02d}:{ts.second:02d}" # The event's time, under both of Blastware's names for it, so a time # is judged as a time even while the type is wrong (#41). values.update(EventDate=date, EventTime=time, HistogramStartDate=date, HistogramStartTime=time) if pv is not None: values.update(TranPPV=pv.tran, VertPPV=pv.vert, LongPPV=pv.long, PeakVectorSum=pv.peak_vector_sum) if counts["MicL"]: values["MicLPSPL dB(L)"] = mic_count_to_db(max(abs(c) for c in counts["MicL"])) values["MicLPSPL psi(L)"] = pv.micl if pv is not None else None return SfmSide( event=ev, values=values, notes=[v for v in (pi.project, pi.client, pi.operator, pi.sensor_location) if v] if pi is not None else [], job_number=None, channels=[ch for ch in _CHANNELS if counts[ch]], counts=counts, ) # ── The comparison ────────────────────────────────────────────────────────── VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error") # Not event data: the report's own format version and Blastware's file name. _NOT_COMPARED = {"FileVersion", "FileName"} _NUMBER = re.compile(r"^\s*(-?\d+(?:\.\d+)?)") _GEO = ("Tran", "Vert", "Long") @dataclass class FieldResult: field: str verdict: str bw: Optional[str] sfm: Optional[str] detail: str = "" carveout: Optional[str] = None def _printed_number(printed: str) -> Optional[tuple[float, int]]: m = _NUMBER.match(printed) if not m: return None num = m.group(1) return float(num), (len(num) - num.index(".") - 1 if "." in num else 0) def matches_printed(value: float, printed: str) -> bool: """True when `value` prints as `printed` at Blastware's precision. Blastware rounds halves away from zero (-0.0625 s -> -0.063), so half a unit of the last printed decimal either way is a match.""" p = _printed_number(printed) return p is not None and abs(value - p[0]) <= 0.5 * 10 ** -p[1] + 1e-9 def _render(value: object, printed: str) -> str: p = _printed_number(printed) if p is not None and isinstance(value, (int, float)) and not isinstance(value, bool): return f"{value:.{p[1]}f}" return str(value) def _same_text(a: object, b: str) -> bool: return " ".join(str(a).split()) == " ".join(b.split()) def _mic_converter(ref: XmlReport) -> Optional[Callable[[int], float]]: units = ref.event_units or "" if "dB(L)" in units: return mic_count_to_db if "psi(L)" in units: return lambda c: c * _MIC_FS_PSI return None def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> FieldResult: if not printed.strip() or printed.strip() == "N/A": return FieldResult(tag, "no_reference", printed, None) if tag == "MicLPSPL": units = ref.event_units or "" key = ("MicLPSPL dB(L)" if "dB(L)" in units else "MicLPSPL psi(L)" if "psi(L)" in units else None) value = sfm.values.get(key) if key else None else: value = sfm.values.get(tag) if value is None: return FieldResult(tag, "sfm_blank", printed, None) if printed.startswith(">"): # ZC frequency above range: SFM agrees only by setting its flag. flag = getattr(sfm.event.peak_values, tag[:-len("ZCFreq")].lower() + "_zc_above_range", False) return FieldResult(tag, "match" if flag else "mismatch", printed, str(value)) if printed == "OORANGE": return FieldResult(tag, "mismatch", printed, str(value)) if isinstance(value, (int, float)) and not isinstance(value, bool) and _printed_number(printed): ok = matches_printed(float(value), printed) else: ok = _same_text(value, printed) return FieldResult(tag, "match" if ok else "mismatch", printed, _render(value, printed)) def _cell_diff(value: float, printed: str) -> Optional[float]: """|value - printed| when the cell disagrees, else None; inf for a cell that is not a number.""" p = _printed_number(printed) if p is None: return float("inf") d = abs(value - p[0]) return d if d > 0.5 * 10 ** -p[1] + 1e-9 else None def _series_result(field: str, n_bw: int, n_sfm: int, diffs: list[tuple[int, float]], row_len: int) -> FieldResult: first = diffs[0][0] if diffs else None max_abs = max((d for _, d in diffs), default=0.0) ok = not diffs and not row_len return FieldResult( field, "match" if ok else "mismatch", f"{n_bw} rows", f"{n_sfm} values", f"rows={n_bw} sfm={n_sfm} differing={len(diffs)} row_length_disagreements={row_len} " f"first_diff={first} max_abs={max_abs:.4g}", ) def _compare_samples(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]: """One result per reference channel. A row holds only the channels still running, so row j's cells pair, in order, with the reference channels SFM has more than j samples of.""" rows = ref.sample_rows or [] mic = _mic_converter(ref) convert = {ch: (lambda c: c * GEO_IPS_PER_COUNT) for ch in _GEO} if mic is not None: convert["MicL"] = mic lens = {ch: len(sfm.counts.get(ch, [])) for ch in ref.channels} diffs: dict[str, list[tuple[int, float]]] = {ch: [] for ch in ref.channels} row_len = {ch: 0 for ch in ref.channels} for j, row in enumerate(rows): running = [ch for ch in ref.channels if lens[ch] > j] if len(running) != len(row): for ch in ref.channels: row_len[ch] += 1 continue for ch, cell in zip(running, row): if ch in convert: d = _cell_diff(convert[ch](sfm.counts[ch][j]), cell) if d is not None: diffs[ch].append((j, d)) out = [] for ch in ref.channels: if ch not in convert or not lens[ch]: out.append(FieldResult(f"samples.{ch}", "sfm_blank", f"{len(rows)} rows", None)) continue extra = max(0, lens[ch] - len(rows)) # SFM samples with no row at all out.append(_series_result(f"samples.{ch}", len(rows), lens[ch], diffs[ch], row_len[ch] + extra)) return out def _compare_intervals(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]: """One result per column, plus the interval times. SFM keeps each interval's peaks; it drops their frequencies and the geo PVS.""" intervals = ref.intervals or [] out = [FieldResult("intervals.Time", "sfm_blank", f"{len(intervals)} rows", None)] mic_db, mic_psi = mic_count_to_db, (lambda c: c * _MIC_FS_PSI) for i, title in enumerate(ref.interval_columns or []): field = f"intervals.{title}" ch, _, rest = title.partition(" ") if rest.startswith("Peak") and ch in _GEO: convert = lambda c: c * GEO_IPS_PER_COUNT # noqa: E731 elif ch == "MicL" and rest == "Peak dB(L)": convert = mic_db elif ch == "MicL" and rest == "Peak psi(L)": convert = mic_psi else: out.append(FieldResult(field, "sfm_blank", f"{len(intervals)} rows", None)) continue counts = sfm.counts.get(ch, []) if not counts: out.append(FieldResult(field, "sfm_blank", f"{len(intervals)} rows", None)) continue cells = [row[i] if i < len(row) else "" for _, row in intervals] diffs = [] for j, (cell, c) in enumerate(zip(cells, counts)): d = _cell_diff(convert(c), cell) if d is not None: diffs.append((j, d)) out.append(_series_result(field, len(cells), len(counts), diffs, abs(len(cells) - len(counts)))) return out def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]: """Every field Blastware's report carries, set against what SFM produced. A mismatch a carve-out covers and applies to becomes `accepted`.""" out = [_compare_scalar(tag, text, sfm, ref) for tag, text in ref.scalars.items() if tag not in _NOT_COMPARED] ref_notes = [v for _, v in ref.notes] if ref_notes and not sfm.notes: out.append(FieldResult("notes", "sfm_blank", " | ".join(ref_notes), None)) else: ok = [" ".join(v.split()) for v in ref_notes] == [" ".join(v.split()) for v in sfm.notes] out.append(FieldResult("notes", "match" if ok else "mismatch", " | ".join(ref_notes), " | ".join(sfm.notes))) if ref.job_number is not None: out.append(FieldResult("JobNumber", "sfm_blank", ref.job_number, None) if sfm.job_number is None else FieldResult("JobNumber", "match" if _same_text(sfm.job_number, ref.job_number) else "mismatch", ref.job_number, sfm.job_number)) out.append(FieldResult("Channels", "match" if ref.channels == sfm.channels else "mismatch", " ".join(ref.channels), " ".join(sfm.channels))) if ref.sample_rows is not None: out.extend(_compare_samples(sfm, ref)) if ref.intervals is not None: out.extend(_compare_intervals(sfm, ref)) for r in out: if r.verdict != "mismatch": continue for co in carveouts: covered = any(r.field == f or (f.endswith(".") and r.field.startswith(f)) for f in co.fields) if covered and co.applies(sfm, ref, r): r.verdict, r.carveout = "accepted", co.id break return out