Files
seismo-relay/minimateplus/decode_check.py
T
serversdownandClaude Opus 5.5 9091fe75a9 feat(decode): ZC frequency, peak displacement and times of peak from the unit's own event summary
After its embedded event record, every Blastware event file carries the
unit's own per-channel summary: a chain of [length][id][payload] records,
ids 0x32 Tran .. 0x35 MicL, each with min, max, peak sample,
half-period and a displacement integral; the event record itself holds
the vector-sum peak's sample.  Blastware prints these as they are
(measured on DL2, 2026-11-05):

- ZC frequency = (rate / 2) / half-period: 15,844 / 15,844 waveform and
  104,000 / 104,000 histogram values; every word too (">100" at <= 5
  samples, "N/A" at 0, "<1.0" beyond rate / 2).  Recomputing from the
  samples had reached 46%: the unit works at full resolution.
- peak displacement = half the integral x 16 counts x in/s per count /
  rate: 19,479 / 19,479 (84% recomputed).
- times of peak and the vector-sum time now come from the unit's peak
  samples.  They equal the samples' argmax on 25,962 / 25,966 channels;
  the 4 others are O117I1NK.R70W, whose stored samples wrap at the
  trigger (Blastware's own sample table has the same wrapped values).

The event-record readers return the validated record's offset, so the
summary is read from that spot only.  No summary: nothing is set, and
times of peak stay the samples'.

The checker reports ZC frequency and displacement, and reads the mic's
above-range flag under its real name (mic_zc_above_range).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-05 14:00:13 -05:00

448 lines
21 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 datetime
import math
import re
from dataclasses import dataclass, field
from typing import Callable, Optional, Sequence
from .bw_xml_report import XmlReport
from .event_file_io import (interval_times, _GEO_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT,
decode_blastware_bytes)
from .histogram_codec import half_period_to_hz
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
# interval column -> SFM's value per interval (a number, or Blastware's word)
interval_values: dict[str, list[object]] = field(default_factory=dict)
interval_times: Optional[list[str]] = None # each interval's printed time
def interval_frequency(halfp: int, sample_rate: int) -> object:
"""An interval's frequency as Blastware prints it: "N/A" for a half-period
of 0, ">100" (">200" at 2048 sps) at 5 samples or fewer, "<1.0" below 1 Hz,
else (sample rate / 2) / half-period in Hz. Measured on ~3.1 M DL2 cells,
2026-11-03 (#50: the rate, not a fixed 512)."""
if halfp == 0:
return "N/A"
hz = half_period_to_hz(halfp, sample_rate)
if hz is None:
return f">{round(100 * sample_rate / 1024)}"
return "<1.0" if hz < 1.0 else hz
def _interval_size(seconds: int) -> str:
n, unit = (seconds // 60, "minute") if seconds % 60 == 0 else (seconds, "second")
return f"{n} {unit}{'' if n == 1 else 's'}"
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)
# A waveform's peak detail (None on a histogram, so not reported).
for tag, value in (("TranTimeofPeak", pv.tran_time_of_peak),
("VertTimeofPeak", pv.vert_time_of_peak),
("LongTimeofPeak", pv.long_time_of_peak),
("MicLTimeofPeak", pv.micl_time_of_peak),
("PeakVectorSumTimeSum", pv.pvs_time),
("TranPeakAcceleration", pv.tran_peak_accel_g),
("VertPeakAcceleration", pv.vert_peak_accel_g),
("LongPeakAcceleration", pv.long_peak_accel_g),
("TranPeakDisplacement", pv.tran_peak_disp_in),
("VertPeakDisplacement", pv.vert_peak_disp_in),
("LongPeakDisplacement", pv.long_peak_disp_in)):
if value is not None:
values[tag] = value
# The unit's ZC frequency, every record type. Above range it is judged
# by its flag (_compare_scalar); below 1 Hz Blastware prints a word.
for tag, hz in (("TranZCFreq", pv.tran_zc_freq), ("VertZCFreq", pv.vert_zc_freq),
("LongZCFreq", pv.long_zc_freq), ("MicLZCFreq", pv.mic_zc_freq)):
if hz is not None:
values[tag] = "<1.0" if hz < 1.0 else hz
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))
if ev.stop_time is not None:
values.update(HistogramStopDate=ev.stop_time.strftime("%Y-%m-%d"),
HistogramStopTime=ev.stop_time.strftime("%H:%M:%S"))
if ev.histogram_interval_sec:
values["IntervalSize"] = _interval_size(ev.histogram_interval_sec)
interval_values: dict[str, list[object]] = {}
if ev.interval_half_periods and ev.sample_rate:
for ch, hps in ev.interval_half_periods.items():
interval_values[f"{ch} Freq Hz"] = [interval_frequency(h, ev.sample_rate) for h in hps]
if ev.interval_pvs:
interval_values["Geo PVS in/s"] = list(ev.interval_pvs)
times = None
n = len(counts["Tran"])
if ev.record_type == "Histogram" and ts is not None and ev.histogram_interval_sec and n:
start = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
ends = interval_times(start, ev.histogram_interval_sec, ev.stop_time, n)
times = [t.strftime("%Y-%m-%d %H:%M:%S") for t in ends]
# A peak's date and time are those of the interval holding it (first).
for tag, series in (("TranPeak", counts["Tran"]), ("VertPeak", counts["Vert"]),
("LongPeak", counts["Long"]), ("MicL", counts["MicL"]),
("PeakVectorSum", ev.interval_pvs)):
if series and len(series) == n:
j = max(range(n), key=lambda q: abs(series[q]))
values[f"{tag}Date"] = ends[j].strftime("%Y-%m-%d")
values[f"{tag}Time"] = ends[j].strftime("%H:%M:%S")
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,
interval_values=interval_values,
interval_times=times,
)
# ── 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"):
# A printed value that states its unit is compared in that unit:
# K441LA17.IN0W's Units say psi(L), its MicTriggerLevel "125.0 dB(L)".
units = printed if ("dB(L)" in printed or "psi(L)" in printed) else (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.
ch = tag[:-len("ZCFreq")].lower()
flag = getattr(sfm.event.peak_values, ("mic" if ch == "micl" else ch) + "_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: object, printed: str) -> Optional[float]:
"""|value - printed| when the cell disagrees, else None; inf for a cell that
is not a number. A word on SFM's side (">100", "N/A") must be printed."""
if isinstance(value, str):
return None if _same_text(value, printed) else float("inf")
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 []
if title not in columns:
return None
i = columns.index(title)
cells = [row[i] if i < len(row) else "" for _, row in (ref.intervals or [])]
values = sfm.interval_values.get(title)
if values is None:
convert = _interval_converter(title, sfm)
counts = sfm.counts.get(title.partition(" ")[0], [])
if convert is None or not counts:
return None
values = [convert(c) for c in counts]
pairs = [(j, cell, v) for j, (cell, v) in enumerate(zip(cells, values))]
return pairs, abs(len(cells) - len(values))
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]
title = field.split(".", 1)[1]
n_sfm = (len(sfm.interval_values[title]) if title in sfm.interval_values
else len(sfm.counts.get(title.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."""
n = len(ref.intervals or [])
return ([_compare_interval_times(sfm, ref, n)]
+ [_compare_series(f"intervals.{t}", n, sfm, ref) for t in ref.interval_columns or []])
def _compare_interval_times(sfm: SfmSide, ref: XmlReport, n: int) -> FieldResult:
if sfm.interval_times is None:
return FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)
diffs = [(j, float("inf")) for j, ((t, _), s) in enumerate(zip(ref.intervals or [], sfm.interval_times))
if not _same_text(s, t)]
return _series_result("intervals.Time", n, len(sfm.interval_times), diffs,
abs(n - len(sfm.interval_times)))
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