""" 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_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT, decode_blastware_bytes) from .models import Event from .waveform_codec import mic_count_to_db # SFM's conversion at the Normal range (10 in/s full scale = 32000 counts), # which SFM assumes when it cannot read the event's range from the file. 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 geo_ips_per_count: float = GEO_IPS_PER_COUNT # at the event's range, as SFM read it 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, "GeoRange": _GEO_FS_BY_RANGE.get(ev.geo_range), } 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, geo_ips_per_count=_GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) / _GEO_INT16_FS, ) # ── 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_PSI_PER_COUNT 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 _sample_converters(sfm: SfmSide, ref: XmlReport) -> dict[str, Callable[[int], float]]: k = sfm.geo_ips_per_count convert: dict[str, Callable[[int], float]] = {ch: (lambda c: c * k) for ch in _GEO} mic = _mic_converter(ref) if mic is not None: convert["MicL"] = mic return convert def _interval_converter(title: str, sfm: SfmSide) -> Optional[Callable[[int], float]]: """SFM keeps each interval's peaks; it drops their frequencies and geo PVS.""" ch, _, rest = title.partition(" ") if rest.startswith("Peak") and ch in _GEO: return lambda c: c * sfm.geo_ips_per_count if ch == "MicL" and rest == "Peak dB(L)": return mic_count_to_db if ch == "MicL" and rest == "Peak psi(L)": return lambda c: c * _MIC_PSI_PER_COUNT return None def series_pairs(sfm: SfmSide, ref: XmlReport, field: str) -> Optional[tuple[list[tuple[int, str, float]], int]]: """For a `samples.` or `intervals.` field: the (index, printed cell, SFM value) pairs and the count of row-length disagreements, or None when SFM has no conversion or no data for it. A waveform 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; a row whose cell count differs is a disagreement for every channel.""" if field.startswith("samples."): ch = field[len("samples."):] convert = _sample_converters(sfm, ref).get(ch) counts = sfm.counts.get(ch, []) if convert is None or not counts: return None rows = ref.sample_rows or [] lens = {c: len(sfm.counts.get(c, [])) for c in ref.channels} pairs, row_len = [], 0 for j, row in enumerate(rows): running = [c for c in ref.channels if lens[c] > j] if len(running) != len(row): row_len += 1 elif ch in running: pairs.append((j, row[running.index(ch)], convert(counts[j]))) return pairs, row_len + max(0, len(counts) - len(rows)) if field.startswith("intervals."): title = field[len("intervals."):] columns = ref.interval_columns or [] convert = _interval_converter(title, sfm) counts = sfm.counts.get(title.partition(" ")[0], []) if convert is None or not counts or title not in columns: return None i = columns.index(title) cells = [row[i] if i < len(row) else "" for _, row in (ref.intervals or [])] pairs = [(j, cell, convert(c)) for j, (cell, c) in enumerate(zip(cells, counts))] return pairs, abs(len(cells) - len(counts)) return None def _compare_series(field: str, n_bw: int, sfm: SfmSide, ref: XmlReport) -> FieldResult: got = series_pairs(sfm, ref, field) if got is None: return FieldResult(field, "sfm_blank", f"{n_bw} rows", None) pairs, row_len = got diffs = [(j, d) for j, cell, v in pairs if (d := _cell_diff(v, cell)) is not None] n_sfm = len(sfm.counts.get(field.split(".", 1)[1].partition(" ")[0], [])) return _series_result(field, n_bw, n_sfm, diffs, row_len) def _compare_samples(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]: """One result per reference channel.""" n = len(ref.sample_rows or []) return [_compare_series(f"samples.{ch}", n, sfm, ref) for ch in ref.channels] def _compare_intervals(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]: """One result per column, plus the interval times, which SFM does not keep.""" n = len(ref.intervals or []) return ([FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)] + [_compare_series(f"intervals.{t}", n, sfm, ref) for t in ref.interval_columns or []]) 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