merge: dev into feat/series4-sfm-parity -- v0.32.0, #42, #47/#49, #44/#45, the S3 decode checker

Brings the branch up to dev (41 commits) before the 1c bench fixes, which
touch code dev changed: the histogram reader (#47/#49, bench finding #2), the
v0.32.0 event-time rules, the Blastware file's setup-block fields (#44/#45),
and the decode checker for verifying stored S3 downloads.

One conflict: the top of the Series-III reference's change table -- both sides
added rows; kept all, in date order, CRLF preserved.  CLAUDE.md, README,
blastware_file.py, models.py and database.py merged cleanly.  Suite: the known
16 failures only (15 test_bw_ascii_report, test_save_imported_bw_without_report_
works_unchanged, which also fails on dev); 1237 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-29 22:51:42 -04:00
commit 342c69602d
54 files changed
+22279 -264

No files matched your search

+26
View File
@@ -152,6 +152,7 @@ from __future__ import annotations
import datetime
import logging
import re
import struct
from pathlib import Path
from typing import Optional, Union
@@ -416,6 +417,31 @@ def _make_stem(ts_local: datetime.datetime) -> str:
return s
_BW_NAME = re.compile(r"^[B-Z]\d{3}([0-9A-Z]{4})\.([0-9A-Z]{2})0[WH]?$")
def blastware_filename_time(name: str) -> Optional[datetime.datetime]:
"""The event time a Blastware filename encodes, or None for any other name.
The inverse of `blastware_filename`: `<prefix><serial3><stem 4>.<AB>0[W|H]`,
time = 1985-01-01 + stem*1296 + AB seconds. This is Blastware's own time
to the second -- it equals the report's Event Time on 1,330/1,330
report-paired waveforms (81 prod-store, 1,249 DL2) and the report's
Histogram Start Time on 13,089/13,089 histograms (measured 2026-10-26).
Only the V10.72 `AB0` form is decoded; anything else gives None.
"""
m = _BW_NAME.match((name or "").upper())
if not m:
return None
stem = 0
for c in m.group(1):
stem = stem * 36 + _STEM_CHARS.index(c)
ab = _STEM_CHARS.index(m.group(2)[0]) * 36 + _STEM_CHARS.index(m.group(2)[1])
if ab >= _STEM_UNIT_SEC:
return None
return _INSTANTEL_EPOCH + datetime.timedelta(seconds=stem * _STEM_UNIT_SEC + ab)
def blastware_filename(event: Event, serial: str, ach: bool = False) -> str:
"""
Return the correct Blastware filename for an event.
+10 -3
View File
@@ -280,8 +280,15 @@ _MONTHS = {
def _parse_event_date(s: str) -> Optional[datetime.date]:
"""Parse "April 23, 2026" or "May 8, 2026" → date."""
"""Parse "April 23, 2026", "May 8, 2026" or "2026-08-14" → date.
Blastware writes whichever the PC's settings say: every one of the 81
report-paired waveforms in prod's store (2026-09-30 snapshot) is ISO, and
reading only the long form left their event time unread."""
s = s.strip()
iso = _parse_iso_date(s)
if iso is not None:
return iso
parts = s.replace(",", " ").split()
if len(parts) < 3:
return None
@@ -297,8 +304,8 @@ def _parse_event_date(s: str) -> Optional[datetime.date]:
def _parse_iso_date(s: str) -> Optional[datetime.date]:
"""Parse "2026-05-16" → date. Histograms use ISO format for their
Start Date / Stop Date / Peak Date fields; waveforms use the
"May 8, 2026" long form which `_parse_event_date` handles."""
Start Date / Stop Date / Peak Date fields; a waveform's Event Date may be
either form (see `_parse_event_date`)."""
s = s.strip()
try:
return datetime.date.fromisoformat(s)
+133
View File
@@ -0,0 +1,133 @@
"""
minimateplus/bw_xml_report.py — parse Blastware's `_XML.XML` event report.
Blastware's ACH keeps, in `Sent/`, a full XML report beside each event binary:
`<stem>_<ext>_XML.XML` for `<stem>.<ext>`. It carries every field of the event
report plus every waveform sample or histogram interval, and DL2's backup holds
one for 70,042 Series 3 events back to 2016 (its ASCII reports start in 2025).
SFM uses it only to check its own decode, never as data.
The small `<stem>_<ext>.XML` summary beside it writes decimal commas and is not
this file.
Layout (FileVersion 8.0), as the parser reads it:
- top-level simple elements, e.g. ``<SampleRate>1024 sps</SampleRate>``
- value elements, e.g. ``<TranPPV><Value>0.015</Value><Units>in/s</Units></TranPPV>``
- ``<Channels><Channel>Tran</Channel>...</Channels>``
- the job number and up to four user notes, between the top-level
``<Units>`` and ``<GeoRange>``; each note is tagged with its
operator-editable label (``Project``, ``Location``, ``Seis.Loc`` ...) and
an empty note is omitted
- waveform: ``WaveformDataChannels/Data/Row/Cell``. A row holds only the
channels still running: where channels end at different lengths, the last
rows have fewer cells
- histogram: ``HistogramData`` with ``HistogramDataColumnTitle/ColumnTitle``
and ``HistogramDataIntervals``, alternating ``Time`` and ``Row``
Cell and value text is kept exactly as printed (``">100"``, ``"N/A"``,
``"OORANGE"``, ``"6.7 Volts"``); interpreting it is the comparison's job.
Pure: no I/O beyond reading the file passed to `parse_xml_report_file`.
"""
from __future__ import annotations
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Union
@dataclass
class XmlReport:
scalars: dict[str, str]
units: dict[str, str]
event_units: Optional[str]
channels: list[str]
job_number: Optional[str]
notes: list[tuple[str, str]]
sample_rows: Optional[list[list[str]]]
interval_columns: Optional[list[str]]
intervals: Optional[list[tuple[str, list[str]]]]
def _text(el: ET.Element) -> str:
return (el.text or "").strip()
def _cells(row: ET.Element) -> list[str]:
return [_text(c) for c in row.findall("Cell")]
def parse_xml_report(data: bytes) -> XmlReport:
"""Parse the bytes of an `_XML.XML` event report. Raises ValueError when
they are not well-formed XML (a truncated file, for one)."""
try:
root = ET.fromstring(data)
except ET.ParseError as exc:
raise ValueError(f"not a well-formed XML report: {exc}") from exc
scalars: dict[str, str] = {}
units: dict[str, str] = {}
event_units: Optional[str] = None
channels: list[str] = []
job_number: Optional[str] = None
notes: list[tuple[str, str]] = []
sample_rows: Optional[list[list[str]]] = None
interval_columns: Optional[list[str]] = None
intervals: Optional[list[tuple[str, list[str]]]] = None
in_notes = False
for el in root:
tag = el.tag
if tag == "Units" and len(el) == 0:
event_units = _text(el)
scalars[tag] = event_units
in_notes = True
continue
if tag == "GeoRange":
in_notes = False
if in_notes and len(el) == 0:
# Job number and user notes: never scalars, so the comparison
# scores each once.
if tag == "JobNumber":
job_number = _text(el)
elif _text(el):
notes.append((tag, _text(el)))
continue
if tag == "Channels":
channels = [_text(c) for c in el.findall("Channel")]
elif tag == "WaveformDataChannels":
data_el = el.find("Data")
if data_el is not None:
sample_rows = [_cells(r) for r in data_el.findall("Row")]
elif tag == "HistogramData":
titles = el.find("HistogramDataColumnTitle")
interval_columns = ([" ".join(_text(t).split()) for t in titles.findall("ColumnTitle")]
if titles is not None else [])
body = el.find("HistogramDataIntervals")
intervals = []
time: Optional[str] = None
for child in (body if body is not None else []):
if child.tag == "Time":
time = _text(child)
elif child.tag == "Row":
intervals.append((time or "", _cells(child)))
time = None
elif el.find("Value") is not None:
scalars[tag] = _text(el.find("Value"))
u = el.find("Units")
if u is not None:
units[tag] = _text(u)
elif len(el) == 0:
scalars[tag] = _text(el)
return XmlReport(
scalars=scalars, units=units, event_units=event_units, channels=channels,
job_number=job_number, notes=notes, sample_rows=sample_rows,
interval_columns=interval_columns, intervals=intervals,
)
def parse_xml_report_file(path: Union[str, Path]) -> XmlReport:
return parse_xml_report(Path(path).read_bytes())
+302
View File
@@ -0,0 +1,302 @@
"""
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 re
from dataclasses import dataclass
from typing import Callable, Optional, Sequence
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
# SFM's conversion: it cannot yet read the geophone range from the file, and
# assumes Normal (10 in/s full scale = 32000 counts).
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"}
@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] # None until the decoder reads 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
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,
}
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
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=None,
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 _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)
if mic is not None:
convert["MicL"] = mic
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.<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(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, 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))
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
+89
View File
@@ -0,0 +1,89 @@
"""
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 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
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,)
+259 -69
View File
@@ -20,6 +20,7 @@ import hashlib
import json
import logging
import os
import re
import struct
from pathlib import Path
from typing import Optional, Union
@@ -50,7 +51,7 @@ SIDECAR_KIND = "sfm.event"
# bumped without a `pip install` re-run — leading to confusing stale
# version stamps in sidecars. Bump this constant and CHANGELOG.md
# together at release time.
TOOL_VERSION = "0.31.0" # +/sensor_check group (schema v2); gates the backfill regen
TOOL_VERSION = "0.32.0" # waveform times from the event record, report dates, histogram reader; gates the backfill regen
try:
# Best-effort: prefer the installed metadata when it's NEWER than the
@@ -157,6 +158,9 @@ def _bw_report_to_dict(report: BwAsciiReport) -> dict:
"available": True,
"event_type": report.event_type,
"version": report.version,
# Blastware's exact trigger, so a backfill can re-apply it
# (apply_bw_report_dict_to_event); absent from sidecars before 0.32.0.
"event_datetime": report.event_datetime.isoformat() if report.event_datetime else None,
"trigger": {
"channel": report.trigger_channel,
"geo_level_ips": report.geo_trigger_level_ips,
@@ -296,16 +300,29 @@ def apply_report_to_event(event: Event, report: BwAsciiReport) -> None:
event.sample_rate = report.sample_rate_sps
if report.record_time_s is not None:
event.rectime_seconds = report.record_time_s
# The report's event_datetime is Blastware's exact trigger time (parsed
# from Event Time + Event Date). Prefer it over the binary footer's stop
# time so a report-paired import matches BW to the second.
edt = report.event_datetime
if edt is not None:
event.timestamp = Timestamp(
raw=b"", flag=0x10,
year=edt.year, unknown_byte=0, month=edt.month, day=edt.day,
hour=edt.hour, minute=edt.minute, second=edt.second,
)
# The report's event_datetime is Blastware's copy of the unit's trigger time
# (Event Time + Event Date) -- see _apply_report_time.
if report.event_datetime is not None:
_apply_report_time(event, report.event_datetime)
def _apply_report_time(event: Event, edt: datetime.datetime) -> None:
"""A paired report's time fills in only when the instrument's own event
record gave none. Against a validated record it is a cross-check: a
disagreement is logged and the record kept. (They agree on 1,320/1,320.)"""
if event.timestamp_source == "event_record" and event.timestamp is not None:
ts = event.timestamp
cur = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
if cur != edt.replace(microsecond=0):
log.warning("event record says %s, its paired report %s; the event record "
"is kept", cur, edt)
return
event.timestamp = Timestamp(
raw=b"", flag=0x10,
year=edt.year, unknown_byte=0, month=edt.month, day=edt.day,
hour=edt.hour, minute=edt.minute, second=edt.second,
)
event.timestamp_source = "report"
def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
@@ -371,6 +388,16 @@ def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
rt = rec.get("record_time_s")
if rt is not None:
event.rectime_seconds = rt
# As apply_report_to_event: the report's time fills in only without a
# validated event record (_apply_report_time).
edt = bw_report.get("event_datetime")
if edt:
try:
t = datetime.datetime.fromisoformat(edt)
except (TypeError, ValueError):
t = None
if t is not None:
_apply_report_time(event, t)
def _project_info_to_dict(pi: Optional[ProjectInfo]) -> dict:
@@ -427,9 +454,8 @@ def event_to_sidecar_dict(
supplies a non-empty value (the report mirrors the device's
compliance config, which is what BW shows in its event report).
- ``event.timestamp`` is overlaid from the report's Event Date +
Event Time (BW's report timestamps are second-resolution and
match the binary's footer; we prefer the report value because
the BW-binary footer timestamp can drift on some firmware).
Event Time -- unless it came from the instrument's own embedded event
record, which the report only cross-checks (see _apply_report_time).
"""
if source_kind not in {"sfm-live", "sfm-ach", "bw-import", "idf-import"}:
raise ValueError(f"unknown source_kind: {source_kind!r}")
@@ -438,7 +464,7 @@ def event_to_sidecar_dict(
# ── Overlay event fields from the report when present ───────────────────
timestamp_iso = _ts_iso(event.timestamp)
if bw_report and bw_report.event_datetime:
if bw_report and bw_report.event_datetime and event.timestamp_source != "event_record":
timestamp_iso = bw_report.event_datetime.isoformat()
# Build peak_values, optionally overlaid from the report. The report
@@ -468,6 +494,7 @@ def event_to_sidecar_dict(
event_block = {
"serial": serial,
"timestamp": timestamp_iso,
"timestamp_source": event.timestamp_source,
"waveform_key": event._waveform_key.hex() if event._waveform_key else None,
"record_type": event.record_type,
"sample_rate": event.sample_rate,
@@ -475,6 +502,8 @@ def event_to_sidecar_dict(
"total_samples": event.total_samples,
"pretrig_samples": event.pretrig_samples,
}
if event.decode_problems:
event_block["decode_problems"] = list(event.decode_problems)
if bw_report:
# Report values are authoritative — they're the user-configured
# values BW reads back, not STRT-derived guesses. In particular
@@ -684,35 +713,16 @@ _MIC_FS_PSI = 0.0125 / _INT16_FS # ~0.5 psi full-scale assumption
def _decode_strt(strt: bytes) -> dict:
"""
Decode the 21-byte STRT record from a BW file.
Decode the 21-byte STRT record from a BW file: the waveform key (4B).
Returns dict with waveform_key (4B), total_samples, pretrig_samples,
rectime_seconds. Falls back to None on truncated/missing fields.
The record holds no setup fields. It was once read as total samples
([8:10]), pre-trigger samples ([16:18]) and record time ([18]), but [18] is
the record-type marker (0x46 waveform, 0x0A histogram) and the others
matched nothing (#44/#45); those come from the recording-setup block.
"""
if len(strt) < 21 or strt[0:4] != b"STRT":
return {}
return {
"waveform_key": strt[6:10].hex(),
"total_samples": struct.unpack_from(">H", strt, 8)[0],
"pretrig_samples": struct.unpack_from(">H", strt, 16)[0],
"rectime_seconds": strt[18],
}
def _find_first_string(buf: bytes, label: bytes, max_len: int = 256) -> Optional[str]:
"""
Search `buf` for `label` (e.g. b"Project:") and return the
null-terminated ASCII string that follows, stripped.
"""
pos = buf.find(label)
if pos < 0:
return None
start = pos + len(label)
end = buf.find(b"\x00", start, start + max_len)
if end < 0:
end = start + max_len
text = buf[start:end].decode("ascii", errors="replace").strip()
return text or None
return {"waveform_key": strt[6:10].hex()}
def _decode_samples_4ch_int16_le(stream: bytes) -> dict[str, list[int]]:
@@ -822,11 +832,90 @@ def derive_record_type_from_filename(filename, default: str = "Waveform") -> str
# float32 within it. The configured post-trigger record time (seconds) is a
# big-endian float32 exactly 30 bytes before the "Standard Recording Setup"
# label. Verified across the corpus reading 1.0 / 2.0 / 3.0 s on different
# setups — and ts2 - record_time reproduces Blastware's trigger to the second
# (N844LQHB: stop 10:33:32 - 3.0 = 10:33:29).
# setups. ⚠ ts2 - record_time is only an estimate of the trigger: a second off
# on ~19% of files (measured 2026-10-26); the event record below is exact.
_RECSETUP_MARKER = b"Standard Recording Setup"
_RECTIME_OFFSET_BEFORE_MARKER = 30
# The recording-setup block, found by its structure rather than by name
# (#44/#45). It ends in the setup's name -- whatever the operator saved it as
# ("Standard Recording Setup", "BE16352.set", ...), NUL-terminated, right after
# the bytes 1c 08 -- and the four user notes follow the name as label/value
# string pairs. 37% of the DL2 archive's files name the setup something other
# than "Standard Recording Setup", which _RECSETUP_MARKER cannot see; the 1c 08
# form matches exactly once in every one of its 70,041 files (measured
# 2026-10-29). Offsets are from the first byte of the name.
_SETUP_NAME_RE = re.compile(rb"\x1c\x08([\x20-\x7e]{1,40})\x00")
_SAMPLE_RATE_BEFORE_NAME = 42 # uint16 BE, samples per second
_PRETRIG_BEFORE_NAME = 36 # float32 BE, seconds, negative (-0.25, -0.0625 ...)
_RECTIME_BEFORE_NAME = 30 # float32 BE, seconds (the marker's offset above)
_SAMPLE_RATES = (1024, 2048, 4096)
_NOTE_SLOTS = 4 # project, client, operator, sensor location
# The instrument's own event record, which the unit sends in its 5A stream and
# Blastware therefore copies into every waveform file (measured 2026-10-26; see
# the Series-III reference, "The embedded event record"):
#
# [-6:-2] 00 28 05 00 [0:2] fe 80 [2:10] trigger [10:18] stop
#
# each time `dd mm yyyy(BE) 00 hh mm ss`. On 7,935 waveforms exactly one
# candidate passes every check below, and its trigger equals Blastware's report
# (1,320/1,320), its filename (7,935/7,935) and the unit's own 0C record.
_EVENT_RECORD_LEAD = b"\x00\x28\x05\x00"
_EVENT_RECORD_MARKER = b"\xfe\x80"
# (stop - trigger) - record time, seconds. Measured -3 .. +6 on 7,935 files.
_EVENT_RECORD_SLACK_S = (-5.0, 10.0)
def _ts8(b: bytes) -> Optional[datetime.datetime]:
"""`dd mm yyyy(BE) 00 hh mm ss`, strictly: the zero byte must be zero."""
if len(b) < 8 or b[4] != 0:
return None
try:
return datetime.datetime((b[2] << 8) | b[3], b[1], b[0], b[5], b[6], b[7])
except ValueError:
return None
def _embedded_event_record(
raw: bytes, end: int, start: Optional[datetime.datetime],
stop: Optional[datetime.datetime], record_time: Optional[float],
) -> tuple[Optional[datetime.datetime], str]:
"""The trigger time from the instrument's embedded event record, or (None, why).
Every `fe 80` before `end` (the footer) is a candidate. One counts only if
its lead bytes match, both its times are well formed, the footer's session
start <= trigger <= its stop, its stop is the footer's stop or a second
before it, and its length agrees with the record time. Exactly one may
pass: none, or more than one, is reported rather than guessed between.
"""
if start is None or stop is None:
return None, "the footer has no start and stop to check one against"
found, rejected = [], 0
i = raw.find(_EVENT_RECORD_MARKER, 6)
while 0 <= i and i + 18 <= end:
trig, rec_stop = _ts8(raw[i + 2:i + 10]), _ts8(raw[i + 10:i + 18])
valid = (
raw[i - 6:i - 2] == _EVENT_RECORD_LEAD
and trig is not None and rec_stop is not None
and start <= trig <= rec_stop
and 0 <= (stop - rec_stop).total_seconds() <= 1
and (record_time is None
or _EVENT_RECORD_SLACK_S[0]
<= (rec_stop - trig).total_seconds() - record_time
<= _EVENT_RECORD_SLACK_S[1])
)
if valid:
found.append(trig)
else:
rejected += 1
i = raw.find(_EVENT_RECORD_MARKER, i + 1)
if len(found) == 1:
return found[0], ""
if found:
return None, f"{len(found)} candidates validate"
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate")
def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
"""The configured post-trigger record time in seconds, from the recording-
@@ -842,15 +931,85 @@ def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
return rt if 0.05 <= rt <= 600.0 else None
def read_blastware_file(path: Union[str, Path]) -> Event:
def _setup_name_at(raw: bytes) -> Optional[int]:
"""Offset of the recording setup's name, or None unless exactly one
candidate is found -- two would mean the anchor is not what it seems."""
found = [m.start(1) for m in _SETUP_NAME_RE.finditer(raw)]
return found[0] if len(found) == 1 else None
def _setup_sample_rate(raw: bytes) -> Optional[int]:
"""The configured sample rate (samples/s) from the recording-setup block."""
k = _setup_name_at(raw)
if k is None or k < _SAMPLE_RATE_BEFORE_NAME:
return None
sr = struct.unpack_from(">H", raw, k - _SAMPLE_RATE_BEFORE_NAME)[0]
return sr if sr in _SAMPLE_RATES else None
def _setup_record_time(raw: bytes) -> Optional[float]:
"""The configured post-trigger record time (s) from the recording-setup
block. A histogram's block carries a stale value here: callers use it
for waveforms only."""
k = _setup_name_at(raw)
if k is None or k < _RECTIME_BEFORE_NAME:
return None
rt = struct.unpack_from(">f", raw, k - _RECTIME_BEFORE_NAME)[0]
return rt if 0.05 <= rt <= 600.0 else None
def _setup_pretrigger(raw: bytes) -> Optional[float]:
"""The pre-trigger (s, negative) from the recording-setup block -- the
value Blastware prints, -0.247 s as well as -0.25 s (6,453 of 6,453 DL2
waveforms, measured 2026-10-29). A histogram's block holds 0.0."""
k = _setup_name_at(raw)
if k is None or k < _PRETRIG_BEFORE_NAME:
return None
pre = struct.unpack_from(">f", raw, k - _PRETRIG_BEFORE_NAME)[0]
return pre if -2.0 <= pre <= 0.0 else None
def _setup_notes(raw: bytes) -> ProjectInfo:
"""The setup name and the four user notes. Blastware lets the operator
relabel the note slots ("Seis. Loc:", "Location:", "Project: " ...), so the
labels are not searched for: slot n is the nth label/value pair after the
name, as in bw_ascii_report. An empty value is None."""
k = _setup_name_at(raw)
if k is None:
return ProjectInfo()
parts = raw[k:].split(b"\x00", 1 + 2 * _NOTE_SLOTS)
text = [p.decode("ascii", errors="replace").strip() or None for p in parts]
text += [None] * (2 + 2 * _NOTE_SLOTS - len(text))
project, client, operator, location = text[2:2 + 2 * _NOTE_SLOTS:2]
return ProjectInfo(setup_name=text[0], project=project, client=client,
operator=operator, sensor_location=location)
def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event:
"""Parse a Blastware event file into an Event: `decode_blastware_bytes` on its
bytes, `name` defaulting to the file's own (see there -- never a time source)."""
path = Path(path)
return decode_blastware_bytes(path.read_bytes(), name=name or path.name)
def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
"""
Parse a Blastware waveform file into an Event.
Parse a Blastware event's bytes into an Event. No filename is needed.
`name`, when given, labels the record type and is compared with the decoded
time -- a disagreement is logged -- but never supplies it: an event SFM
receives straight from a unit has no Blastware name.
Recovers:
- waveform_key, rectime_seconds, total_samples, pretrig_samples
(from the STRT record)
- timestamp (from the footer's start-time field)
- project_info (from ASCII labels embedded in the body)
- waveform_key (from the STRT record)
- sample_rate; for a waveform also rectime_seconds, total_samples and
pretrig_samples (from the recording-setup block and the decoded
sample count)
- timestamp: a waveform's from the instrument's embedded event record
(`timestamp_source` "event_record"); without a validated one, an
estimate from the footer with a `decode_problems` entry; a histogram's
from the footer start ("footer")
- project_info: setup name and the four user notes, by position
- raw_samples (Tran/Vert/Long/MicL int16 lists)
- peak_values (computed from raw_samples; approximate — see notes
on _peaks_from_samples about Normal-range assumption)
@@ -860,21 +1019,20 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
byte-for-byte regeneration of the BW file from this Event alone is
not possible — the on-disk BW file IS the byte-for-byte source.
"""
path = Path(path)
raw = path.read_bytes()
label = name or "<bytes>"
if len(raw) < _bw._WAVEFORM_HEADER_SIZE + 21 + 26:
raise ValueError(f"{path}: file too short ({len(raw)} bytes) to be a BW event")
raise ValueError(f"{label}: file too short ({len(raw)} bytes) to be a BW event")
# Header: validate magic prefix.
header = raw[:_bw._WAVEFORM_HEADER_SIZE]
if not header.startswith(_bw._FILE_HEADER_PREFIX):
raise ValueError(f"{path}: not a Blastware file (bad header prefix)")
raise ValueError(f"{label}: not a Blastware file (bad header prefix)")
# STRT record: 21 bytes immediately after the header.
strt_raw = raw[_bw._WAVEFORM_HEADER_SIZE : _bw._WAVEFORM_HEADER_SIZE + 21]
strt_fields = _decode_strt(strt_raw)
if not strt_fields:
raise ValueError(f"{path}: STRT record missing or malformed")
raise ValueError(f"{label}: STRT record missing or malformed")
# Footer: locate the 0e 08 marker, validating the year is in a sane range.
body_start = _bw._WAVEFORM_HEADER_SIZE + 21
@@ -913,7 +1071,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
if footer_pos < 0 and len(raw) >= 26:
footer_pos = len(raw) - 26
if footer_pos < body_start:
raise ValueError(f"{path}: footer not found")
raise ValueError(f"{label}: footer not found")
body = raw[body_start : footer_pos]
footer = raw[footer_pos : footer_pos + 26]
@@ -960,18 +1118,12 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
if decoded is None:
log.warning(
"%s: body codec failed to decode (body starts %s) — "
"raw_samples will be empty", path, body[:8].hex(" "),
"raw_samples will be empty", label, body[:8].hex(" "),
)
samples = {"Tran": [], "Vert": [], "Long": [], "MicL": []}
else:
samples = decoded_to_adc_counts(decoded)
# Metadata strings (label-anchored search across the body).
project = _find_first_string(body, b"Project:")
client = _find_first_string(body, b"Client:")
user = _find_first_string(body, b"User Name:")
seisloc = _find_first_string(body, b"Seis Loc:")
# Build the Event.
ev = Event(index=-1)
if strt_fields.get("waveform_key"):
@@ -981,10 +1133,23 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
# ".bw" suffix, so the derivation falls back to "Waveform" and the
# caller overrides ev.record_type using the original filename — see
# waveform_store.save_imported_bw.
ev.record_type = derive_record_type_from_filename(path.name)
ev.rectime_seconds = strt_fields.get("rectime_seconds")
ev.total_samples = strt_fields.get("total_samples")
ev.pretrig_samples = strt_fields.get("pretrig_samples")
ev.record_type = derive_record_type_from_filename(name)
# Setup fields come from the recording-setup block (#44/#45), not the STRT
# record: STRT[18] is the record-type marker (0x46 / 0x0A), which is why
# every waveform used to read "70 s". A histogram has no record time or
# pre-trigger -- Blastware reports neither.
ev.sample_rate = _setup_sample_rate(raw)
if is_waveform_body:
ev.rectime_seconds = _setup_record_time(raw)
ev.total_samples = len(samples["Tran"]) or None
pre = _setup_pretrigger(raw)
if pre is not None and ev.sample_rate:
ev.pretrig_samples = round(-pre * ev.sample_rate)
if None in (ev.sample_rate, ev.rectime_seconds, ev.pretrig_samples):
ev.decode_problems.append(
f"recording-setup block incomplete: sample rate {ev.sample_rate}, "
f"record time {ev.rectime_seconds}, pre-trigger {pre}")
# Event timestamp. The footer's two timestamps mean different things by
# record type:
@@ -999,11 +1164,37 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
# * Histogram / undecodable: ts1 = the window start, which IS the event
# time — keep it.
# Discriminate by ``is_waveform_body`` (the codec), not the filename.
#
# ⚠ 2026-10-26 (measured): ts2 - record time is a second off on ~19% of
# waveforms. The exact trigger is in the instrument's own event record,
# embedded in the 5A stream (_embedded_event_record), so a waveform takes
# it from there. Without a validated one the estimate stands, reported as a
# decode problem -- never a filename's time, which is only a cross-check.
# Histograms stay on ts1 although it runs a second early on 97% (their
# record, marker fe f5, holds the exact start): in Blastware's timing a
# waveform and its histogram share a second 209 times in prod's store, and
# events is unique on (serial, timestamp) -- #51.
if is_waveform_body and ts2 is not None:
_stop = datetime.datetime(ts2.year, ts2.month, ts2.day,
ts2.hour, ts2.minute, ts2.second)
_rt = _parse_record_time_seconds(raw)
_trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop
_start = (datetime.datetime(ts1.year, ts1.month, ts1.day, ts1.hour, ts1.minute, ts1.second)
if ts1 is not None else None)
_trig, _why = _embedded_event_record(raw, footer_pos, _start, _stop, _rt)
if _trig is not None:
ev.timestamp_source = "event_record"
else:
_trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop
ev.timestamp_source = "estimate"
_problem = (f"no validated embedded event record ({_why}); the time is "
"estimated as the footer stop minus the record time, which is a "
"second off on ~19% of measured files")
ev.decode_problems.append(_problem)
log.warning("%s: %s", label, _problem)
_named = _bw.blastware_filename_time(name) if name else None
if _named is not None and _named != _trig:
log.warning("%s: decoded event time %s (%s) disagrees with the filename's %s; "
"the decoded time is kept", label, _trig, ev.timestamp_source, _named)
ev.timestamp = Timestamp(
raw=footer[10:18],
flag=0x10,
@@ -1017,10 +1208,9 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
year=ts1.year, unknown_byte=0, month=ts1.month, day=ts1.day,
hour=ts1.hour, minute=ts1.minute, second=ts1.second,
)
ev.timestamp_source = "footer"
ev.project_info = ProjectInfo(
project=project, client=client, operator=user, sensor_location=seisloc,
)
ev.project_info = _setup_notes(raw)
ev.raw_samples = samples
# Sensor self-check traces from the binary's trailing block (waveform
# events only; returns {} for histograms / when absent). Carried on the
+184 -134
View File
@@ -255,18 +255,25 @@ def walk_body(body: bytes) -> List[dict]:
def _walk_auto(body: bytes) -> List[dict]:
"""Pick the block model by signature strength, not by which returns first.
The multi-interval variant announces itself with consecutive block headers
at an exact ``12 + 20*n`` stride — far stronger evidence than a handful of
scattered standard-tail blocks, which a multi-interval body will also yield
by coincidence. Dispatching on "whichever decoder returns something"
handed 193 BE18193 files to the standard walker and produced peaks of
149 in/s against a 10 in/s full scale.
A multi-interval body announces itself with consecutive block headers at an
exact ``12 + record * n`` stride -- far stronger evidence than a handful of
scattered standard-tail blocks, which it will also yield by coincidence.
Dispatching on "whichever decoder returns something" handed 193 BE18193
files to the standard walker and produced peaks of 149 in/s against a
10 in/s full scale. A single short block (under a minute of intervals) has
no second header; it is tried after the standard walker, which a one-block
standard body satisfies with the same values.
"""
if detect_multi_interval_stride(body):
layout = detect_multi_interval_layout(body)
if layout and (_is_multi_header(body, _stride(*layout))
or layout[0] == 16):
recs = walk_multi_interval_blocks(body)
if recs:
return recs
return walk_body(body)
recs = walk_body(body)
if recs:
return recs
return walk_multi_interval_blocks(body) if layout else []
def decode_histogram_body(body: bytes) -> Optional[dict]:
@@ -291,7 +298,9 @@ def decode_histogram_body(body: bytes) -> Optional[dict]:
"Tran": [r["t_peak"] for r in records],
"Vert": [r["v_peak"] for r in records],
"Long": [r["l_peak"] for r in records],
"MicL": [r["m_peak"] for r in records],
# A mic-off histogram has no mic channel: an empty list, as a mic-off
# waveform's decode gives.
"MicL": [r["m_peak"] for r in records if r["m_peak"] is not None],
}
@@ -328,160 +337,201 @@ def geo_count_to_ins(count: int) -> float:
return count * _GEO_LSB_INS
# ── Multi-interval block variant (CONFIRMED 2026-08-26) ─────────────────────
# ── Multi-interval blocks (CONFIRMED 2026-08-26; re-read 2026-10-26) ─────────
#
# When the histogram interval is SHORTER than one minute, the device packs
# several intervals into a single block so that every block still covers
# exactly one minute of data:
# When the histogram interval is SHORTER than one minute, the device packs one
# minute of intervals into each block:
#
# interval size intervals/block stride
# 1 minute 1 32 <- the standard block above
# 15 seconds 4 92
# 2 seconds 30 612
# interval per block stride, mic on (20 B records) mic off (16 B)
# 1 minute 1 32 <- the standard block above 28 (inferred)
# 15 s 4 92 76 (inferred)
# 2 s 30 612 492 (inferred)
#
# stride = 12 + n_intervals * 20
# stride = 12 + per_block * record, record = 4 * channels + 4
#
# Block layout:
# Block layout (measured 2026-10-26, issues #47 and #49):
# [0] 0x00
# [1] segment_id (256 blocks per segment, same as the standard block)
# [2:4] block_ctr uint16 LE (0x0100.., resets each segment)
# [4] 0x0a marker
# [5] 0x00
# [6 ...] n x 20-byte interval records, each carrying 8 x uint16
# LITTLE-endian values:
# T_peak, T_halfperiod, V_peak, V_halfperiod,
# L_peak, L_halfperiod, M_peak, M_halfperiod
# then 2 more words; the first is 0x0000 on every real interval.
# [-6:] 6-byte block trailer
# [1] segment_id (256 blocks per segment, as in the standard block)
# [2:4] block_ctr uint16 LE
# [4] 0x0a
# [5 ...] one record per interval: per channel a BIG-endian uint16 peak and
# half-period (Tran, Vert, Long[, MicL]), then 0x0000, then one more
# word ("meta_var" keeps those 4 bytes)
# [-7:] trailer: 3 bytes, then the 4-byte tail -- 9c 06 00 42 on the
# stream's LAST block
#
# ⚠ ENDIANNESS: the standard 32-byte block is BIG-endian. This variant is
# LITTLE-endian. Do not share the accessor.
# The last block is SHORT, not padded: it holds only the intervals recorded and
# ends on 9c 06 00 42 (K440L3AQ.T70H: 1,427 x 4 + 2 = 5,710, Blastware's count;
# T193L0XM.CI0H: 30 + 21 = 51). Reading it at full stride ran into the setup
# data that follows, which is what the old "garbage slot" trimming cleaned up;
# that trimming survives only as the fallback for a stream with no 9c 06 00 42.
#
# These files previously decoded to nothing at all — 415 of them in the
# production snapshot, 216 on BE18193 (2 s intervals) and 199 on BE9440
# (15 s). Before that they were being accepted by the WAVEFORM codec, which
# returned garbage peaking up to 400x the device-reported PPV.
# ⚠ RETRACTED 2026-10-26: "8 x uint16 LITTLE-endian from byte 6, a 6-byte
# header with [5] == 0". That is the same bytes shifted by one: identical while
# every high byte is zero, which is why it matched Blastware on 10,715,314 of the
# 770 archive files' intervals -- and wrong on the 1 that was not (K440KZP4.560H
# #4764: a Long half-period of 1 read as 257, ">100 Hz" read as ~2 Hz). And
# byte 5 is the first record's Tran peak high byte, so a block whose first
# interval exceeded 1.275 in/s ended the old walk.
#
# Ground truth: BE9440/K440L3AQ.T70H (15 s intervals, 5,710 of them) decodes
# against its Blastware ASCII export with 17,130/17,130 geo peak counts,
# 22,840/22,840 frequencies and 5,710/5,710 mic dB(L) values matching exactly.
# Mic off (#47): BE9441's K441LTOK.QZ0 (2 s, 22 intervals, one short block)
# matches its Blastware export on 66/66 peaks and 66/66 frequencies. The mic-off
# strides above follow from the same layout; only the 2 s short block is
# measured.
#
# Ground truth, mic on: BE9440/K440L3AQ.T70H (15 s, 5,710 intervals) --
# 17,130 / 22,840 / 5,710 geo peaks, frequencies and mic dB(L), all exact.
_MULTI_HEADER_LEN = 6
_MULTI_RECORD_LEN = 20
_MULTI_TRAILER_LEN = 6
# At least 2 records: a 1-record block would have stride 12 + 20 = 32, which
# collides with the standard big-endian block and mis-decodes it.
_MULTI_MIN_RECORDS = 2
_MULTI_MAX_RECORDS = 64
_MULTI_HEADER_LEN = 5
_MULTI_TRAILER_LEN = 7
_MULTI_MAX_RECORDS = 64
_RECORD_LENS = (20, 16) # mic on (4 channels), mic off (3 channels)
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. A peak above
# this is physically impossible and marks buffer garbage in a partial block.
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. Used only by
# the fallback trim of a stream with no terminal tail.
_GEO_MAX_COUNTS = 2000
def _is_multi_header(body: bytes, off: int) -> bool:
return (off + _MULTI_HEADER_LEN <= len(body)
and body[off] == 0x00
and body[off + 4] == 0x0A
and body[off + 5] == 0x00)
and body[off + 4] == 0x0A)
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
"""Block stride of a multi-interval histogram body, or None.
def _ctr(body: bytes, off: int) -> int:
return body[off + 2] | (body[off + 3] << 8)
Found by locating the second block header; validated against
``stride = 12 + n * 20`` and confirmed on a third block where present.
def _follows(body: bytes, off: int, nxt: int) -> bool:
"""A block header at ``nxt`` that continues the block at ``off``: block_ctr
one higher, or -- every 256 blocks -- the next segment (block_ctr restarts)."""
if not _is_multi_header(body, nxt):
return False
if body[nxt + 1] == body[off + 1]:
return (_ctr(body, nxt) - _ctr(body, off)) & 0xFFFF == 1
return body[nxt + 1] == (body[off + 1] + 1) & 0xFF
def _stride(rec: int, n: int) -> int:
return _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + rec * n
def _records_plausible(body: bytes, off: int, rec: int, m: int) -> bool:
"""Every record's zero word is 0000 -- what tells a 16-byte layout from a
20-byte one when both strides happen to fit (492 = 12 + 16x30 = 12 + 20x24)."""
z = rec - 4
for k in range(m):
q = off + _MULTI_HEADER_LEN + rec * k
if q + rec > len(body) or body[q + z] or body[q + z + 1]:
return False
return True
def detect_multi_interval_layout(body: bytes) -> Optional[Tuple[int, int]]:
"""``(record_len, per_block)`` of a multi-interval body, or None.
Found from the second block header (block_ctr one higher), confirmed on a
third when present; a single short block is found from its terminal tail.
"""
if not _is_multi_header(body, 0):
return None
lo = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MIN_RECORDS
hi = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MAX_RECORDS
for stride in range(lo, min(hi, len(body)) + 1, 2):
if (stride - 12) % _MULTI_RECORD_LEN:
continue
if not _is_multi_header(body, stride):
continue
# DECISIVE CHECK: consecutive blocks differ by exactly 1 in block_ctr.
# Without it this false-positives on ordinary standard-block bodies:
# those carry a header every 32 bytes, and 192 = 12 + 20*9 and
# 512 = 12 + 20*25 are both multiples of 32, so a stride "fits" while
# actually skipping 6 or 16 real blocks. Sampling a standard body at
# stride 192 handed 9,082 files to the wrong decoder and produced peaks
# of 149 in/s against a 10 in/s full scale.
def _ctr(o: int) -> int:
return body[o + 2] | (body[o + 3] << 8)
if (_ctr(stride) - _ctr(0)) & 0xFFFF != 1:
continue
# Confirm on a third block WHEN ONE IS ACTUALLY PRESENT. A body can
# be longer than two strides and still hold only two real blocks: a
# final *partial* block leaves trailing padding. E.g. 51 intervals at
# 2 s = one full 30-interval block + a 21-interval remainder, in a
# 2787-byte body — long enough to demand a third header at 1224 that
# does not exist. Requiring it unconditionally threw away the correct
# stride and the file decoded to nothing (BE18193 T193L0XM.CI0H).
# The block-counter check above is the decisive anti-false-positive
# test; this one is corroboration, so a missing third header means
# end-of-stream, not disqualification.
if (2 * stride + _MULTI_HEADER_LEN <= len(body)
and _is_multi_header(body, 2 * stride)):
if (_ctr(2 * stride) - _ctr(stride)) & 0xFFFF != 1:
for rec in _RECORD_LENS:
# A 20-byte record with one interval per block IS the standard 32-byte
# block, which walk_body reads; the mic-off one-minute block is not.
for n in range(2 if rec == 20 else 1, _MULTI_MAX_RECORDS + 1):
s = _stride(rec, n)
if s + _MULTI_HEADER_LEN > len(body):
break
if not _follows(body, 0, s):
continue
return stride
# The block-counter step is the decisive test: a standard body has a
# header every 32 bytes, and 192 = 12 + 20x9 skips 6 of them. A third
# block, when there is one, must follow too.
if (_is_multi_header(body, 2 * s) and not _follows(body, s, 2 * s)
and body[2 * s - 4:2 * s] != _BLOCK_TAIL_TERMINAL):
continue
if not _records_plausible(body, 0, rec, n):
continue
return rec, n
# One block only (a histogram shorter than a minute): bounded by its tail.
t = body.find(_BLOCK_TAIL_TERMINAL)
while t >= 0:
for rec in _RECORD_LENS:
span = t + 4 - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN
if span > 0 and span % rec == 0 and span // rec <= _MULTI_MAX_RECORDS \
and _records_plausible(body, 0, rec, span // rec):
return rec, span // rec
t = body.find(_BLOCK_TAIL_TERMINAL, t + 1)
return None
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
"""Block stride of a multi-interval histogram body, or None."""
layout = detect_multi_interval_layout(body)
return _stride(*layout) if layout else None
def _decode_record(body: bytes, q: int, rec: int, off: int) -> dict:
def be16(p: int) -> int:
return (body[p] << 8) | body[p + 1]
mic = rec == 20
z = rec - 4
return {
"segment_id": body[off + 1],
"block_ctr": _ctr(body, off),
"t_peak": be16(q), "t_halfp": be16(q + 2),
"v_peak": be16(q + 4), "v_halfp": be16(q + 6),
"l_peak": be16(q + 8), "l_halfp": be16(q + 10),
"m_peak": be16(q + 12) if mic else None,
"m_halfp": be16(q + 14) if mic else None,
"meta_var": bytes(body[q + z:q + z + 4]),
"is_terminal": False,
}
def walk_multi_interval_blocks(body: bytes,
stride: Optional[int] = None) -> List[dict]:
"""Decode a multi-interval histogram body into per-interval records."""
if stride is None:
stride = detect_multi_interval_stride(body)
if not stride:
return []
n_per_block = (stride - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN) // _MULTI_RECORD_LEN
if n_per_block < 1:
return []
def u16le(p: int) -> int:
return body[p] | (body[p + 1] << 8)
"""Decode a multi-interval histogram body into per-interval records.
``stride`` is accepted for compatibility and ignored: the record size is
detected, and each block's own length is read from the stream.
"""
layout = detect_multi_interval_layout(body)
if not layout:
return []
rec, n = layout
s = _stride(rec, n)
out: List[dict] = []
for off in range(0, len(body) - stride + 1, stride):
if not _is_multi_header(body, off):
break # end of the block run; trailer follows
for k in range(n_per_block):
q = off + _MULTI_HEADER_LEN + _MULTI_RECORD_LEN * k
out.append({
"_tail0": u16le(q + 16),
"segment_id": body[off + 1],
"block_ctr": u16le(off + 2),
"t_peak": u16le(q), "t_halfp": u16le(q + 2),
"v_peak": u16le(q + 4), "v_halfp": u16le(q + 6),
"l_peak": u16le(q + 8), "l_halfp": u16le(q + 10),
"m_peak": u16le(q + 12), "m_halfp": u16le(q + 14),
"meta_var": bytes(body[q + 16:q + 20]),
"is_terminal": False,
})
# A session ending mid-block leaves the remaining slots of the FINAL block
# filled with whatever was in the buffer. Those decoded as peaks thousands
# of times the device-reported PPV, so they have to go — but only from the
# final block: a non-zero tail word occurs mid-file on real intervals, and
# trimming on that alone truncated four BE9440 files by up to 2,800
# intervals, while trimming purely from the end left garbage stranded
# behind one slot that happened to have a zero tail word.
#
# Within the final block, stop at the first slot that is not plausibly
# real: a non-zero tail word, or a geo peak above full scale. 16-count
# units put Normal-range full scale (10.000 in/s) at 2000 counts, so
# anything beyond that is physically impossible.
if out:
last_block_start = ((len(out) - 1) // n_per_block) * n_per_block
for i in range(last_block_start, len(out)):
r = out[i]
if (r["_tail0"] != 0
or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS):
del out[i:]
off = 0
while _is_multi_header(body, off):
# The last block ends on the terminal tail, after however many intervals
# it holds; any other block runs the full stride to the next header.
m = next((k for k in range(1, n + 1)
if body[off + _stride(rec, k) - 4:off + _stride(rec, k)] == _BLOCK_TAIL_TERMINAL),
None)
last = m is not None
if not last:
nxt = off + s
if not _follows(body, off, nxt):
# No terminal tail and no next block: the stream just stops. Read
# what fits and trim implausible slots (the pre-2026-10-26 rule).
m, last = min(n, (len(body) - off - _MULTI_HEADER_LEN) // rec), True
recs = [_decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off)
for k in range(max(m, 0))]
for k, r in enumerate(recs):
if (r["meta_var"][:2] != b"\x00\x00"
or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS):
del recs[k:]
break
out.extend(recs)
break
for r in out:
r.pop("_tail0", None)
m = n
for k in range(m):
r = _decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off)
r["is_terminal"] = last
out.append(r)
if last:
break
off += s
return out
+9
View File
@@ -553,6 +553,15 @@ class Event:
# shape diagnostic (rendered fit-to-box). None when absent.
sensor_check: Optional[dict] = None # {"Tran": [...], ..., "MicL": [...]}
# Where `timestamp` came from, when decoded from a Blastware binary
# (event_file_io): "event_record" -- the instrument's own event record in
# the 5A stream, validated; "report" -- a paired Blastware report;
# "footer" -- a histogram's footer start; "estimate" -- footer stop minus
# the record time, a second off on ~19% of measured files, so it comes with
# an entry in decode_problems. None: not decoded from a file.
timestamp_source: Optional[str] = None
decode_problems: list = field(default_factory=list)
# ── Debug / introspection ─────────────────────────────────────────────────
# Raw 210-byte waveform record bytes, set when debug mode is active.
# Exposed by the SFM server via ?debug=true so field layouts can be verified.