Files
seismo-relay/minimateplus/event_file_io.py
T
serversdownandClaude Opus 5.5 2b698e74cf feat(decode): a histogram's interval detail -- frequencies (#50), vector sums, interval size, stop
Group B of the file-only decode, measured on DL2 2026-11-03:

- Frequency = (sample rate / 2) / half-period: 527,915 / 527,915 cells
  at 1024 sps and 1,725 / 1,725 at 2048.  #50: half_period_to_hz took a
  fixed 512 and halved every 2048-sps frequency; it now takes the rate
  (default 1024).  Blastware prints 'N/A' for a half-period of 0, '>100'
  ('>200' at 2048) at 5 samples or fewer, '<1.0' below 1 Hz.
- Each interval's vector sum, sqrt(PVS^2) at the event's range:
  771,354 / 771,354.
- Interval size: uint16 seconds at k - 40 (Series IV [8:10]).
- Stop: the footer's (2,995 / 2,999 sampled; 4 print a second earlier).

Event gains histogram_interval_sec, interval_half_periods, interval_pvs
and stop_time; the .h5 gains /intervals/half_period/<ch>,
/intervals/pvs_ips and a histogram_interval_sec attr.  The decoder walks
a histogram once (histogram_codec.channels_from_records) and takes the
event's PVS from the same records.  The checker compares each interval
column, number or Blastware's word; the test that pinned Tran Freq Hz
as blank now pins the match.

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

1447 lines
63 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
minimateplus/event_file_io.py — modern event-file (.sfm.json sidecar) IO.
This module is the single home for event-file conversion code that doesn't
fit cleanly inside `blastware_file.py` (which is the BW binary codec):
- sidecar JSON read/write (the modern per-event metadata file)
- read_blastware_file() — reverse of write_blastware_file, used by
the BW-importer flow when SFM is ingesting files produced by
Blastware's own ACH (where the source A5 frames aren't available).
Sidecar schema v1 layout — see docs in the project plan or the schema
declared in `event_to_sidecar_dict()`.
"""
from __future__ import annotations
import datetime
import hashlib
import json
import logging
import math
import os
import re
import struct
from pathlib import Path
from typing import Optional, Union
from .models import DeviceInfo, Event, PeakValues, ProjectInfo, Timestamp
from . import blastware_file as _bw # avoid circular reference at module load
from .bw_ascii_report import BwAsciiReport
from . import waveform_codec as _wc
from .waveform_codec import decode_waveform_v2, decoded_to_adc_counts
from .histogram_codec import channels_from_records, decode_histogram_body, decode_histogram_body_full
# Reference pressure for dB(L) → psi conversion (20 µPa expressed in psi).
# Same constant as sfm/sfm_webapp.html so server-side and browser-side
# conversions agree.
_DBL_REF_PSI = 2.9e-9
log = logging.getLogger(__name__)
# Schema version for the sidecar JSON. Bump when fields change shape.
# Older readers must reject anything > SCHEMA_VERSION; newer fields added
# inside `extensions` are forward-compatible without a bump.
SCHEMA_VERSION = 1
SIDECAR_KIND = "sfm.event"
# Default tool_version stamp; callers can override. Hard-coded here
# rather than read via importlib.metadata because the latter reflects the
# *installed* dist-info, which doesn't update when pyproject.toml is
# 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.33.0" # setup + notes, record type, histogram PVS and mic from the file; gates the backfill regen
try:
# Best-effort: prefer the installed metadata when it's NEWER than the
# baked-in constant (e.g. a downstream packager bumped the wheel
# without editing this file). Otherwise fall back to TOOL_VERSION.
from importlib.metadata import version as _pkg_version
_meta_v = _pkg_version("seismo-relay")
def _vtuple(s):
try:
return tuple(int(p) for p in s.split(".")[:3])
except Exception:
return (0, 0, 0)
_TOOL_VERSION_DEFAULT = (
_meta_v if _vtuple(_meta_v) > _vtuple(TOOL_VERSION) else TOOL_VERSION
)
except Exception:
_TOOL_VERSION_DEFAULT = TOOL_VERSION
# ── Sidecar dict construction ─────────────────────────────────────────────────
def _ts_iso(ts: Optional[Timestamp]) -> Optional[str]:
if ts is None:
return None
try:
return datetime.datetime(
ts.year, ts.month, ts.day,
ts.hour or 0, ts.minute or 0, ts.second or 0,
).isoformat()
except Exception:
return str(ts)
def _peak_values_to_dict(pv: Optional[PeakValues]) -> dict:
if pv is None:
return {
"transverse": None,
"vertical": None,
"longitudinal": None,
"vector_sum": None,
"mic_psi": None,
}
return {
"transverse": pv.tran,
"vertical": pv.vert,
"longitudinal": pv.long,
"vector_sum": pv.peak_vector_sum,
"mic_psi": pv.micl,
}
def _bw_report_to_dict(report: BwAsciiReport) -> dict:
"""Project a parsed BW ASCII report into the sidecar's `bw_report` block.
All fields are rendered as plain JSON-compatible types (no datetime
objects). Channels are uniformly lowercased for stable JSON keys.
"""
def _ch(ch_name: str) -> dict:
cs = report.channels.get(ch_name)
if cs is None:
return {}
out = {
"ppv_ips": cs.ppv_ips,
"zc_freq_hz": cs.zc_freq_hz,
"time_of_peak_s": cs.time_of_peak_s,
"peak_accel_g": cs.peak_accel_g,
"peak_disp_in": cs.peak_disp_in,
}
# Drop all-None entries — keeps the JSON tidy for partial reports.
out = {k: v for k, v in out.items() if v is not None}
# Saturation flag (only present when True) — signals that ppv_ips
# is the channel range max (a lower bound), not an exact reading.
if getattr(cs, "ppv_saturated", False):
out["ppv_saturated"] = True
# ZC Freq above device reporting ceiling (BW ">100 Hz") — value
# in zc_freq_hz is the threshold, not an exact measurement.
if getattr(cs, "zc_freq_above_range", False):
out["zc_freq_above_range"] = True
return out
def _sc(ch_name: str) -> dict:
sc = report.sensor_check.get(ch_name)
if sc is None:
return {}
out = {
"freq_hz": sc.test_freq_hz,
"ratio": sc.test_ratio,
"amplitude_mv": sc.test_amplitude_mv,
"result": sc.test_results,
}
return {k: v for k, v in out.items() if v is not None}
monitor_log = []
for entry in report.monitor_log:
e = {
"start": entry.start_time.isoformat() if entry.start_time else None,
"stop": entry.stop_time.isoformat() if entry.stop_time else None,
"description": entry.description,
}
monitor_log.append({k: v for k, v in e.items() if v is not None})
return {
"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,
},
"recording": {
"sample_rate_sps": report.sample_rate_sps,
"record_time_s": report.record_time_s,
"pretrig_s": report.pretrig_s,
"stop_mode": report.record_stop_mode,
"geo_range_ips": report.geo_range_ips,
"units": report.units,
},
"device": {
"battery_volts": report.battery_volts,
"calibration_date": report.calibration_date.isoformat() if report.calibration_date else None,
"calibration_by": report.calibration_by,
},
"peaks": {
"tran": _ch("Tran"),
"vert": _ch("Vert"),
"long": _ch("Long"),
"vector_sum": {
"ips": report.peak_vector_sum_ips,
"time_s": report.peak_vector_sum_time_s,
# Histogram events have an absolute date+time for the PVS
# (the interval at which it occurred); waveform events
# only have the time_s offset.
"when": report.peak_vector_sum_when.isoformat() if report.peak_vector_sum_when else None,
# Set when BW reported the PVS as OORANGE — value is the
# conservative upper bound sqrt(3) * geo_range_ips, not
# an exact peak.
"saturated": bool(getattr(report, "peak_vector_sum_saturated", False)),
},
},
"mic": {
"weighting": report.mic.weighting,
"pspl_dbl": report.mic.pspl_dbl,
"pspl_saturated": bool(getattr(report.mic, "pspl_saturated", False)),
"zc_freq_hz": report.mic.zc_freq_hz,
"zc_freq_above_range": bool(getattr(report.mic, "zc_freq_above_range", False)),
"time_of_peak_s": report.mic.time_of_peak_s,
},
"sensor_check": {
"tran": _sc("Tran"),
"vert": _sc("Vert"),
"long": _sc("Long"),
"mic": _sc("MicL"),
},
# Histogram-specific fields (None on waveform-mode events).
# Per-channel absolute peak time/date for histograms — for
# waveforms see channels[ch]["time_of_peak_s"] instead.
"histogram": {
"start": report.histogram_start.isoformat() if report.histogram_start else None,
"stop": report.histogram_stop.isoformat() if report.histogram_stop else None,
"n_intervals": report.histogram_n_intervals,
"interval_size": report.histogram_interval_size_str,
"interval_size_s": report.histogram_interval_size_s,
"channel_peak_when": {ch: dt.isoformat() for ch, dt in report.channel_peak_when.items()},
},
"monitor_log": monitor_log,
"pc_sw_version": report.pc_sw_version,
}
def _dbl_to_psi(pspl_dbl: float) -> float:
"""Convert dB(L) sound pressure level back to psi. Uses the same
20 µPa reference (= 2.9e-9 psi) as the webapp so server-side and
browser-side conversions agree."""
return _DBL_REF_PSI * (10.0 ** (pspl_dbl / 20.0))
def apply_report_to_event(event: Event, report: BwAsciiReport) -> None:
"""Overlay device-authoritative fields from a parsed BW ASCII report
onto an in-memory Event, IN-PLACE.
Why this exists
───────────────
`read_blastware_file()` parses the BW binary and fills `Event.peak_values`
via `_peaks_from_samples()` — which runs the (still-undecoded) BW body
codec assuming raw int16 LE and produces ±32K-shaped noise on every
channel. Result: peak values land in the SeismoDb event row as
~10 in/s on every event regardless of the actual signal.
When a paired BW ASCII report is available, the report carries the
device's own authoritative peak / project / sample-rate / record-time
values. This helper folds those onto the Event before it flows to
`SeismoDb.insert_events()`, so the DB columns reflect the report
rather than the broken-codec output.
Fields overlaid (only when the report supplies a non-None value):
- peak_values.tran / .vert / .long (from report.channels)
- peak_values.peak_vector_sum (from report.peak_vector_sum_ips)
- peak_values.micl (psi) (from report.mic.pspl_dbl → psi)
- project_info.project / .client / .operator / .sensor_location
- sample_rate (from report.sample_rate_sps)
- rectime_seconds (from report.record_time_s)
Fields NOT touched (operator-edit / parser-output preserved):
- timestamp, raw_samples, record_type, total_samples,
pretrig_samples, _waveform_key, _a5_frames, _raw_record
- false_trigger and review state (those live on the sidecar, not on Event)
"""
if event.peak_values is None:
event.peak_values = PeakValues()
pv = event.peak_values
ch = report.channels
if (t := ch.get("Tran")) and t.ppv_ips is not None: pv.tran = t.ppv_ips
if (v := ch.get("Vert")) and v.ppv_ips is not None: pv.vert = v.ppv_ips
if (l := ch.get("Long")) and l.ppv_ips is not None: pv.long = l.ppv_ips
if report.peak_vector_sum_ips is not None:
pv.peak_vector_sum = report.peak_vector_sum_ips
if report.mic.pspl_dbl is not None and report.mic.pspl_dbl > 0:
pv.micl = _dbl_to_psi(report.mic.pspl_dbl)
if (t := ch.get("Tran")):
pv.tran_zc_freq = t.zc_freq_hz
pv.tran_zc_above_range = bool(getattr(t, "zc_freq_above_range", False))
if (v := ch.get("Vert")):
pv.vert_zc_freq = v.zc_freq_hz
pv.vert_zc_above_range = bool(getattr(v, "zc_freq_above_range", False))
if (l := ch.get("Long")):
pv.long_zc_freq = l.zc_freq_hz
pv.long_zc_above_range = bool(getattr(l, "zc_freq_above_range", False))
if report.mic is not None:
pv.mic_zc_freq = report.mic.zc_freq_hz
pv.mic_zc_above_range = bool(getattr(report.mic, "zc_freq_above_range", False))
if event.project_info is None:
event.project_info = ProjectInfo()
pi = event.project_info
if report.project: pi.project = report.project
if report.client: pi.client = report.client
if report.operator: pi.operator = report.operator
if report.sensor_location: pi.sensor_location = report.sensor_location
if report.sample_rate_sps:
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 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:
"""Mirror of ``apply_report_to_event`` for the projected sidecar
dict shape (as produced by ``_bw_report_to_dict``).
Why this exists
───────────────
The ingest path holds a live ``BwAsciiReport`` parsed straight from
the ``_ASCII.TXT`` and uses ``apply_report_to_event`` to overlay
device-authoritative peaks onto the codec output before insert.
The backfill path doesn't have the original ``.TXT`` (it's not
retained in the waveform store), but it does have the preserved
``bw_report`` block from the sidecar — which contains the same
projected fields. Re-overlaying those during a backfill keeps the
DB peak columns aligned with what BW reports rather than letting
the codec output (which may be incomplete for unhandled formats or
walker edge cases) win by default.
No-ops cleanly when ``bw_report`` is ``None``, empty, or missing
any particular sub-field — only fields with a concrete value get
written. Mirrors ``apply_report_to_event``'s "report wins where
present" semantics.
"""
if not bw_report:
return
if event.peak_values is None:
event.peak_values = PeakValues()
pv = event.peak_values
peaks = bw_report.get("peaks") or {}
tran = (peaks.get("tran") or {}).get("ppv_ips")
vert = (peaks.get("vert") or {}).get("ppv_ips")
long = (peaks.get("long") or {}).get("ppv_ips")
if tran is not None: pv.tran = tran
if vert is not None: pv.vert = vert
if long is not None: pv.long = long
vs_ips = (peaks.get("vector_sum") or {}).get("ips")
if vs_ips is not None:
pv.peak_vector_sum = vs_ips
mic = bw_report.get("mic") or {}
pspl = mic.get("pspl_dbl")
if pspl is not None and pspl > 0:
pv.micl = _dbl_to_psi(pspl)
for axis, freq_attr, above_attr in (
("tran", "tran_zc_freq", "tran_zc_above_range"),
("vert", "vert_zc_freq", "vert_zc_above_range"),
("long", "long_zc_freq", "long_zc_above_range"),
):
chd = peaks.get(axis) or {}
setattr(pv, freq_attr, chd.get("zc_freq_hz"))
setattr(pv, above_attr, bool(chd.get("zc_freq_above_range", False)))
pv.mic_zc_freq = mic.get("zc_freq_hz")
pv.mic_zc_above_range = bool(mic.get("zc_freq_above_range", False))
rec = bw_report.get("recording") or {}
sr = rec.get("sample_rate_sps")
if sr:
event.sample_rate = sr
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:
if pi is None:
return {
"project": None,
"client": None,
"operator": None,
"sensor_location": None,
}
return {
"project": pi.project,
"client": pi.client,
"operator": pi.operator,
"sensor_location": pi.sensor_location,
}
def event_to_sidecar_dict(
event: Event,
*,
serial: str,
blastware_filename: str,
blastware_filesize: int,
blastware_sha256: str,
source_kind: str = "sfm-live",
txt_filename: Optional[str] = None,
a5_pickle_filename: Optional[str] = None,
tool_version: str = _TOOL_VERSION_DEFAULT,
captured_at: Optional[datetime.datetime] = None,
review: Optional[dict] = None,
extensions: Optional[dict] = None,
bw_report: Optional[BwAsciiReport] = None,
) -> dict:
"""
Build a v1 sidecar dict from an Event + the surrounding metadata.
Pure helper — no file I/O. Callers stitch the result into a sidecar
via `write_sidecar()` (or POST it back via the PATCH endpoint).
When *bw_report* is supplied (e.g. by the ACH-forwarded import path
where Blastware writes a per-event ASCII report alongside the binary),
its decoded fields are folded into the sidecar:
- A new top-level ``bw_report`` block carries the rich derived
per-channel stats (Peak Acceleration, Peak Displacement, ZC Freq,
Time of Peak), the Peak Vector Sum + time, the per-channel sensor
self-check results, and monitor-log timestamps.
- ``peak_values`` is overlaid from the report (the report's PPV/PVS
values are computed by the device firmware and are authoritative;
anything ``read_blastware_file()`` derived from samples is
approximate at best until the body codec is decoded).
- ``project_info`` is overlaid from the report when the report
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 -- 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}")
captured_at = captured_at or datetime.datetime.utcnow()
# ── Overlay event fields from the report when present ───────────────────
timestamp_iso = _ts_iso(event.timestamp)
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
# stores Mic peak as PSPL (dB(L)); we convert to psi to match the
# existing peak_values.mic_psi field.
peak_dict = _peak_values_to_dict(event.peak_values)
if bw_report:
ch = bw_report.channels
if (t := ch.get("Tran")) and t.ppv_ips is not None: peak_dict["transverse"] = t.ppv_ips
if (v := ch.get("Vert")) and v.ppv_ips is not None: peak_dict["vertical"] = v.ppv_ips
if (l := ch.get("Long")) and l.ppv_ips is not None: peak_dict["longitudinal"] = l.ppv_ips
if bw_report.peak_vector_sum_ips is not None:
peak_dict["vector_sum"] = bw_report.peak_vector_sum_ips
if bw_report.mic.pspl_dbl is not None and bw_report.mic.pspl_dbl > 0:
peak_dict["mic_psi"] = _dbl_to_psi(bw_report.mic.pspl_dbl)
# Project info: overlay from report (the report mirrors the
# session-start compliance config that BW renders in event reports).
proj_dict = _project_info_to_dict(event.project_info)
if bw_report:
if bw_report.project: proj_dict["project"] = bw_report.project
if bw_report.client: proj_dict["client"] = bw_report.client
if bw_report.operator: proj_dict["operator"] = bw_report.operator
if bw_report.sensor_location: proj_dict["sensor_location"] = bw_report.sensor_location
# Event-block fields: overlay from report where available.
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,
"rectime_seconds": event.rectime_seconds,
"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
# `event.rectime_seconds` from `read_blastware_file()` reads
# STRT[18] which is actually the `0x46` record-type marker (= 70)
# rather than the user's Record Time setting. Always overwrite.
if bw_report.sample_rate_sps:
event_block["sample_rate"] = bw_report.sample_rate_sps
if bw_report.record_time_s is not None:
event_block["rectime_seconds"] = bw_report.record_time_s
# Derive total_samples + pretrig_samples per channel from the
# report's sample_rate × times. These match the row count of
# the report's sample table (verified: event-c reports 1024 sps
# × (1.0 + 0.25) = 1280 rows).
if (sr := bw_report.sample_rate_sps) and bw_report.record_time_s is not None:
pretrig_s = abs(bw_report.pretrig_s) if bw_report.pretrig_s is not None else 0.0
event_block["total_samples"] = int(round(sr * (bw_report.record_time_s + pretrig_s)))
event_block["pretrig_samples"] = int(round(sr * pretrig_s))
out = {
"schema_version": SCHEMA_VERSION,
"kind": SIDECAR_KIND,
"event": event_block,
"peak_values": peak_dict,
"project_info": proj_dict,
"blastware": {
"filename": blastware_filename,
"filesize": blastware_filesize,
"sha256": blastware_sha256,
"available": True,
},
"source": {
"kind": source_kind,
"captured_at": captured_at.isoformat() + "Z" if captured_at.tzinfo is None else captured_at.isoformat(),
"tool_version": tool_version,
"a5_pickle_filename": a5_pickle_filename,
"txt_filename": txt_filename,
},
"review": review or {
"false_trigger": False,
"reviewer": None,
"reviewed_at": None,
"notes": "",
},
"extensions": extensions or {},
}
if bw_report:
out["bw_report"] = _bw_report_to_dict(bw_report)
return out
# ── Sidecar IO ────────────────────────────────────────────────────────────────
def write_sidecar(path: Union[str, Path], data: dict) -> None:
"""
Atomic write of a sidecar dict to <path>.
Validates schema_version is supported before writing so we don't
silently drop a future-format sidecar over the wire.
"""
path = Path(path)
sv = data.get("schema_version")
if not isinstance(sv, int) or sv < 1 or sv > SCHEMA_VERSION:
raise ValueError(
f"write_sidecar: unsupported schema_version={sv!r} "
f"(this build supports 1..{SCHEMA_VERSION})"
)
tmp = path.with_suffix(path.suffix + ".tmp")
with tmp.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2, sort_keys=False, default=str)
f.write("\n")
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
def read_sidecar(path: Union[str, Path]) -> dict:
"""
Load a sidecar JSON file.
Raises FileNotFoundError if missing, ValueError on bad shape /
unsupported schema_version. Unknown keys at the top level are
preserved in the returned dict (forward-compat).
"""
path = Path(path)
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, dict):
raise ValueError(f"sidecar at {path}: top-level is not a JSON object")
sv = data.get("schema_version")
if not isinstance(sv, int) or sv < 1:
raise ValueError(f"sidecar at {path}: missing or invalid schema_version")
if sv > SCHEMA_VERSION:
raise ValueError(
f"sidecar at {path}: schema_version={sv} > supported {SCHEMA_VERSION}; "
"upgrade seismo-relay to read this file"
)
if data.get("kind") != SIDECAR_KIND:
raise ValueError(f"sidecar at {path}: unexpected kind={data.get('kind')!r}")
return data
def patch_sidecar(
path: Union[str, Path],
*,
review: Optional[dict] = None,
extensions: Optional[dict] = None,
reviewer_now: bool = True,
) -> dict:
"""
Atomically apply a JSON-merge-patch to a sidecar file's `review`
and/or `extensions` blocks. Other top-level keys are untouched.
`review_now`: when True (default) and `review` is non-empty, stamps
`review.reviewed_at` with the current UTC time so the review-time is
auditable without the caller having to pass it.
Returns the new full sidecar dict.
"""
path = Path(path)
data = read_sidecar(path)
if review:
merged = dict(data.get("review") or {})
merged.update({k: v for k, v in review.items() if v is not None or k in merged})
if reviewer_now:
merged["reviewed_at"] = datetime.datetime.utcnow().isoformat() + "Z"
data["review"] = merged
if extensions:
merged_ext = dict(data.get("extensions") or {})
merged_ext.update(extensions)
data["extensions"] = merged_ext
write_sidecar(path, data)
return data
def sidecar_path_for(blastware_path: Union[str, Path]) -> Path:
"""Convention: <bw_path>.sfm.json sits next to the BW binary."""
p = Path(blastware_path)
return p.with_name(p.name + ".sfm.json")
def file_sha256(path: Union[str, Path], chunk_size: int = 65536) -> str:
"""Compute SHA-256 of a file as a hex string."""
h = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
# ── Blastware-file reader ─────────────────────────────────────────────────────
#
# Reverse of `blastware_file.write_blastware_file`. Used by the BW-import
# flow to ingest files produced by Blastware's own ACH (where the source
# A5 frames are not available).
#
# File structure (recap):
# [22B header] [21B STRT record] [body bytes] [26B footer]
#
# The body holds:
# - 6B preamble (00 00 ff ff ff ff) immediately after the STRT
# - 4-channel interleaved int16 LE samples
# - Embedded ASCII metadata strings (Project: / Client: / User Name: /
# Seis Loc: / Extended Notes) from the device's session-start config
#
# The 0C waveform record (per-event peaks, project name) is NOT in the
# BW file — those are computed by the device firmware and only carried
# in the live SUB 0C response. read_blastware_file() therefore computes
# peaks from the raw samples assuming Normal-range (10 in/s full-scale)
# geophone sensitivity. Imported events surface that assumption via the
# sidecar's `peak_values.computed_from_samples` flag.
# Geophone scale factor, in/s per ADC unit, for Normal range (10 in/s FS).
# Confirmed from CLAUDE.md (geo_hardware_constant = 6.206053 in/s per V,
# ADC full-scale = 1.61133 V Normal range = 10.0 in/s peak; per-count
# resolution ≈ 10.0 / 32768).
_GEO_NORMAL_FS_INS = 10.0
_GEO_SENSITIVE_FS_INS = 1.250
_INT16_FS = 32768.0
# Geophone full-scale count — 32000, not 32768. One decoder unit (16 ADC
# counts) is exactly 0.005 in/s, so 10.000 in/s = 32000 counts. Must match
# sfm.event_hdf5._GEO_INT16_FS or sidecar peaks disagree with the plotted
# waveform by 2.3%. Confirmed 2026-08-25 against the BW ASCII corpus.
_GEO_INT16_FS = 32000.0
# Full scale per geo_range: 0 Normal, 1 Sensitive.
_GEO_FS_BY_RANGE = {0: _GEO_NORMAL_FS_INS, 1: _GEO_SENSITIVE_FS_INS}
# A histogram's geo values are decoder units of 16 counts: 0.005 in/s at the
# Normal range, scaled by the range's full scale like the samples above.
_HIST_GEO_COUNTS_PER_UNIT = 16
# Microphone scale factor, psi per MicL count: one count is 0.25 Pa
# (waveform_codec.MIC_PA_PER_COUNT, measured against Blastware's psi(L) on
# 1,729,253 DL2 intervals). It replaces a "~0.5 psi full-scale" guess,
# 0.0125 / 32768, that read every mic peak ~95x low (2026-10-31).
_PA_PER_PSI = 6894.757
_MIC_PSI_PER_COUNT = _wc.MIC_PA_PER_COUNT / _PA_PER_PSI
def _decode_strt(strt: bytes) -> dict:
"""
Decode the 21-byte STRT record from a BW file: the waveform key (4B).
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()}
def _decode_samples_4ch_int16_le(stream: bytes) -> dict[str, list[int]]:
"""
Decode a 4-channel interleaved int16 LE byte stream into per-channel
lists. Channels are [Tran, Vert, Long, Mic] = [ch0, ch1, ch2, ch3].
Truncates to a multiple of 8 bytes (one full sample-set).
"""
n_complete = (len(stream) // 8) * 8
if n_complete == 0:
return {"Tran": [], "Vert": [], "Long": [], "MicL": []}
fmt = "<" + "h" * (n_complete // 2)
flat = list(struct.unpack(fmt, stream[:n_complete]))
return {
"Tran": flat[0::4],
"Vert": flat[1::4],
"Long": flat[2::4],
"MicL": flat[3::4],
}
def _peaks_from_samples(samples: dict[str, list[int]],
geo_fs_ins: float = _GEO_NORMAL_FS_INS) -> PeakValues:
"""
Compute peaks from raw int16 samples at the given geophone full scale
(Normal, 10 in/s, unless the file's range says otherwise). Used by the
BW-importer when the 0C waveform record (the device's authoritative peaks)
is unavailable.
"""
def _peak_ins(ch: list[int]) -> float:
if not ch:
return 0.0
m = max(abs(int(v)) for v in ch)
return m / _GEO_INT16_FS * geo_fs_ins
tran = _peak_ins(samples.get("Tran", []))
vert = _peak_ins(samples.get("Vert", []))
long_ = _peak_ins(samples.get("Long", []))
# Mic in psi: one count = 0.25 Pa
mic_ch = samples.get("MicL", []) or []
mic = max((abs(int(v)) for v in mic_ch), default=0) * _MIC_PSI_PER_COUNT
# Peak vector sum: max over time of sqrt(T^2 + V^2 + L^2)
pvs = 0.0
n = min(len(samples.get("Tran", [])), len(samples.get("Vert", [])), len(samples.get("Long", [])))
if n:
scale = geo_fs_ins / _GEO_INT16_FS
T = samples["Tran"]; V = samples["Vert"]; L = samples["Long"]
for i in range(n):
t = T[i] * scale
v = V[i] * scale
l = L[i] * scale
mag = (t*t + v*v + l*l) ** 0.5
if mag > pvs:
pvs = mag
return PeakValues(
tran=tran, vert=vert, long=long_,
peak_vector_sum=pvs, micl=mic,
)
# STRT[18], the record-type byte (#41): 0x46 on every one of DL2's 6,577
# waveform files and 0x0A on every one of its 63,535 histograms (measured
# 2026-10-29). Manual / Event / Combo never occur there, so their bytes are
# unknown and decode as None, not as a guess.
_RECORD_TYPE_BY_STRT = {0x46: "Waveform", 0x0A: "Histogram"}
_RECORD_TYPE_BY_EXT_SUFFIX = {
'H': 'Histogram',
'W': 'Waveform',
'M': 'Manual',
'E': 'Event',
'C': 'Combo',
}
def derive_record_type_from_filename(filename, default: str = "Waveform") -> str:
"""Derive a BW Event's record_type from its filename's extension suffix.
V10.72+ MiniMate Plus firmware encodes the event type as the LAST
character of the extension (the `T` in BW's `AB0T` scheme):
``M529LKIQ.G10H`` → H → ``"Histogram"``
``T350L385.VY0W`` → W → ``"Waveform"``
``...M`` → M → ``"Manual"``
``...E`` → E → ``"Event"``
``...C`` → C → ``"Combo"``
Old S338 firmware uses 3-char extensions ending in ``0`` whose
encoding is not yet known — those fall through to ``default``.
Micromate Series 4 uses a different scheme entirely (observed:
``IDFH``, ``IDFW``) but the LAST-char convention (H / W) still holds
for the type code, so it works for both families.
Returns ``default`` if filename is empty, has no extension, or the
suffix char isn't a recognized type code.
"""
if not filename:
return default
try:
name = Path(filename).name
except (TypeError, ValueError):
return default
if '.' not in name:
return default
ext = name.rsplit('.', 1)[1]
if not ext:
return default
return _RECORD_TYPE_BY_EXT_SUFFIX.get(ext[-1].upper(), default)
# Marker for the recording-setup config block, and the offset of the record-time
# 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. ⚠ 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
_INTERVAL_BEFORE_NAME = 40 # uint16 BE, histogram interval in seconds (2 / 5 / 15 / 60 / 300)
_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, Optional[int]]:
"""The trigger time and trigger source from the instrument's embedded event
record, or (None, why, None).
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.
The two bytes between the lead and `fe 80` are the trigger source, a uint16
BE bitmask: 0x01 Tran, 0x02 Vert, 0x04 Long, 0x08 MicL, 0x200 Manual --
Blastware's Trigger on 6,493 / 6,493 DL2 waveforms (2026-11-03).
"""
if start is None or stop is None:
return None, "the footer has no start and stop to check one against", None
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, int.from_bytes(raw[i - 2:i], "big")))
else:
rejected += 1
i = raw.find(_EVENT_RECORD_MARKER, i + 1)
if len(found) == 1:
return found[0][0], "", found[0][1]
if found:
return None, f"{len(found)} candidates validate", None
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate"), None
def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
"""The configured post-trigger record time in seconds, from the recording-
setup config block, or None when absent / implausible."""
a = raw.find(_RECSETUP_MARKER)
if a < _RECTIME_OFFSET_BEFORE_MARKER:
return None
off = a - _RECTIME_OFFSET_BEFORE_MARKER
try:
rt = struct.unpack(">f", raw[off:off + 4])[0]
except struct.error:
return None
return rt if 0.05 <= rt <= 600.0 else None
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]
enabled, number = _setup_job_number(raw, k)
return ProjectInfo(setup_name=text[0], project=project, client=client,
operator=operator, sensor_location=location,
job_number_enabled=enabled, job_number=number)
# The job number, in Series IV's 0x1A layout ([39] report flags, [40:42] the
# number): flags at k - 9, bit 0x02 = shown; the number, uint16 BE, at k - 8,
# kept while switched off. The flag matches Blastware's JobNumber on 2,997 /
# 2,997 DL2 events that print one and 66,986 / 66,986 that don't, and every
# printed value matches (all are 1; measured 2026-11-02).
_REPORT_FLAGS_BEFORE_NAME = 9
_JOB_NUMBER_BEFORE_NAME = 8
_JOB_NUMBER_ON = 0x02
def _setup_job_number(raw: bytes, k: int) -> tuple[Optional[bool], Optional[int]]:
"""(shown, number) from the setup block whose name starts at k."""
if k < _REPORT_FLAGS_BEFORE_NAME:
return None, None
flags = raw[k - _REPORT_FLAGS_BEFORE_NAME]
j = k - _JOB_NUMBER_BEFORE_NAME
return bool(flags & _JOB_NUMBER_ON), int.from_bytes(raw[j:j + 2], "big")
# The geophone range sits in the setup's channel blocks, which follow the
# notes: the byte 29 after each geophone label (`00 00 01 Tran ...`). 0x00 is
# Normal, 0x01 Sensitive -- Blastware's GeoRange on 70,042 / 70,042 DL2 events,
# all three channels agreeing on every one (measured 2026-11-01). SFM's live
# 1A read has the same byte at label+33.
_RANGE_AFTER_LABEL = 29
_CHANNEL_BLOCK_SPAN = 2000 # how far past the setup name the blocks may sit
def _setup_geo_range(raw: bytes) -> tuple[Optional[int], Optional[str]]:
"""(geo_range, problem): 0 Normal or 1 Sensitive when all three geophone
channels say the same, else None and why."""
k = _setup_name_at(raw)
if k is None:
return None, "no recording-setup block to read the geophone range from"
found = {}
for label in (b"Tran", b"Vert", b"Long"):
i = raw.find(b"\x00\x00\x01" + label, k, k + _CHANNEL_BLOCK_SPAN)
p = i + 3 + _RANGE_AFTER_LABEL
found[label.decode()] = raw[p] if i >= 0 and p < len(raw) else None
values = set(found.values())
if len(values) == 1 and values <= {0, 1}:
return values.pop(), None
return None, f"geophone range not read: channel range bytes {found}"
# The identity block before the setup: what the live read gets from SUB FE
# (DeviceInfo). Offsets back from k, the setup name; matched against every DL2
# report 2026-11-03 -- serial, version and calibration 69,983 / 69,983, the
# battery 69,729 plus 254 that Blastware rounds half up (6.25 -> "6.3 Volts").
_SERIAL_BEFORE_NAME = 202 # ASCII, NUL-terminated
_BATTERY_BEFORE_NAME = 190 # uint16 BE, hundredths of a volt
_FIRMWARE_MINOR_BEFORE_NAME = 193 # 0x11 = 17 for S338.17, as SUB EA
_FIRMWARE_BEFORE_NAME = 147 # "S338.17"
_DSP_BEFORE_NAME = 138 # "10.72"
_CALIBRATION_BEFORE_NAME = 132 # dd mm yyyy (BE)
_CALIBRATED_BY_BEFORE_NAME = 128 # "Instantel"
_MANUFACTURER_BEFORE_NAME = 94 # "Instantel"
_MODEL_BEFORE_NAME = 72 # "MiniMate Plus" / "BlastMate III"
def _cstr(raw: bytes, i: int, limit: int = 40) -> Optional[str]:
if i < 0:
return None
j = raw.find(b"\x00", i, i + limit)
s = raw[i:j if j >= 0 else i + limit].decode("ascii", errors="replace").strip()
return s or None
def _setup_identity(raw: bytes, k: int) -> tuple[Optional[DeviceInfo], Optional[float]]:
"""(the unit's identity, the battery in volts) from the block before the
setup name at k."""
if k < _SERIAL_BEFORE_NAME:
return None, None
serial = _cstr(raw, k - _SERIAL_BEFORE_NAME, 16)
if not serial:
return None, None
c = k - _CALIBRATION_BEFORE_NAME
try:
cal = datetime.date(int.from_bytes(raw[c + 2:c + 4], "big"), raw[c + 1], raw[c])
except ValueError:
cal = None
info = DeviceInfo(
serial=serial,
firmware_minor=raw[k - _FIRMWARE_MINOR_BEFORE_NAME],
firmware_version=_cstr(raw, k - _FIRMWARE_BEFORE_NAME, 9),
dsp_version=_cstr(raw, k - _DSP_BEFORE_NAME, 6),
manufacturer=_cstr(raw, k - _MANUFACTURER_BEFORE_NAME),
model=_cstr(raw, k - _MODEL_BEFORE_NAME),
calibration_date=cal,
calibrated_by=_cstr(raw, k - _CALIBRATED_BY_BEFORE_NAME, 32),
)
b = k - _BATTERY_BEFORE_NAME
return info, int.from_bytes(raw[b:b + 2], "big") / 100
# Trigger settings, in Series IV's 0x1A layout again: the trigger-source bitmask
# at k - 19 ([29]: 0x07 geophones, 0x08 mic), the stop mode at k - 31 ([17],
# 0 = Fixed), and each channel block's trigger level, a float32 at label + 30 --
# in/s for a geophone, psi for the mic. The mic block's type code at label + 4
# is Series IV's (2 = linear). Against every DL2 waveform (2026-11-03): the geo
# level 6,447 / 6,447, the mic level 4,403 / 4,403, and Blastware prints a level
# exactly when its channel is a trigger source and the event was not Manual.
_TRIGGER_SOURCES_BEFORE_NAME = 19
_STOP_MODE_BEFORE_NAME = 31
_TRIGGER_LEVEL_AFTER_LABEL = 30
_MIC_TYPE_AFTER_LABEL = 4
def _setup_trigger(raw: bytes, k: int) -> dict:
out = {"trigger_sources": raw[k - _TRIGGER_SOURCES_BEFORE_NAME],
"record_stop_mode": raw[k - _STOP_MODE_BEFORE_NAME]}
t = raw.find(b"\x00\x00\x01Tran", k, k + _CHANNEL_BLOCK_SPAN)
if t >= 0:
p = t + 3 + _TRIGGER_LEVEL_AFTER_LABEL
out["trigger_level_geo"] = struct.unpack_from(">f", raw, p)[0]
m = raw.find(b"MicL", k, k + _CHANNEL_BLOCK_SPAN)
if m >= 0:
out["trigger_level_mic_psi"] = struct.unpack_from(">f", raw, m + _TRIGGER_LEVEL_AFTER_LABEL)[0]
out["mic_type"] = int.from_bytes(raw[m + _MIC_TYPE_AFTER_LABEL:m + _MIC_TYPE_AFTER_LABEL + 4], "big")
return out
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 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 (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)
Does NOT recover the source A5 frames (they aren't in the BW file).
The returned Event has `_a5_frames = None`, signalling that
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.
"""
label = name or "<bytes>"
if len(raw) < _bw._WAVEFORM_HEADER_SIZE + 21 + 26:
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"{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"{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
# The footer is the file's last 26 bytes whenever they are one -- 0e 08 and
# two valid times: 70,041 / 70,041 DL2 files (measured 2026-11-03). Taking
# the first "0e 08 + plausible year" instead found, on 14 of them, an
# earlier record ~1.1 KB before the end holding the stop time and zeros: a
# histogram then started at its own stop (a day late on BE9558's daily
# histograms) and a waveform lost its stop, so its trigger time too.
#
# Otherwise the search below stands. The signature can occur inside the
# sample stream, so it prefers the first candidate whose body yields a
# waveform record chain terminating on the 0x06 marker, then the first
# candidate (2026-08-25: BE17353/S353L4O5.OX0W, false positive at 3800,
# real footer at 8576).
end = len(raw) - 26
if (end >= body_start and raw[end:end + 2] == b"\x0e\x08"
and _bw._decode_ts_be(raw[end + 2:end + 10]) is not None
and _bw._decode_ts_be(raw[end + 10:end + 18]) is not None):
footer_candidates = [end]
else:
footer_candidates = []
pos = body_start
while True:
pos = raw.find(b"\x0e\x08", pos)
if pos < 0 or pos + 26 > len(raw):
break
yr = (raw[pos + 4] << 8) | raw[pos + 5]
if 2015 <= yr <= 2050:
footer_candidates.append(pos)
pos += 1
footer_pos = -1
for cand in footer_candidates:
cand_body = raw[body_start:cand]
try:
recs = _wc.walk_records(cand_body)
except Exception:
recs = []
if recs:
tail = recs[-1]["end"]
if tail + 5 <= len(cand_body) and cand_body[tail + 4] == _wc.STREAM_END_ID:
footer_pos = cand
break
if footer_pos < 0 and footer_candidates:
footer_pos = footer_candidates[0]
if footer_pos < 0 and len(raw) >= 26:
footer_pos = len(raw) - 26
if footer_pos < body_start:
raise ValueError(f"{label}: footer not found")
body = raw[body_start : footer_pos]
footer = raw[footer_pos : footer_pos + 26]
# Footer layout:
# [0:2] 0e 08 marker
# [2:10] ts1 (start) BE 8B
# [10:18] ts2 (stop) BE 8B
# [18:24] 00 01 00 02 00 00
# [24:26] crc
ts1 = _bw._decode_ts_be(footer[2:10])
ts2 = _bw._decode_ts_be(footer[10:18])
# Body: decode via the verified body codecs. Two formats coexist:
#
# 1. Waveform-mode (.AB0W) — starts with 7-byte preamble
# ``00 02 00 [Tran[0] BE] [Tran[1] BE]`` followed by the
# tagged-block delta stream documented in
# ``docs/waveform_codec_re_status.md`` and §7.6.1 of the
# protocol reference. Decoded by ``waveform_codec.decode_waveform_v2``.
#
# 2. Histogram-mode (.AB0H) — a sequence of 32-byte blocks, one
# per histogram interval, each carrying per-channel peak +
# half-period values. Decoded by
# ``histogram_codec.decode_histogram_body``. Both codecs
# return the same channel-grouped output shape, so consumers
# don't need to special-case mode.
#
# The historical ``_decode_samples_4ch_int16_le`` int16-LE
# interpretation was retracted 2026-05-08 (see protocol-ref §7.6.1
# retraction box) — it produced ±32K noise on every event.
#
# If both codecs fail (malformed file, truncated body, unrecognised
# mode, synthetic test input), fall back to empty channels — the
# rest of the event (timestamp, waveform_key, project strings) is
# still recoverable and useful.
#
# The record type comes from the bytes: STRT[18] (#41), 0x46 / 0x0A on
# 70,041 / 70,041 DL2 files. It picks the codec. Trying the waveform codec
# first handed it BE9440 / BE9557 / BE17354's 2018 5 s histograms, which it
# accepted and returned ~5x too many "samples" for. Only an unknown type
# falls back to the old trial order. The filename's last letter is only a
# cross-check -- SFM's own downloads have no name, and a manual download's
# (".QZ0") carries no type at all.
type_byte = strt_raw[18]
record_type = _RECORD_TYPE_BY_STRT.get(type_byte)
problems = []
if record_type is None:
problems.append(f"unknown record type byte 0x{type_byte:02x} at STRT[18]")
hist_records = None
if record_type == "Histogram":
hist_records = decode_histogram_body_full(body)
decoded = channels_from_records(hist_records)
is_waveform_body = False
elif record_type == "Waveform":
decoded = decode_waveform_v2(body)
is_waveform_body = True
else:
decoded = decode_waveform_v2(body)
is_waveform_body = decoded is not None
if decoded is None:
hist_records = decode_histogram_body_full(body)
decoded = channels_from_records(hist_records)
if decoded is None:
log.warning(
"%s: body codec failed to decode (body starts %s) — "
"raw_samples will be empty", label, body[:8].hex(" "),
)
if record_type is not None:
problems.append(f"the {record_type.lower()} codec could not decode the body")
samples = {"Tran": [], "Vert": [], "Long": [], "MicL": []}
else:
samples = decoded_to_adc_counts(decoded)
# Build the Event.
ev = Event(index=-1)
if strt_fields.get("waveform_key"):
ev._waveform_key = bytes.fromhex(strt_fields["waveform_key"])
ev.record_type = record_type
ev.decode_problems.extend(problems)
named_type = derive_record_type_from_filename(name, default=None) if name else None
if named_type is not None and ev.record_type is not None and named_type != ev.record_type:
log.warning("%s: record type %s from the file disagrees with the filename's %s; "
"the file's is kept", label, ev.record_type, named_type)
# 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)
ev.geo_range, range_problem = _setup_geo_range(raw)
if range_problem:
ev.decode_problems.append(range_problem + "; peaks assume the Normal range")
k = _setup_name_at(raw)
if k is not None:
ev.device_info, ev.battery_volts = _setup_identity(raw, k)
for attr, value in _setup_trigger(raw, k).items():
setattr(ev, attr, value)
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:
# * Waveform: ts1 = the monitoring-SESSION start (shared across every
# event that day — a unit arming at 06:00 stamps 06:00 on all of them),
# ts2 = THIS event's recording STOP. Blastware's Date/Time is the
# TRIGGER = ts2 - record time, and the record time is a float32 in the
# recording-setup config block (see _parse_record_time_seconds), so the
# exact trigger is recoverable from the binary alone. Falls back to ts2
# (the stop, within the record duration) if the config block is absent.
# (Stamping ts1 showed the session start, hours off.)
# * 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)
_start = (datetime.datetime(ts1.year, ts1.month, ts1.day, ts1.hour, ts1.minute, ts1.second)
if ts1 is not None else None)
_trig, _why, ev.triggered_by = _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,
year=_trig.year, unknown_byte=0, month=_trig.month, day=_trig.day,
hour=_trig.hour, minute=_trig.minute, second=_trig.second,
)
elif ts1 is not None:
ev.timestamp = Timestamp(
raw=footer[2:10],
flag=0x10,
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 = _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
# Event so the .h5 writer persists them device-agnostically.
from minimateplus.sensor_check import decode_sensor_check
ev.sensor_check = decode_sensor_check(raw) or None
# Only compute peaks from samples when we actually have samples.
# For events the codec couldn't decode (histogram-mode bodies, until
# the §7.6.2 histogram codec is wired in), samples is an empty dict
# and ``_peaks_from_samples`` would return PeakValues(0, 0, 0, 0, 0).
# That would then OVERWRITE existing good DB peak values (e.g. from
# paired BW ASCII reports) during the backfill UPSERT path.
# Leaving peak_values=None signals "we don't know" to downstream
# consumers; the backfill script seeds from the DB row when it sees
# None, and ``apply_report_to_event`` overlays from a paired ASCII
# report when one is supplied.
has_samples = any(samples.get(ch) for ch in ("Tran", "Vert", "Long", "MicL"))
# The geophone full scale is the file's range; Normal when it wasn't read.
geo_fs = _GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS)
ev.peak_values = _peaks_from_samples(samples, geo_fs) if has_samples else None
ev.stop_time = ts2
if hist_records:
# A histogram stores each interval's vector sum (squared), and each
# channel's half-period: Blastware's per-interval Geo PVS (771,354 /
# 771,354 DL2 cells) and frequency, (sample rate / 2) / half-period.
unit_ins = _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS
ev.interval_pvs = [math.sqrt(r["pvs_sq"]) * unit_ins for r in hist_records]
ev.interval_half_periods = {
ch: [r[key] for r in hist_records if r[key] is not None]
for ch, key in (("Tran", "t_halfp"), ("Vert", "v_halfp"),
("Long", "l_halfp"), ("MicL", "m_halfp"))}
if not ev.interval_half_periods["MicL"]:
del ev.interval_half_periods["MicL"]
k = _setup_name_at(raw)
if k is not None and k >= _INTERVAL_BEFORE_NAME:
ev.histogram_interval_sec = int.from_bytes(
raw[k - _INTERVAL_BEFORE_NAME:k - _INTERVAL_BEFORE_NAME + 2], "big") or None
if not is_waveform_body and ev.peak_values is not None and ev.interval_pvs:
# The event's vector sum is the largest interval's. Combining the
# channel peaks instead read high on 86% of DL2's histograms -- they
# can come from different moments.
ev.peak_values.peak_vector_sum = max(ev.interval_pvs)
ev._a5_frames = None # not recoverable from BW file
return ev