Compare commits
9
Commits
v0.32.0
...
29c8e2b034
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29c8e2b034 | ||
|
|
42fe35f3b3 | ||
|
|
6def0d1f41 | ||
|
|
f46afafdb4 | ||
|
|
b4706a30f0 | ||
|
|
a8c91809a6 | ||
|
|
184a03a5cd | ||
|
|
560869ed61 | ||
|
|
b69ff4171d |
No files matched your search
+1
-1
@@ -6,7 +6,7 @@
|
|||||||
/bridges/s3-bridge/*.bin
|
/bridges/s3-bridge/*.bin
|
||||||
/bridges/s3-bridge/*.log
|
/bridges/s3-bridge/*.log
|
||||||
/bridges/s3-bridge/*.set
|
/bridges/s3-bridge/*.set
|
||||||
/example-events/
|
/example-events
|
||||||
/tests/fixtures/
|
/tests/fixtures/
|
||||||
/manuals/
|
/manuals/
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,65 @@ All notable changes to seismo-relay are documented here.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Unreleased
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **A Blastware event imported without its ASCII report now carries its
|
||||||
|
setup and notes (#44, #45).** Until now such an event stored no sample
|
||||||
|
rate, a record time of "70 s" (the STRT record-type byte, 0x46), a
|
||||||
|
pre-trigger and sample count read from STRT bytes that are neither, and
|
||||||
|
blank project / client / operator / location (the reader stopped at the
|
||||||
|
NUL after each label). All of DL2's 2016–2024 events arrive this way.
|
||||||
|
- The recording-setup block is found by structure (`1c 08`, the setup
|
||||||
|
name, NUL), not by the name "Standard Recording Setup", which 37% of
|
||||||
|
DL2's files do not use.
|
||||||
|
- Sample rate, pre-trigger and record time come from that block; a
|
||||||
|
waveform's sample count is the decoded count. A histogram gets a
|
||||||
|
sample rate only: Blastware reports no record time or pre-trigger for
|
||||||
|
one.
|
||||||
|
- The setup name and the four notes are read by position, as the ASCII
|
||||||
|
parser does: their labels are operator-editable.
|
||||||
|
- Verified against Blastware's own `_XML.XML` reports for the 70,042 DL2
|
||||||
|
events that have one (2016–2026): sample rate 70,042/70,042, record
|
||||||
|
time 6,524/6,524, pre-trigger 6,484/6,484, notes 70,042/70,042, sample
|
||||||
|
count 6,523/6,524 (one waveform the decoder ends 3 samples short —
|
||||||
|
separate).
|
||||||
|
- Events imported with an ASCII report are unchanged: the report still
|
||||||
|
overlays. Not yet read: the job number (2,997 archive events carry
|
||||||
|
one). The waveform-time estimate still finds the record time by the
|
||||||
|
name, pending a measurement. The Micromate half of #44/#45 (SFM's own
|
||||||
|
downloads, no report) stays with the parity branch.
|
||||||
|
- ⚠ **Codec change: bump `TOOL_VERSION` at release** and run
|
||||||
|
`backfill_sidecars.py` then `backfill_event_shape.py` on prod (~2 h on
|
||||||
|
the NAS) so stored report-less events pick the fields up. No schema
|
||||||
|
change, no migration.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **`scratch/verify_bw_fields_against_xml.py`** checks the fields SFM reads
|
||||||
|
from a Blastware file alone against the event's `_XML.XML` report — the
|
||||||
|
first piece of the decode checker. DL2's `Sent/` holds those reports,
|
||||||
|
every sample included, for 70,042 events back to 2016; its ASCII reports
|
||||||
|
only go back to 2025.
|
||||||
|
- **README roadmap:** a bulk event importer, parked.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **`CLAUDE.md`:** the 14,338 ASCII-report pairs were said to reach "back
|
||||||
|
to 2018"; they are all 2025–26 events. Corrected in place.
|
||||||
|
- **The SFM / SDM tier model in `CLAUDE.md` is marked superseded** by
|
||||||
|
Terra-View's ADR 0003 (`docs/adr/0003-stack-components-and-names.md`).
|
||||||
|
- SFM is the whole seismograph module, and "SDM" is retired as a name.
|
||||||
|
- The codec library stays pure.
|
||||||
|
- Lab tools (`bridges/` bench tools, `scratch/`, `seismo_lab.py`) are to
|
||||||
|
leave the production image, and are ported into `sfm/` when they become
|
||||||
|
production tools.
|
||||||
|
- The call-in server becomes SFM's front door after a staged proof.
|
||||||
|
- The repo becomes `sfm` after `feat/series4-sfm-parity` merges.
|
||||||
|
|
||||||
|
The old section stays below the banner as history.
|
||||||
|
Docs only: no code or schema change, no migration, `TOOL_VERSION` unchanged.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## v0.32.0 — 2026-10-27
|
## v0.32.0 — 2026-10-27
|
||||||
|
|
||||||
**Event times you can trust, and Series 4 mapped end to end.** Two threads.
|
**Event times you can trust, and Series 4 mapped end to end.** Two threads.
|
||||||
|
|||||||
@@ -129,7 +129,13 @@ Read this first when picking the project back up.
|
|||||||
- **Series-3 decode is verified per-sample at scale (v0.27.0).** The full DL2
|
- **Series-3 decode is verified per-sample at scale (v0.27.0).** The full DL2
|
||||||
archive decodes **14,338 / 14,338** paired files exactly against their
|
archive decodes **14,338 / 14,338** paired files exactly against their
|
||||||
preserved Blastware ASCII exports — 1,249 waveform + 13,089 histogram, 45
|
preserved Blastware ASCII exports — 1,249 waveform + 13,089 histogram, 45
|
||||||
units, files back to 2018. That is 11x the ground truth the prod store
|
units, files back to 2018. ⚠ **Corrected 2026-10-29:** the 14,338 pairs
|
||||||
|
are all events from 2025–26 (five more carry a 1995 clock); DL2 kept ASCII
|
||||||
|
reports only from 2025. 🔑 Its `Sent/<stem>_<ext>_XML.XML` files are
|
||||||
|
Blastware's full event report — every report field plus every sample —
|
||||||
|
for **70,042 events back to 2016**, local copy `~/dl2-archive/xml`.
|
||||||
|
`scratch/verify_bw_fields_against_xml.py` checks file-only fields against
|
||||||
|
them. That is 11x the ground truth the prod store
|
||||||
carried, and it supersedes the old "per-sample on 11%, peak-only on 89%"
|
carried, and it supersedes the old "per-sample on 11%, peak-only on 89%"
|
||||||
caveat. Harness: `scratch/verify_against_ascii.py` (note its saturation
|
caveat. Harness: `scratch/verify_against_ascii.py` (note its saturation
|
||||||
carve-out — BW clamps clipped events, the decoder reports true counts).
|
carve-out — BW clamps clipped events, the decoder reports true counts).
|
||||||
@@ -276,6 +282,26 @@ dedicated release commit when you are ready to ship to `main`.**
|
|||||||
|
|
||||||
## Architecture: three-tier conceptual model
|
## Architecture: three-tier conceptual model
|
||||||
|
|
||||||
|
> ⚠ **SUPERSEDED 2026-10-27 by Terra-View's
|
||||||
|
> [`docs/adr/0003-stack-components-and-names.md`](../terra-view/docs/adr/0003-stack-components-and-names.md).**
|
||||||
|
> The SFM / SDM split below is retired.
|
||||||
|
> - **SFM is the whole seismograph module:** the call-in server, the adapters,
|
||||||
|
> decoding, the store, per-event measurements and the API. "SDM" is not
|
||||||
|
> used as a name any more.
|
||||||
|
> - **The codec library stays pure**, as described in tier 3. That rule
|
||||||
|
> survives unchanged.
|
||||||
|
> - **Lab tools** (`bridges/` bench tools, `scratch/`, `seismo_lab.py`) are
|
||||||
|
> experimental and are to leave the production image. One that becomes a
|
||||||
|
> real production tool is *ported* into `sfm/`, rebuilt on
|
||||||
|
> `sfm/device_access`.
|
||||||
|
> - **The call-in server** (today's `bridges/ach_server.py` and
|
||||||
|
> `bridges/mm_ach_server.py`) becomes SFM's front door, after the staged
|
||||||
|
> proof in the ADR.
|
||||||
|
> - **The repo becomes `sfm`** after `feat/series4-sfm-parity` merges.
|
||||||
|
>
|
||||||
|
> The text below is history, kept in place per this repo's retraction
|
||||||
|
> convention.
|
||||||
|
|
||||||
seismo-relay is a **suite of cooperating components**, not a single app.
|
seismo-relay is a **suite of cooperating components**, not a single app.
|
||||||
The three tiers below are the canonical mental model — the current
|
The three tiers below are the canonical mental model — the current
|
||||||
directory layout doesn't fully reflect them yet (some of what is
|
directory layout doesn't fully reflect them yet (some of what is
|
||||||
|
|||||||
@@ -616,6 +616,8 @@ Implementation steps (concrete):
|
|||||||
|
|
||||||
### Ingestion gaps
|
### Ingestion gaps
|
||||||
|
|
||||||
|
- [ ] **Event importer (parked 2026-10-29).** A way to load a folder of event files from disk into SFM in bulk — a historical archive, a laptop's Blastware folder, a backup — without routing them through a watcher. It is one of the four ways events should reach SFM (watcher forward, upload from disk, SFM's own serial/modem download, SFM's future call-in server). Prompted by DL2's 2016–2024 backfill, which the watcher could only drip-feed at 500 events a pass.
|
||||||
|
|
||||||
- [ ] **MLG forwarding.** `series3-watcher` forwards event binaries + their `_ASCII.TXT` reports, but skips `.MLG` per-unit monitor log files entirely. Adding an `POST /db/import/mlg_file` endpoint + watcher scan path would populate `monitor_log` for non-ACH-routed units (coverage queries, "was this unit monitoring on date X" lookups).
|
- [ ] **MLG forwarding.** `series3-watcher` forwards event binaries + their `_ASCII.TXT` reports, but skips `.MLG` per-unit monitor log files entirely. Adding an `POST /db/import/mlg_file` endpoint + watcher scan path would populate `monitor_log` for non-ACH-routed units (coverage queries, "was this unit monitoring on date X" lookups).
|
||||||
- [ ] **0C-record raw bytes persistence in the sidecar.** Currently on branch `claude/codec-re-cBGNe` as commit `a187124`; cherry-pick if useful as a standalone fix. Preserves the 210-byte 0C record under `extensions.raw_records.waveform_record_b64` so future field-offset analysis (Peak Acceleration / Time of Peak / etc. — the fields BW computes client-side from samples) can run offline.
|
- [ ] **0C-record raw bytes persistence in the sidecar.** Currently on branch `claude/codec-re-cBGNe` as commit `a187124`; cherry-pick if useful as a standalone fix. Preserves the 210-byte 0C record under `extensions.raw_records.waveform_record_b64` so future field-offset analysis (Peak Acceleration / Time of Peak / etc. — the fields BW computes client-side from samples) can run offline.
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import hashlib
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import struct
|
import struct
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, Union
|
from typing import Optional, Union
|
||||||
@@ -712,35 +713,16 @@ _MIC_FS_PSI = 0.0125 / _INT16_FS # ~0.5 psi full-scale assumption
|
|||||||
|
|
||||||
def _decode_strt(strt: bytes) -> dict:
|
def _decode_strt(strt: bytes) -> dict:
|
||||||
"""
|
"""
|
||||||
Decode the 21-byte STRT record from a BW file.
|
Decode the 21-byte STRT record from a BW file: the waveform key (4B).
|
||||||
|
|
||||||
Returns dict with waveform_key (4B), total_samples, pretrig_samples,
|
The record holds no setup fields. It was once read as total samples
|
||||||
rectime_seconds. Falls back to None on truncated/missing fields.
|
([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":
|
if len(strt) < 21 or strt[0:4] != b"STRT":
|
||||||
return {}
|
return {}
|
||||||
return {
|
return {"waveform_key": strt[6:10].hex()}
|
||||||
"waveform_key": strt[6:10].hex(),
|
|
||||||
"total_samples": struct.unpack_from(">H", strt, 8)[0],
|
|
||||||
"pretrig_samples": struct.unpack_from(">H", strt, 16)[0],
|
|
||||||
"rectime_seconds": strt[18],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _find_first_string(buf: bytes, label: bytes, max_len: int = 256) -> Optional[str]:
|
|
||||||
"""
|
|
||||||
Search `buf` for `label` (e.g. b"Project:") and return the
|
|
||||||
null-terminated ASCII string that follows, stripped.
|
|
||||||
"""
|
|
||||||
pos = buf.find(label)
|
|
||||||
if pos < 0:
|
|
||||||
return None
|
|
||||||
start = pos + len(label)
|
|
||||||
end = buf.find(b"\x00", start, start + max_len)
|
|
||||||
if end < 0:
|
|
||||||
end = start + max_len
|
|
||||||
text = buf[start:end].decode("ascii", errors="replace").strip()
|
|
||||||
return text or None
|
|
||||||
|
|
||||||
|
|
||||||
def _decode_samples_4ch_int16_le(stream: bytes) -> dict[str, list[int]]:
|
def _decode_samples_4ch_int16_le(stream: bytes) -> dict[str, list[int]]:
|
||||||
@@ -855,6 +837,21 @@ def derive_record_type_from_filename(filename, default: str = "Waveform") -> str
|
|||||||
_RECSETUP_MARKER = b"Standard Recording Setup"
|
_RECSETUP_MARKER = b"Standard Recording Setup"
|
||||||
_RECTIME_OFFSET_BEFORE_MARKER = 30
|
_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
|
# 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
|
# Blastware therefore copies into every waveform file (measured 2026-10-26; see
|
||||||
# the Series-III reference, "The embedded event record"):
|
# the Series-III reference, "The embedded event record"):
|
||||||
@@ -934,6 +931,60 @@ def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
|
|||||||
return rt if 0.05 <= rt <= 600.0 else 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]
|
||||||
|
return ProjectInfo(setup_name=text[0], project=project, client=client,
|
||||||
|
operator=operator, sensor_location=location)
|
||||||
|
|
||||||
|
|
||||||
def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event:
|
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
|
"""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)."""
|
bytes, `name` defaulting to the file's own (see there -- never a time source)."""
|
||||||
@@ -950,13 +1001,15 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
|||||||
receives straight from a unit has no Blastware name.
|
receives straight from a unit has no Blastware name.
|
||||||
|
|
||||||
Recovers:
|
Recovers:
|
||||||
- waveform_key, rectime_seconds, total_samples, pretrig_samples
|
- waveform_key (from the STRT record)
|
||||||
(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: a waveform's from the instrument's embedded event record
|
||||||
(`timestamp_source` "event_record"); without a validated one, an
|
(`timestamp_source` "event_record"); without a validated one, an
|
||||||
estimate from the footer with a `decode_problems` entry; a histogram's
|
estimate from the footer with a `decode_problems` entry; a histogram's
|
||||||
from the footer start ("footer")
|
from the footer start ("footer")
|
||||||
- project_info (from ASCII labels embedded in the body)
|
- project_info: setup name and the four user notes, by position
|
||||||
- raw_samples (Tran/Vert/Long/MicL int16 lists)
|
- raw_samples (Tran/Vert/Long/MicL int16 lists)
|
||||||
- peak_values (computed from raw_samples; approximate — see notes
|
- peak_values (computed from raw_samples; approximate — see notes
|
||||||
on _peaks_from_samples about Normal-range assumption)
|
on _peaks_from_samples about Normal-range assumption)
|
||||||
@@ -1071,12 +1124,6 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
|||||||
else:
|
else:
|
||||||
samples = decoded_to_adc_counts(decoded)
|
samples = decoded_to_adc_counts(decoded)
|
||||||
|
|
||||||
# Metadata strings (label-anchored search across the body).
|
|
||||||
project = _find_first_string(body, b"Project:")
|
|
||||||
client = _find_first_string(body, b"Client:")
|
|
||||||
user = _find_first_string(body, b"User Name:")
|
|
||||||
seisloc = _find_first_string(body, b"Seis Loc:")
|
|
||||||
|
|
||||||
# Build the Event.
|
# Build the Event.
|
||||||
ev = Event(index=-1)
|
ev = Event(index=-1)
|
||||||
if strt_fields.get("waveform_key"):
|
if strt_fields.get("waveform_key"):
|
||||||
@@ -1087,9 +1134,22 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
|||||||
# caller overrides ev.record_type using the original filename — see
|
# caller overrides ev.record_type using the original filename — see
|
||||||
# waveform_store.save_imported_bw.
|
# waveform_store.save_imported_bw.
|
||||||
ev.record_type = derive_record_type_from_filename(name)
|
ev.record_type = derive_record_type_from_filename(name)
|
||||||
ev.rectime_seconds = strt_fields.get("rectime_seconds")
|
|
||||||
ev.total_samples = strt_fields.get("total_samples")
|
# Setup fields come from the recording-setup block (#44/#45), not the STRT
|
||||||
ev.pretrig_samples = strt_fields.get("pretrig_samples")
|
# record: STRT[18] is the record-type marker (0x46 / 0x0A), which is why
|
||||||
|
# every waveform used to read "70 s". A histogram has no record time or
|
||||||
|
# pre-trigger -- Blastware reports neither.
|
||||||
|
ev.sample_rate = _setup_sample_rate(raw)
|
||||||
|
if is_waveform_body:
|
||||||
|
ev.rectime_seconds = _setup_record_time(raw)
|
||||||
|
ev.total_samples = len(samples["Tran"]) or None
|
||||||
|
pre = _setup_pretrigger(raw)
|
||||||
|
if pre is not None and ev.sample_rate:
|
||||||
|
ev.pretrig_samples = round(-pre * ev.sample_rate)
|
||||||
|
if None in (ev.sample_rate, ev.rectime_seconds, ev.pretrig_samples):
|
||||||
|
ev.decode_problems.append(
|
||||||
|
f"recording-setup block incomplete: sample rate {ev.sample_rate}, "
|
||||||
|
f"record time {ev.rectime_seconds}, pre-trigger {pre}")
|
||||||
|
|
||||||
# Event timestamp. The footer's two timestamps mean different things by
|
# Event timestamp. The footer's two timestamps mean different things by
|
||||||
# record type:
|
# record type:
|
||||||
@@ -1150,9 +1210,7 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
|||||||
)
|
)
|
||||||
ev.timestamp_source = "footer"
|
ev.timestamp_source = "footer"
|
||||||
|
|
||||||
ev.project_info = ProjectInfo(
|
ev.project_info = _setup_notes(raw)
|
||||||
project=project, client=client, operator=user, sensor_location=seisloc,
|
|
||||||
)
|
|
||||||
ev.raw_samples = samples
|
ev.raw_samples = samples
|
||||||
# Sensor self-check traces from the binary's trailing block (waveform
|
# Sensor self-check traces from the binary's trailing block (waveform
|
||||||
# events only; returns {} for histograms / when absent). Carried on the
|
# events only; returns {} for histograms / when absent). Carried on the
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
"""
|
||||||
|
Check the setup and note fields SFM reads from a Blastware event file alone
|
||||||
|
(#44/#45) against Blastware's own `_XML.XML` event report.
|
||||||
|
|
||||||
|
python scratch/verify_bw_fields_against_xml.py <binaries dir> <xml dir> [--jobs N]
|
||||||
|
|
||||||
|
Fields: sample rate; for waveforms, record time, pre-trigger (at the 3
|
||||||
|
decimals Blastware prints) and the sample count (the XML's row count); the
|
||||||
|
four user notes, in order. Notes are compared as the ordered list of
|
||||||
|
non-empty values, because Blastware's XML names each one after its label
|
||||||
|
("<Project>", "<Location>", ...), which the operator can change.
|
||||||
|
|
||||||
|
Any disagreement is reported as SFM's -- there is no carve-out list yet.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import collections
|
||||||
|
import html
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
from minimateplus.event_file_io import read_blastware_file # noqa: E402
|
||||||
|
|
||||||
|
_BIN = re.compile(r"^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$", re.I)
|
||||||
|
_EPOCH = datetime(1985, 1, 1)
|
||||||
|
_SIMPLE = re.compile(rb"<([A-Za-z][\w.]*)>([^<]*)</\1>")
|
||||||
|
|
||||||
|
|
||||||
|
def _event_year(name: str) -> int:
|
||||||
|
stem, ext = name.upper().split(".")
|
||||||
|
return (_EPOCH + timedelta(seconds=int(stem[4:8], 36) * 1296 + int(ext[:2], 36))).year
|
||||||
|
|
||||||
|
|
||||||
|
def _xml_fields(xml: bytes) -> dict:
|
||||||
|
head = xml[: xml.find(b"<WaveformDataChannels>") if b"<WaveformDataChannels>" in xml
|
||||||
|
else xml.find(b"<HistogramData>")]
|
||||||
|
out: dict = {}
|
||||||
|
m = re.search(rb"<SampleRate>(\d+) sps</SampleRate>", head)
|
||||||
|
out["sample_rate"] = int(m.group(1)) if m else None
|
||||||
|
m = re.search(rb"<RecordTime>([\d.]+)", head)
|
||||||
|
out["record_time"] = float(m.group(1)) if m else None
|
||||||
|
m = re.search(rb"<Pre-triggerLength>(-?[\d.]+)", head)
|
||||||
|
out["pretrig_s"] = float(m.group(1)) if m else None
|
||||||
|
out["rows"] = xml.count(b"<Row>") if b"<WaveformDataChannels>" in xml else None
|
||||||
|
# The notes sit between the top-level <Units> and <GeoRange>.
|
||||||
|
u = head.find(b"</Units>")
|
||||||
|
g = head.find(b"<GeoRange>")
|
||||||
|
notes, out["job_number"] = [], None
|
||||||
|
if u >= 0 and g > u:
|
||||||
|
for tag, val in _SIMPLE.findall(head[u + len(b"</Units>"):g]):
|
||||||
|
v = html.unescape(val.decode("utf-8", "replace")).strip()
|
||||||
|
if tag == b"JobNumber": # its own field, not a note
|
||||||
|
out["job_number"] = v
|
||||||
|
elif v:
|
||||||
|
notes.append(v)
|
||||||
|
out["notes"] = notes
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _check(args) -> list:
|
||||||
|
name, bin_path, xml_path = args
|
||||||
|
logging.disable(logging.CRITICAL)
|
||||||
|
rows = []
|
||||||
|
try:
|
||||||
|
ev = read_blastware_file(bin_path)
|
||||||
|
x = _xml_fields(Path(xml_path).read_bytes())
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return [(name, "decode", "error", repr(exc)[:120], None)]
|
||||||
|
kind = name[-1].upper()
|
||||||
|
sr = ev.sample_rate
|
||||||
|
|
||||||
|
def put(field, want, got, ok):
|
||||||
|
rows.append((name, field, "match" if ok else ("SFM blank" if got is None else "MISMATCH"),
|
||||||
|
want, got))
|
||||||
|
|
||||||
|
if x["sample_rate"] is not None:
|
||||||
|
put("sample_rate", x["sample_rate"], sr, sr == x["sample_rate"])
|
||||||
|
if kind == "W":
|
||||||
|
if x["record_time"] is not None:
|
||||||
|
rt = ev.rectime_seconds
|
||||||
|
put("record_time", x["record_time"], rt,
|
||||||
|
rt is not None and abs(rt - x["record_time"]) < 1e-4)
|
||||||
|
if x["pretrig_s"] is not None:
|
||||||
|
# Blastware prints 3 decimals, rounding halves away from zero
|
||||||
|
# (-0.0625 s -> -0.063), so half a unit either way is a match.
|
||||||
|
got = (-ev.pretrig_samples / sr
|
||||||
|
if ev.pretrig_samples is not None and sr else None)
|
||||||
|
put("pretrig", x["pretrig_s"], got,
|
||||||
|
got is not None and abs(got - x["pretrig_s"]) <= 5e-4 + 1e-9)
|
||||||
|
if x["rows"]:
|
||||||
|
put("samples", x["rows"], ev.total_samples, ev.total_samples == x["rows"])
|
||||||
|
pi = ev.project_info
|
||||||
|
got = [v for v in (pi.project, pi.client, pi.operator, pi.sensor_location) if v]
|
||||||
|
put("notes", x["notes"], got, got == x["notes"])
|
||||||
|
if x["job_number"] is not None:
|
||||||
|
jn = getattr(pi, "job_number", None)
|
||||||
|
put("job_number", x["job_number"], jn, jn is not None and str(jn) == x["job_number"])
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("bin_dir")
|
||||||
|
ap.add_argument("xml_dir")
|
||||||
|
ap.add_argument("--jobs", type=int, default=os.cpu_count())
|
||||||
|
a = ap.parse_args()
|
||||||
|
|
||||||
|
xmls = {f.upper(): os.path.join(a.xml_dir, f) for f in os.listdir(a.xml_dir)}
|
||||||
|
work, seen = [], set()
|
||||||
|
for root, _, files in os.walk(a.bin_dir):
|
||||||
|
for f in files:
|
||||||
|
if not _BIN.match(f) or f.upper() in seen:
|
||||||
|
continue
|
||||||
|
seen.add(f.upper())
|
||||||
|
x = xmls.get(f.upper().replace(".", "_") + "_XML.XML")
|
||||||
|
if x:
|
||||||
|
work.append((f, os.path.join(root, f), x))
|
||||||
|
print(f"{len(seen)} event files, {len(work)} with an XML report")
|
||||||
|
|
||||||
|
tally = collections.Counter()
|
||||||
|
examples = collections.defaultdict(list)
|
||||||
|
with ProcessPoolExecutor(a.jobs) as pool:
|
||||||
|
for rows in pool.map(_check, work, chunksize=64):
|
||||||
|
for name, field, verdict, want, got in rows:
|
||||||
|
yr = _event_year(name) if field != "decode" else 0
|
||||||
|
tally[(field, name[-1].upper(), verdict)] += 1
|
||||||
|
tally[(field, yr, verdict)] += 1
|
||||||
|
if verdict != "match" and len(examples[(field, verdict)]) < 8:
|
||||||
|
examples[(field, verdict)].append((name, want, got))
|
||||||
|
|
||||||
|
fields = ("sample_rate", "record_time", "pretrig", "samples", "notes", "job_number", "decode")
|
||||||
|
print("\nfield type match mismatch SFM-blank error")
|
||||||
|
for f in fields:
|
||||||
|
for t in ("W", "H"):
|
||||||
|
m, mm, b, e = (tally[(f, t, v)] for v in ("match", "MISMATCH", "SFM blank", "error"))
|
||||||
|
if m + mm + b + e:
|
||||||
|
print(f"{f:12s} {t:4s} {m:6d} {mm:9d} {b:10d} {e:6d}")
|
||||||
|
years = sorted({k[1] for k in tally if isinstance(k[1], int) and k[1]})
|
||||||
|
print("\nnot matching, by event year:")
|
||||||
|
for f in fields[:-1]:
|
||||||
|
bad = {y: tally[(f, y, "MISMATCH")] + tally[(f, y, "SFM blank")] for y in years}
|
||||||
|
if any(bad.values()):
|
||||||
|
print(f" {f:12s} " + " ".join(f"{y}:{n}" for y, n in bad.items() if n))
|
||||||
|
for (f, v), ex in sorted(examples.items()):
|
||||||
|
print(f"\n{f} -- {v}:")
|
||||||
|
for name, want, got in ex:
|
||||||
|
print(f" {name}: Blastware {want!r} SFM {got!r}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,113 @@
|
|||||||
|
"""
|
||||||
|
Setup and note fields read from a Blastware event file alone (#44, #45).
|
||||||
|
|
||||||
|
Every expected value below comes from Blastware's own output for the same
|
||||||
|
file -- its ASCII report or its `_XML.XML` event report -- or, for the bench
|
||||||
|
file with neither, from the record length and the MiniMate Plus spec, as
|
||||||
|
written up in #44/#45. None is derived from the decoder under test.
|
||||||
|
|
||||||
|
The STRT record's bytes are not these fields: STRT[18] is the record-type
|
||||||
|
marker (0x46 waveform, 0x0A histogram), which is why every waveform used to
|
||||||
|
read "70 s".
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from minimateplus.event_file_io import read_blastware_file
|
||||||
|
|
||||||
|
_FIX = Path(__file__).resolve().parent / "fixtures"
|
||||||
|
|
||||||
|
# (file, sample rate, record time s, pre-trigger samples, total samples)
|
||||||
|
_WAVEFORMS = [
|
||||||
|
# ASCII report: 1024 sps, 3.0 s, -0.25 s; 3328 samples per channel.
|
||||||
|
("5-11-26/M529LL1A.SP0", 1024, 3.0, 256, 3328),
|
||||||
|
# ASCII report: 1024 sps, 1.0 s, -0.25 s.
|
||||||
|
("decode-re-5-8-26/event-c/M529LK44.AB0", 1024, 1.0, 256, 1280),
|
||||||
|
# #44/#45: BE9441 bench at 4096 sps, 5 s, 0.25 s -> 21,504 samples.
|
||||||
|
("minimate-bench-10-26-26-blastware/blastware/K441LTOF.ZI0", 4096, 5.0, 1024, 21504),
|
||||||
|
# XML: setup "BE16352.set", 1024 sps, 1.0 s, -0.247 s, 1277 sample rows.
|
||||||
|
("bw-import-fields-10-29-26/R352HIUI.F40W", 1024, 1.0, 253, 1277),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("rel,sr,rt,pretrig,total", _WAVEFORMS)
|
||||||
|
def test_waveform_setup_fields_come_from_the_file(rel, sr, rt, pretrig, total):
|
||||||
|
ev = read_blastware_file(_FIX / rel)
|
||||||
|
assert ev.sample_rate == sr
|
||||||
|
assert ev.rectime_seconds == pytest.approx(rt)
|
||||||
|
assert ev.pretrig_samples == pretrig
|
||||||
|
assert ev.total_samples == total
|
||||||
|
|
||||||
|
|
||||||
|
# (file, sample rate) -- ASCII report / XML
|
||||||
|
_HISTOGRAMS = [
|
||||||
|
("histogram-mic-off-10-26-26/K441LTOK.QZ0", 2048),
|
||||||
|
("ts-fix/K441LKZU.C30H", 1024),
|
||||||
|
("bw-import-fields-10-29-26/M529L4XQ.R30H", 1024),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("rel,sr", _HISTOGRAMS)
|
||||||
|
def test_histogram_sample_rate_comes_from_the_file(rel, sr):
|
||||||
|
ev = read_blastware_file(_FIX / rel)
|
||||||
|
assert ev.sample_rate == sr
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("rel,sr", _HISTOGRAMS)
|
||||||
|
def test_histogram_has_no_record_time_or_pretrigger(rel, sr):
|
||||||
|
# Blastware reports neither for a histogram; the STRT record-type byte
|
||||||
|
# (0x0A = 10) is not a record time.
|
||||||
|
ev = read_blastware_file(_FIX / rel)
|
||||||
|
assert ev.rectime_seconds is None
|
||||||
|
assert ev.pretrig_samples is None
|
||||||
|
|
||||||
|
|
||||||
|
# (file, setup name, project, client, operator, sensor location)
|
||||||
|
_NOTES = [
|
||||||
|
# ASCII report; default labels, location spelled "Seis Loc:".
|
||||||
|
("5-11-26/M529LL1A.SP0", "Standard Recording Setup",
|
||||||
|
"Test-5-8-26", "New Client", "Terra-Mechanics - Harrison", "Still Catbed."),
|
||||||
|
# ASCII report; location spelled "Seis. Loc:". BE9441's bench setup is
|
||||||
|
# saved as "Standard Recording Setup.set" (#45).
|
||||||
|
("histogram-mic-off-10-26-26/K441LTOK.QZ0", "Standard Recording Setup.set",
|
||||||
|
"TestUnit-Minimate", "Terra-Mechanics", "Terra-Mechanics Inc. - Harrison", "Test unit 1"),
|
||||||
|
# XML; a setup not named "Standard Recording Setup".
|
||||||
|
("bw-import-fields-10-29-26/R352HIUI.F40W", "BE16352.set",
|
||||||
|
"JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV",
|
||||||
|
"Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"),
|
||||||
|
# XML (<Location>Test Loc</Location> only); the operator relabelled the
|
||||||
|
# four note slots "Location:", "Client:", "User Name:", "General:" and
|
||||||
|
# filled in only the first. Slots are positional, as in the ASCII parser.
|
||||||
|
("bw-import-fields-10-29-26/M529L4XQ.R30H", "Standard Recording Setup",
|
||||||
|
"Test Loc", None, None, None),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("rel,setup,project,client,operator,location", _NOTES)
|
||||||
|
def test_notes_come_from_the_file_by_position(rel, setup, project, client, operator, location):
|
||||||
|
pi = read_blastware_file(_FIX / rel).project_info
|
||||||
|
assert pi.setup_name == setup
|
||||||
|
assert pi.project == project
|
||||||
|
assert pi.client == client
|
||||||
|
assert pi.operator == operator
|
||||||
|
assert pi.sensor_location == location
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_without_a_report_stores_the_file_fields(tmp_path: Path):
|
||||||
|
"""The watcher path with no ASCII report: the sidecar carries what the
|
||||||
|
file holds, not blanks and not the STRT bytes."""
|
||||||
|
from sfm.waveform_store import WaveformStore
|
||||||
|
|
||||||
|
src = _FIX / "bw-import-fields-10-29-26/R352HIUI.F40W"
|
||||||
|
store = WaveformStore(tmp_path / "waveforms")
|
||||||
|
store.save_imported_bw(src.read_bytes(), source_path=src)
|
||||||
|
|
||||||
|
sc = store.load_sidecar("BE16352", src.name)
|
||||||
|
assert sc["event"]["sample_rate"] == 1024
|
||||||
|
assert sc["event"]["rectime_seconds"] == pytest.approx(1.0)
|
||||||
|
assert sc["event"]["pretrig_samples"] == 253
|
||||||
|
assert sc["project_info"]["project"] == "JV 241 - 1425 Spanlers Mill Rad"
|
||||||
|
assert sc["project_info"]["sensor_location"] == "Loc #1 - 1425 Spanlers Mill Rd"
|
||||||
@@ -269,7 +269,7 @@ def test_seismodb_persists_sidecar_filename_and_review_sync(tmp_path: Path):
|
|||||||
|
|
||||||
|
|
||||||
def test_read_blastware_file_round_trip(tmp_path: Path):
|
def test_read_blastware_file_round_trip(tmp_path: Path):
|
||||||
"""write → read → key/timestamp/rectime survive."""
|
"""write → read → key/timestamp survive."""
|
||||||
from minimateplus.blastware_file import write_blastware_file, blastware_filename
|
from minimateplus.blastware_file import write_blastware_file, blastware_filename
|
||||||
|
|
||||||
ev, frames = _make_synthetic_event()
|
ev, frames = _make_synthetic_event()
|
||||||
@@ -278,7 +278,10 @@ def test_read_blastware_file_round_trip(tmp_path: Path):
|
|||||||
|
|
||||||
parsed = event_file_io.read_blastware_file(bw_path)
|
parsed = event_file_io.read_blastware_file(bw_path)
|
||||||
assert parsed._waveform_key == ev._waveform_key
|
assert parsed._waveform_key == ev._waveform_key
|
||||||
assert parsed.rectime_seconds == ev.rectime_seconds
|
# The synthetic file has no recording-setup block, so its record time is
|
||||||
|
# unknown. STRT[18], where the helper puts it, is the record-type marker
|
||||||
|
# and is not read as a record time (#44/#45).
|
||||||
|
assert parsed.rectime_seconds is None
|
||||||
# Timestamp lands via the footer; year/month/day/hour/min/sec all survive.
|
# Timestamp lands via the footer; year/month/day/hour/min/sec all survive.
|
||||||
assert parsed.timestamp is not None
|
assert parsed.timestamp is not None
|
||||||
assert parsed.timestamp.year == ev.timestamp.year
|
assert parsed.timestamp.year == ev.timestamp.year
|
||||||
|
|||||||
Reference in new issue
Block a user