Group A of the file-only decode, every field matched against every DL2 report (2026-11-03): - Identity block before the setup name, what the live read gets from SUB FE: serial k-202, firmware k-147, DSP version k-138, calibration date k-132 + 'by' k-128, manufacturer k-94, model k-72, firmware minor k-193. Event.device_info (DeviceInfo gains calibration_date / calibrated_by). Serial, Version and Calibration 69,983 / 69,983. - Battery: uint16 hundredths of a volt at k-190 (Event.battery_volts). 69,729 exact; the other 254 are Blastware rounding half up. - Trigger source: the two bytes between the embedded event record's lead and fe 80, a bitmask (0x01 Tran 0x02 Vert 0x04 Long 0x08 MicL 0x200 Manual): 6,493 / 6,493. Event.triggered_by. - Trigger settings in Series IV's 0x1A layout: sources bitmask k-19, stop mode k-31 (0 = Fixed), each channel's float32 level at label+30 (geo in/s, mic psi), mic type code at MicL+4 (2 = Linear Weighting). Geo level 6,447 / 6,447, mic 4,403 / 4,403; Blastware prints a level when its channel is a trigger source and the event was not Manual. The mic level's dB uses 6895 Pa/psi (4,272 / 4,272 against 4,271 at 6894.757). - .h5 attrs for all of them (additive). - Checker: SFM's side reports the ten fields; the mic trigger level follows the report's dB/psi. Carve-out units-is-a-display-preference: dB or psi is Blastware's PC setting when it wrote the report -- DL2's reports switch fleet-wide in 61 clean runs by write time, and no byte of the file separates them. Two tests that pinned BatteryLevel / Calibration as blank now pin the match. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
357 lines
16 KiB
Python
357 lines
16 KiB
Python
"""
|
|
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 math
|
|
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"}
|
|
|
|
# How Blastware prints the setup fields SFM reads (measured 2026-11-03).
|
|
_MONTHS = ("January", "February", "March", "April", "May", "June", "July",
|
|
"August", "September", "October", "November", "December")
|
|
_TRIGGERED_BY = {0x0001: "Tran", 0x0002: "Vert", 0x0004: "Long", 0x0008: "MicL", 0x0200: "Manual"}
|
|
_STOP_MODES = {0: "Fixed"}
|
|
_MIC_TYPES = {2: "Linear Weighting"}
|
|
_GEO_TRIGGERS, _MIC_TRIGGER = 0x07, 0x08
|
|
# Blastware turns the mic trigger level from psi to dB with 6895 Pa per psi, not
|
|
# 6894.757: 4,272 / 4,272 DL2 levels against 4,271 (the odd one 0.01 psi,
|
|
# printed 130.8 dB(L), is 130.7498 at the exact constant).
|
|
_TRIGGER_PA_PER_PSI = 6895.0
|
|
|
|
|
|
def _setup_values(ev: Event) -> dict[str, object]:
|
|
out: dict[str, object] = {}
|
|
di = ev.device_info
|
|
if di is not None:
|
|
out["SerialNumber"] = di.serial
|
|
fw = di.firmware_version or ""
|
|
if di.dsp_version and fw.startswith("S33") and di.model:
|
|
# "V 10.72-8.17 MiniMate Plus" from "10.72", "S338.17" and the model --
|
|
# the only version in DL2, so the rule is proven for it alone.
|
|
out["Version"] = f"V {di.dsp_version}-{fw[3:]} {di.model}"
|
|
if di.calibration_date and di.calibrated_by:
|
|
c = di.calibration_date
|
|
out["Calibration"] = f"{_MONTHS[c.month - 1]} {c.day}, {c.year} by {di.calibrated_by}"
|
|
out["BatteryLevel"] = ev.battery_volts
|
|
out["Trigger"] = _TRIGGERED_BY.get(ev.triggered_by)
|
|
out["RecordStopMode"] = _STOP_MODES.get(ev.record_stop_mode)
|
|
out["Microphone"] = _MIC_TYPES.get(ev.mic_type)
|
|
# dB or psi is Blastware's preference, not the unit's (carve-out
|
|
# units-is-a-display-preference); SFM reports dB, the default.
|
|
out["Units"] = "in/s and dB(L)" if ev.mic_type is not None else "in/s"
|
|
# Blastware prints a trigger level only for a channel that is a trigger
|
|
# source, and none for a Manual trigger.
|
|
src, manual = ev.trigger_sources or 0, ev.triggered_by == 0x0200
|
|
if src & _GEO_TRIGGERS and not manual:
|
|
out["GeoTriggerLevel"] = ev.trigger_level_geo
|
|
if src & _MIC_TRIGGER and not manual and ev.trigger_level_mic_psi:
|
|
psi = ev.trigger_level_mic_psi
|
|
out["MicTriggerLevel psi(L)"] = psi
|
|
out["MicTriggerLevel dB(L)"] = 20 * math.log10(psi * _TRIGGER_PA_PER_PSI / 2e-5)
|
|
return out
|
|
|
|
|
|
@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] # only when the file says Blastware shows 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
|
|
values.update(_setup_values(ev))
|
|
|
|
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=str(pi.job_number) if pi is not None and pi.job_number_enabled else 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 in ("MicLPSPL", "MicTriggerLevel"):
|
|
units = ref.event_units or ""
|
|
key = (f"{tag} dB(L)" if "dB(L)" in units else
|
|
f"{tag} 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.<ch>` or `intervals.<column>` 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))
|
|
elif sfm.job_number is not None:
|
|
# SFM says the job number is shown; Blastware printed none.
|
|
out.append(FieldResult("JobNumber", "mismatch", None, 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
|