diff --git a/minimateplus/decode_check.py b/minimateplus/decode_check.py index bba2cde..bcfc2c0 100644 --- a/minimateplus/decode_check.py +++ b/minimateplus/decode_check.py @@ -184,71 +184,86 @@ def _series_result(field: str, n_bw: int, n_sfm: int, diffs: list[tuple[int, flo ) -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 [] +def _sample_converters(ref: XmlReport) -> dict[str, Callable[[int], float]]: + convert: dict[str, Callable[[int], float]] = {ch: (lambda c: c * GEO_IPS_PER_COUNT) for ch in _GEO} 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 + return convert + + +def _interval_converter(title: str) -> 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 * 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_FS_PSI + 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(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) + 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. 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 + """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]: diff --git a/minimateplus/decode_check_carveouts.py b/minimateplus/decode_check_carveouts.py new file mode 100644 index 0000000..9cb0c80 --- /dev/null +++ b/minimateplus/decode_check_carveouts.py @@ -0,0 +1,83 @@ +""" +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, _printed_number, series_pairs, matches_printed + + +@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 _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 (11.55 on T438HGTZ.B30W); it is the + # clipped channel under it that must sit at the ceiling. + return (_clamped(res.bw or "", r) and + any(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 + differing = [(cell, v) for _, cell, v in got[0] if not matches_printed(v, cell)] + return bool(differing) and all( + _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"), + 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."), + applies=_saturation, +) + +CARVEOUTS: tuple[Carveout, ...] = (SATURATION,) diff --git a/tests/test_decode_check.py b/tests/test_decode_check.py index 3d99498..c33d823 100644 --- a/tests/test_decode_check.py +++ b/tests/test_decode_check.py @@ -100,3 +100,26 @@ def test_mic_units_pick_the_conversion(): assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank" fields = set(_results("R352HFZ7.530H")) # no mic assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields) + + +# ── Task 4: carve-outs ────────────────────────────────────────────────────── + +from minimateplus.decode_check_carveouts import CARVEOUTS # noqa: E402 + + +def test_clipped_normal_range_is_accepted(): + # Blastware: Tran 5.445, Vert 6.310, Long OORANGE, PVS OORANGE; SFM Long 10.005, PVS 11.55 + res = _results("T438HGTZ.B30W", CARVEOUTS) + assert res["TranPPV"].verdict == "match" and res["VertPPV"].verdict == "match" + for f in ("LongPPV", "PeakVectorSum"): + assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation") + + +def test_sensitive_range_8x_stays_a_mismatch(): + res = _results("M007HVWF.K30W", CARVEOUTS) + assert res["TranPPV"].verdict == "mismatch" and res["samples.Tran"].verdict == "mismatch" + assert res["PeakVectorSum"].verdict == "mismatch" + + +def test_every_carveout_has_evidence(): + assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS)