""" minimateplus/decode_check_carveouts.py — the proven ways Blastware's report differs from the instrument's data. Every disagreement between SFM and Blastware is SFM's bug until shown otherwise. A carve-out is that showing: the fields it covers, the rule it applies, and evidence that does not rest on SFM's own output -- Blastware contradicting itself, the instrument's own data, a third source, or Instantel documentation. `compare` turns a covered mismatch into `accepted` only when the rule holds, and every run counts the events each carve-out covers. Pure: no I/O, and no import from `sfm/`. """ from __future__ import annotations from dataclasses import dataclass from typing import Callable from .bw_xml_report import XmlReport from .decode_check import (FieldResult, SfmSide, _mic_table_units, _printed_number, series_pairs, matches_printed) from .event_file_io import _MIC_PSI_PER_COUNT from .waveform_codec import mic_count_to_db @dataclass(frozen=True) class Carveout: id: str fields: tuple[str, ...] # exact names, or prefixes ending in "." evidence: str applies: Callable[[SfmSide, XmlReport, FieldResult], bool] _TOL = 0.0006 def _at_ceiling(value: float, r: float) -> bool: """SFM's value sits at the range ceiling: a decoder unit or two past nominal full scale is the clipped count itself (32016 = 10.005 in/s). An 8x Sensitive-range value is far above the band and does not qualify.""" return r - _TOL <= abs(value) <= r * 1.01 def _clamped(printed: str, r: float) -> bool: if printed.strip() == "OORANGE": return True p = _printed_number(printed) return p is not None and abs(p[0]) >= r - _TOL def _differs(v: object, cell: str) -> bool: """A cell SFM disagrees with. SFM's own word (its OORANGE, since 2026-11-09) agrees only when Blastware printed the same word.""" if isinstance(v, str): return " ".join(v.split()) != " ".join(cell.split()) return not matches_printed(v, cell) def _saturation(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool: try: r = float(ref.scalars["GeoRange"]) except (KeyError, ValueError): return False if res.field in ("TranPPV", "VertPPV", "LongPPV"): v = sfm.values.get(res.field) return v is not None and _clamped(res.bw or "", r) and _at_ceiling(float(v), r) if res.field == "PeakVectorSum": # A vector sum can exceed the range without any clipping, so only # Blastware's OORANGE counts. SFM's sum is bounded by three channels at # the ceiling (11.55 on T438HGTZ.B30W), and a channel Blastware itself # clamped must be the one SFM has at the ceiling -- an unclipped channel # read 8x high on the Sensitive range does not qualify. pvs = sfm.values.get("PeakVectorSum") return ((res.bw or "").strip() == "OORANGE" and pvs is not None and r - _TOL <= float(pvs) <= 3 ** 0.5 * r * 1.01 and any(_clamped(ref.scalars.get(f, ""), r) and sfm.values.get(f) is not None and _at_ceiling(float(sfm.values[f]), r) for f in ("TranPPV", "VertPPV", "LongPPV"))) got = series_pairs(sfm, ref, res.field) if got is None or got[1]: return False if res.field == "intervals.Geo PVS in/s": # Per interval, as PeakVectorSum: an OORANGE vector sum, SFM's sum within # three channels at the ceiling, and a channel Blastware itself clamped in # that interval. 17 / 17 DL2 cells, SFM 10.01 .. 17.33 (2026-11-03). cols = ref.interval_columns or [] peaks = [cols.index(c) for c in ("Tran Peak in/s", "Vert Peak in/s", "Long Peak in/s") if c in cols] rows = ref.intervals or [] differing = [(j, cell, v) for j, cell, v in got[0] if _differs(v, cell)] return bool(differing) and all( cell.strip() == "OORANGE" and not isinstance(v, str) and r - _TOL <= v <= 3 ** 0.5 * r * 1.01 and any(_clamped(rows[j][1][p], r) for p in peaks if p < len(rows[j][1])) for j, cell, v in differing) differing = [(cell, v) for _, cell, v in got[0] if _differs(v, cell)] return bool(differing) and all( not isinstance(v, str) and _clamped(cell, r) and _at_ceiling(v, r) and (cell.strip() == "OORANGE" or (v >= 0) == (_printed_number(cell)[0] >= 0)) for cell, v in differing) SATURATION = Carveout( id="saturation", fields=("TranPPV", "VertPPV", "LongPPV", "PeakVectorSum", "samples.Tran", "samples.Vert", "samples.Long", "intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s", "intervals.Geo PVS in/s"), evidence=("Blastware clamps a clipped channel to the range maximum and prints OORANGE; " "the file holds counts past full scale (32016 counts = 10.005 in/s observed). " "scratch/verify_against_ascii.py, 2026-08-28. An interval's vector sum prints " "OORANGE when it exceeds the range in an interval with a clamped channel: 17 / 17 " "DL2 cells, 2026-11-03."), applies=_saturation, ) def _interval_count_is_duration(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool: """Blastware's count exceeds the intervals in its own table, and SFM decoded exactly the table's.""" p = _printed_number(res.bw or "") n = sfm.values.get("NumberofIntervals") rows = len(ref.intervals or []) return p is not None and n is not None and rows == n and p[0] > n INTERVAL_COUNT_IS_DURATION = Carveout( id="interval-count-is-duration", fields=("NumberofIntervals",), evidence=("Blastware's Number of Intervals is (stop - start) / interval from the file's " "footer times -- exact on T193KSWP.FF0H (2,880), M462KSWR.1R0H (1,650) and " "T193KY0A.740H (6,390). Its own interval table lists the intervals the file " "holds: one block (30 at 2 s) fewer when the unit never wrote the last minute. " "2026-11-02."), applies=_interval_count_is_duration, ) _MIC_UNITS = ("in/s and dB(L)", "in/s and psi(L)") def _units_is_a_display_preference(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool: """Both sides say the event has a mic; they differ only in dB against psi.""" return (" ".join((res.bw or "").split()) in _MIC_UNITS and sfm.values.get("Units") in _MIC_UNITS) UNITS_IS_A_DISPLAY_PREFERENCE = Carveout( id="units-is-a-display-preference", fields=("Units",), evidence=("dB(L) or psi(L) is Blastware's display preference on the PC when it wrote the " "report, not the unit's: in report-write order (the _XML.XML mtimes) DL2's 70,034 " "reports switch fleet-wide in 61 clean runs, every unit at once, and no byte or " "bit of the event file separates the two (k-240 .. k+520, nor the 1.2 KB before " "the footer). Instantel documents both settings: the unit's own Microphone " "Units (MiniMate Plus manual 716U0101 Rev 15 §3.9.7: psi(L), dB(L) or Pa(L), " "keypad Right Arrow + Setups) and Blastware's report preference (Blastware " "manual 714U0301 Rev 22 §4, Preferences > Units and Channel: Show Mic in dB / " "in Linear Units). 2026-11-03."), applies=_units_is_a_display_preference, ) def _other_mic_unit(sfm: SfmSide, units: str): """SFM's mic value in the unit the report did NOT say, as Blastware renders it.""" d = sfm.mic_divisor if "dB(L)" in units: return lambda c: c * _MIC_PSI_PER_COUNT / d if "psi(L)" in units: return lambda c: mic_count_to_db(c / d) return None def _mic_units_mixed(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool: """Every mic cell SFM disagrees with is SFM's own value in the other unit.""" counts = sfm.counts.get("MicL") or [] if res.field == "MicLPSPL": own = ref.units.get("MicLPSPL") or "" alt = _other_mic_unit(sfm, own if ("dB(L)" in own or "psi(L)" in own) else (ref.event_units or "")) peak = max((abs(c) for c in counts), default=None) return alt is not None and peak is not None and not _differs(alt(peak), res.bw or "") got = series_pairs(sfm, ref, res.field) # An interval column names its own unit; a sample table says it in its cells. units = res.field if res.field.startswith("intervals.") else _mic_table_units(ref) alt = _other_mic_unit(sfm, units) if got is None or got[1] or alt is None: return False differing = [(j, cell) for j, cell, v in got[0] if _differs(v, cell)] return bool(differing) and all(j < len(counts) and not _differs(alt(counts[j]), cell) for j, cell in differing) MIC_UNITS_MIXED = Carveout( id="mic-units-mixed", fields=("MicLPSPL", "samples.MicL", "intervals.MicL Peak psi(L)", "intervals.MicL Peak dB(L)"), evidence=("Blastware's dB(L) / psi(L) labels do not hold for the mic on every report: 7 DL2 " "reports print the mic peak in dB under a psi line, 3 the reverse, and some mix the " "two inside one column -- K441L9IN.OT0W prints psi '0.000' / '-0.000' for counts of 1 " "to 3 in a dB table, S353JTHU.DT0W psi rows then dB rows. On 19 DL2 events (14 " "sample tables, 5 peaks) every mic cell SFM disagrees with is SFM's own value in the " "other unit; a cell matching neither is still a mismatch. A histogram row can print " "one unit in both its mic columns: I145HKWT.DY0H row 672 reads 95.92 under psi(L) " "and dB(L) (count 5, dB), S353K894.OE0H rows 106 and 608 0.000 under both (count 2, " "psi). 2026-11-09."), applies=_mic_units_mixed, ) CARVEOUTS: tuple[Carveout, ...] = (SATURATION, INTERVAL_COUNT_IS_DURATION, UNITS_IS_A_DISPLAY_PREFERENCE, MIC_UNITS_MIXED)