Release v0.33.0 — SFM reads Series-3 events from the file alone #56
No files matched your search
@@ -13,10 +13,12 @@ Pure: no I/O, and no import from `sfm/`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
from typing import Callable, Optional, Sequence
|
||||
|
||||
from .event_file_io import _GEO_INT16_FS, _GEO_NORMAL_FS_INS, decode_blastware_bytes
|
||||
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
|
||||
|
||||
@@ -77,3 +79,209 @@ def sfm_side(raw: bytes) -> SfmSide:
|
||||
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
|
||||
@@ -42,3 +42,61 @@ def test_report_fields_stay_blank():
|
||||
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
|
||||
for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"):
|
||||
assert s.values.get(tag) is None
|
||||
|
||||
|
||||
# ── Task 3: the comparison ──────────────────────────────────────────────────
|
||||
|
||||
from minimateplus.bw_xml_report import parse_xml_report_file # noqa: E402
|
||||
from minimateplus.decode_check import compare, matches_printed # noqa: E402
|
||||
|
||||
|
||||
def _results(stem, carveouts=()):
|
||||
raw = (FIX / stem).read_bytes()
|
||||
ref = parse_xml_report_file(FIX / (stem.replace(".", "_") + "_XML.XML"))
|
||||
return {r.field: r for r in compare(sfm_side(raw), ref, carveouts)}
|
||||
|
||||
|
||||
def test_matches_printed_rounds_half_away():
|
||||
assert matches_printed(-0.0625, "-0.063") and matches_printed(0.0015, "0.002")
|
||||
assert not matches_printed(0.0026, "0.002")
|
||||
|
||||
|
||||
def test_full_waveform_row_verdicts():
|
||||
res = _results("R352HIUI.F40W")
|
||||
for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime",
|
||||
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
|
||||
assert res["BatteryLevel"].verdict == "sfm_blank"
|
||||
assert "FileName" not in res
|
||||
|
||||
|
||||
def test_ragged_rows_match_by_running_channels():
|
||||
# Tran/Vert/MicL end 3 samples before Long, in SFM and in Blastware's table alike
|
||||
res = _results("T438HGTZ.B30W")
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
assert res[f"samples.{ch}"].verdict == "match", res[f"samples.{ch}"]
|
||||
|
||||
|
||||
def test_an_extra_reference_row_is_a_mismatch_with_detail():
|
||||
raw = (FIX / "T1905KDW.5F0W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
ref.sample_rows.append(["0.000", "0.000", "0.000", "0.000"])
|
||||
res = {r.field: r for r in compare(sfm_side(raw), ref)}
|
||||
assert res["samples.Tran"].verdict == "mismatch"
|
||||
assert "row_length_disagreements=1" in res["samples.Tran"].detail
|
||||
|
||||
|
||||
def test_job_number_na_and_above_range():
|
||||
res = _results("T1905KDW.5F0W")
|
||||
assert res["JobNumber"].verdict == "sfm_blank"
|
||||
assert res["TranZCFreq"].verdict == "no_reference" # N/A
|
||||
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
|
||||
|
||||
|
||||
def test_mic_units_pick_the_conversion():
|
||||
res = _results("T004JTRF.ME0H") # psi(L)
|
||||
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
|
||||
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)
|
||||
Reference in new issue
Block a user