Three causes behind the histograms the checker found decoding wrongly: 1. The file decoder tried the waveform codec first, whatever the record type. It accepted BE9440 / BE9557 / BE17354's 2018 5 s histograms and returned ~5x too many 'samples' (K440HDXX.XH0H: SFM 44,504, Blastware 6,976). The codec now follows STRT[18] (0x46 / 0x0A on 70,041 / 70,041 DL2 files); only an unknown type falls back to trial order, and a chosen codec that fails is a decode problem rather than a silent switch. 2. The sub-minute layout check required each record's 'zero word' to be 0000. It is the high word of the interval's PVS squared, non-zero above 1.28 in/s, so a one-block histogram with a loud interval was not recognised (T193KR5M.X90H, K440HA3C.JM0H, R352HFZ7.530H decoded to nothing). The check is now the measured relation peak <= PVS <= sqrt(3) * peak, which holds on 34,502,955 / 34,502,955 DL2 sub-minute intervals. The no-terminal-tail trim uses the same test. Two test builders wrote PVS bytes no real record has (one still in the retracted little-endian layout); they now write peak^2 in the measured layout, and the retraction test keeps a legacy builder of its own. 3. Checker carve-out interval-count-is-duration: Blastware's Number of Intervals is (stop - start) / interval from the footer times, and its own interval table lists one block fewer when the unit never wrote the last minute. SFM matches the table (T193KSWP.FF0H: 2,880 vs 2,850). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
1329 lines
57 KiB
Python
1329 lines
57 KiB
Python
"""
|
||
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 os
|
||
import re
|
||
import struct
|
||
from pathlib import Path
|
||
from typing import Optional, Union
|
||
|
||
from .models import 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 decode_histogram_body, interval_pvs
|
||
|
||
# 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
|
||
_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-
|
||
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}"
|
||
|
||
|
||
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 0e 08 + plausible-year footer signature can occur inside the sample
|
||
# stream. Collect every candidate and prefer the first whose body yields a
|
||
# waveform record chain terminating on the 0x06 marker; fall back to the
|
||
# first candidate otherwise. Blast radius measured 2026-08-25: changes the
|
||
# chosen footer on exactly 1 of 1,388 series-3 waveform files
|
||
# (BE17353/S353L4O5.OX0W, false positive at 3800, real footer at 8576).
|
||
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]")
|
||
if record_type == "Histogram":
|
||
decoded = decode_histogram_body(body)
|
||
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:
|
||
decoded = decode_histogram_body(body)
|
||
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")
|
||
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 = _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
|
||
if not is_waveform_body and ev.peak_values is not None:
|
||
# A histogram stores each interval's vector sum (squared); the event's
|
||
# is the largest. Combining the channel peaks instead read high on 86%
|
||
# of DL2's histograms -- they can come from different moments.
|
||
pvs = interval_pvs(body)
|
||
if pvs:
|
||
ev.peak_values.peak_vector_sum = (
|
||
max(pvs) * _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS)
|
||
ev._a5_frames = None # not recoverable from BW file
|
||
|
||
return ev
|