Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e071be7ee0 | ||
|
|
a7f9f66da1 | ||
|
|
638ac58b4d | ||
|
|
646da046b7 |
No files matched your search
@@ -1105,6 +1105,14 @@ dated subdirectory under `tests/fixtures/` (e.g. `tests/fixtures/5-18-26/`).
|
||||
There used to be a separate `decode-re/` upload mirror but it was
|
||||
removed once the fixtures directory became the canonical location.
|
||||
|
||||
⚠ **A test reads only tracked files** (2026-11-20). `bridges/captures/`,
|
||||
`example-events/` and most of `tests/fixtures/` are gitignored, so a file a test
|
||||
reads from there exists only on this box: a fresh checkout then fails or skips
|
||||
it. Copy what the test needs into `tests/fixtures/` and `git add -f` it
|
||||
(captures go under `tests/fixtures/captures/<their folder>/`), and do not guard a
|
||||
fixture with a skip -- a missing fixture should fail. A fresh worktree is the
|
||||
check: it must pass as the dev box does.
|
||||
|
||||
---
|
||||
|
||||
## Protocol fundamentals
|
||||
|
||||
+3
-1
@@ -17,11 +17,13 @@ RUN apt-get update && \
|
||||
# docker-compose; storage in the DB is always UTC regardless.
|
||||
ENV TZ=America/New_York
|
||||
|
||||
# The product and its maintenance scripts (the backfills run in this
|
||||
# container). The bench and lab tools -- bridges/, scratch/, seismo_lab.py --
|
||||
# stay out of the image (ADR 0003; SFM imports nothing from them).
|
||||
COPY pyproject.toml requirements.txt ./
|
||||
COPY minimateplus ./minimateplus
|
||||
COPY micromate ./micromate
|
||||
COPY sfm ./sfm
|
||||
COPY bridges ./bridges
|
||||
COPY scripts ./scripts
|
||||
|
||||
RUN pip install --no-cache-dir -e .
|
||||
|
||||
+7
-265
@@ -124,118 +124,17 @@ def build_5a_request(address: int, length: int) -> bytes:
|
||||
crossing a 64 KB page): a 5A request is an ORDINARY 16-byte request --
|
||||
`[10 00 5A 00][length BE][address BE 4][zeros 6]`, SUM8 checksum, every
|
||||
02/03/04/10 escaped -- and this rebuilds all 540 of Blastware's 5A requests
|
||||
byte for byte. The older model below (`build_5a_frame`: a raw "offset_hi
|
||||
0x10", an "11-byte params", "metadata pages at 0x1002 / 0x1004") was the
|
||||
same bytes misread: `10 02 00` is the length 0x0200 escaped, and the
|
||||
"metadata pages" are the first event's chunks at 0x0200 and 0x0400.
|
||||
byte for byte. The older model (`build_5a_frame` and the
|
||||
`bulk_waveform_*` helpers, removed 2026-11-20: a raw "offset_hi 0x10", an
|
||||
"11-byte params", "metadata pages at 0x1002 / 0x1004") was the same bytes
|
||||
misread: `10 02 00` is the length 0x0200 escaped, and the "metadata pages"
|
||||
are the first event's chunks at 0x0200 and 0x0400.
|
||||
"""
|
||||
if not 0 <= address <= 0xFFFFFFFF:
|
||||
raise ValueError(f"address must fit in 32 bits, got {address:#x}")
|
||||
return build_bw_frame(SUB_5A, length, address.to_bytes(4, "big") + bytes(6))
|
||||
|
||||
|
||||
def build_5a_frame(offset_word: int, raw_params: bytes) -> bytes:
|
||||
"""
|
||||
⛔ SUPERSEDED 2026-10-26 by `build_5a_request` -- no production caller. Kept
|
||||
because tests/test_5a_protocol.py pins its bytes against the 5-1-26 captures;
|
||||
for in-page requests it emits the same bytes. Its model (below) is retracted.
|
||||
|
||||
Build a BW→S3 frame for SUB 5A (BULK_WAVEFORM_STREAM) that exactly
|
||||
matches Blastware's wire output.
|
||||
|
||||
SUB 5A uses a DIFFERENT frame format from all other read commands:
|
||||
1. The offset field (bytes [4:6]) is written RAW — the 0x10 in
|
||||
offset_hi=0x10 is NOT DLE-stuffed, unlike build_bw_frame().
|
||||
2. The checksum uses a DLE-aware sum: for each 0x10 XX pair in the
|
||||
stuffed section, only XX contributes; lone bytes contribute normally.
|
||||
This differs from the standard SUM8 checksum on the unstuffed payload.
|
||||
|
||||
Both differences are confirmed from the 1-2-26 BW TX capture (all 10 frames
|
||||
verified against this algorithm on 2026-04-02).
|
||||
|
||||
Args:
|
||||
offset_word: 16-bit offset. For probe/chunks/metadata pages this is
|
||||
`0x1002`. For the proper TERM frame this is computed by
|
||||
`bulk_waveform_term_v2()` from the STRT-derived
|
||||
`end_offset`.
|
||||
raw_params: 10, 11, or 12 params bytes (from `bulk_waveform_params`
|
||||
for probes/samples, `bulk_waveform_term_v2` for TERM, or
|
||||
a manually-built 12-byte block for the metadata pages
|
||||
0x1002 / 0x1004). See gotcha #3 below — params region
|
||||
uses partial DLE stuffing of 0x10 bytes.
|
||||
|
||||
Returns:
|
||||
Complete frame bytes: [ACK][STX][stuffed_section][chk][ETX]
|
||||
"""
|
||||
if len(raw_params) not in (10, 11, 12):
|
||||
# 10 = termination params; 11 = regular probe / chunk params;
|
||||
# 12 = metadata-page params (extra trailing 0x00 — BW byte-perfect quirk
|
||||
# for the two fixed metadata reads at counter=0x1002 and 0x1004).
|
||||
raise ValueError(f"raw_params must be 10/11/12 bytes, got {len(raw_params)}")
|
||||
|
||||
# Build stuffed section between STX and checksum
|
||||
s = bytearray()
|
||||
s += b"\x10\x10" # DLE-stuffed BW_CMD
|
||||
s += b"\x00" # flags
|
||||
s += bytes([SUB_5A]) # sub = 0x5A
|
||||
s += b"\x00" # field3
|
||||
s += bytes([(offset_word >> 8) & 0xFF, # offset_hi — raw, NOT stuffed
|
||||
offset_word & 0xFF]) # offset_lo
|
||||
# Params — partial DLE stuffing of 0x10 bytes (CONFIRMED 2026-05-05).
|
||||
#
|
||||
# The device's de-stuffing rule for params is:
|
||||
# • `10 10` → de-stuffs to `10`
|
||||
# • `10 02/03/04` → kept literal (these are inner-frame markers)
|
||||
# • `10 X` other → de-stuffs to just `X` (drops the 0x10)
|
||||
#
|
||||
# So for any 0x10 byte in the *logical* params that is followed by a
|
||||
# byte NOT in {0x02, 0x03, 0x04, 0x10}, we must double the 0x10 on the
|
||||
# wire (`10 X` → `10 10 X`) so the device's de-stuffer reproduces the
|
||||
# original `10 X` pair. Without this, counter values with `0x10` in
|
||||
# the high byte (e.g. counter=0x1000 has params bytes `10 00`) are
|
||||
# silently corrupted to `0x__00` on the device side, and the device
|
||||
# responds for the wrong address — for counter=0x1000 it returns the
|
||||
# probe response (counter=0x0000), which contains the file header +
|
||||
# STRT. That STRT block then lands in the assembled file body and
|
||||
# Blastware rejects the file as malformed.
|
||||
#
|
||||
# Confirmed against BW capture 5-1-26 / bwcap3sec frame 20: params
|
||||
# logical bytes `00 01 11 10 00 00 00 00 00 00 00` (counter=0x1000)
|
||||
# are encoded on the wire as `00 01 11 10 10 00 00 00 00 00 00 00`.
|
||||
# BW frames 13/14 (meta @ 0x1002 / 0x1004) leave `10 02` and `10 04`
|
||||
# raw — the device handles those literal pairs correctly.
|
||||
i = 0
|
||||
while i < len(raw_params):
|
||||
b = raw_params[i]
|
||||
s.append(b)
|
||||
if (
|
||||
b == 0x10
|
||||
and i + 1 < len(raw_params)
|
||||
and raw_params[i + 1] not in (0x02, 0x03, 0x04, 0x10)
|
||||
):
|
||||
s.append(0x10) # double the 0x10 so it survives device de-stuffing
|
||||
i += 1
|
||||
|
||||
# DLE-aware checksum: for 0x10 XX pairs count XX; for lone bytes count them
|
||||
chk, i = 0, 0
|
||||
while i < len(s):
|
||||
if s[i] == DLE and i + 1 < len(s):
|
||||
chk = (chk + s[i + 1]) & 0xFF
|
||||
i += 2
|
||||
else:
|
||||
chk = (chk + s[i]) & 0xFF
|
||||
i += 1
|
||||
|
||||
# A checksum that is itself a framing byte is DLE-escaped. Sent bare, a
|
||||
# 0x02 before ETX reads as a new STX: BE9441 never answered chunk 0x7D06
|
||||
# (`... 02 03`) and rebooted ~11 s later, twice; escaped (`10 02 03`) it
|
||||
# answered in 28 ms, as did checksums 0x04 and 0x10 (bench, 2026-10-26).
|
||||
# The set is a Micromate's escape set (251/251 THOR requests); the MiniMate's
|
||||
# de-stuffing keeps `10 02/03/04` literal and turns `10 10` into 0x10.
|
||||
tail = bytes([DLE, chk]) if chk in (STX, ETX, 0x04, DLE) else bytes([chk])
|
||||
return bytes([ACK, STX]) + bytes(s) + tail + bytes([ETX])
|
||||
|
||||
|
||||
def build_bw_frame(sub: int, offset: int = 0, params: bytes = bytes(10)) -> bytes:
|
||||
"""
|
||||
Build a BW→S3 read-command frame.
|
||||
@@ -368,164 +267,6 @@ def token_params(token: int = 0) -> bytes:
|
||||
return bytes(p)
|
||||
|
||||
|
||||
def bulk_waveform_params(key4: bytes, counter: int, *, is_probe: bool = False) -> bytes:
|
||||
"""
|
||||
⛔ SUPERSEDED 2026-10-26 by `build_5a_request` / `parse_strt_end_key` -- no
|
||||
production caller; kept for tests/test_5a_protocol.py. See build_5a_request.
|
||||
|
||||
Build the 10-byte params block for SUB 5A (BULK_WAVEFORM_STREAM) requests.
|
||||
|
||||
Confirmed 2026-04-02 from 1-2-26 BW TX capture analysis:
|
||||
|
||||
Probe / first request (is_probe=True, counter=0):
|
||||
params[0] = 0x00
|
||||
params[1:5] = key4 (all 4 key bytes; counter overlaps key4[2:4] = 0x0000)
|
||||
params[5:] = zeros
|
||||
|
||||
Regular chunk requests (is_probe=False):
|
||||
params[0] = 0x00
|
||||
params[1:3] = key4[0:2] (first 2 key bytes as session handle)
|
||||
params[3:5] = counter (BE uint16) (chunk position, increments by 0x0400)
|
||||
params[5:] = zeros
|
||||
|
||||
Termination request: DO NOT use this helper — see bulk_waveform_term_params().
|
||||
|
||||
Args:
|
||||
key4: 4-byte waveform key from EVENT_HEADER (1E) response.
|
||||
counter: Chunk position counter (uint16 BE). Pass 0 for probe.
|
||||
is_probe: If True, embed full key4 (probe step only).
|
||||
|
||||
Returns:
|
||||
11-byte params block. (BW confirmed: chunk frames carry 11 params bytes,
|
||||
not 10; the extra trailing 0x00 was confirmed from 1-2-26 wire capture
|
||||
on 2026-04-02.)
|
||||
"""
|
||||
if len(key4) != 4:
|
||||
raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}")
|
||||
p = bytearray(11) # 11 bytes confirmed from BW wire capture
|
||||
p[0] = 0x00
|
||||
p[1] = key4[0]
|
||||
p[2] = key4[1]
|
||||
if is_probe:
|
||||
# Full key4; counter=0 is implied (overlaps with key4[2:4] which must be 0x0000)
|
||||
p[3] = key4[2]
|
||||
p[4] = key4[3]
|
||||
else:
|
||||
p[3] = (counter >> 8) & 0xFF
|
||||
p[4] = counter & 0xFF
|
||||
return bytes(p)
|
||||
|
||||
|
||||
def bulk_waveform_term_params(key4: bytes, counter: int) -> bytes:
|
||||
"""
|
||||
⛔ SUPERSEDED 2026-10-26 by `build_5a_request` / `parse_strt_end_key` -- no
|
||||
production caller; kept for tests/test_5a_protocol.py. See build_5a_request.
|
||||
|
||||
⛔ DEPRECATED — DO NOT USE IN NEW CODE.
|
||||
|
||||
This is the v1 termination params helper, paired with the broken
|
||||
`_BULK_TERM_OFFSET = 0x005A` magic offset_word. Together they produce a
|
||||
~100-byte device-side terminator response that does NOT contain the
|
||||
partial-last-chunk waveform tail or the 26-byte file footer. Files
|
||||
reconstructed using this terminator are missing their last ~512 bytes of
|
||||
waveform data and have a synthesized footer that disagrees with what BW
|
||||
would have written.
|
||||
|
||||
**For new code, use `bulk_waveform_term_v2(key4, end_offset, last_chunk_counter)`**
|
||||
which computes the correct offset_word + params from the STRT-derived
|
||||
`end_offset`. v2 produces wire bytes that match BW exactly across all
|
||||
tested events (4-27-26 / 5-1-26 / 5-4-26 captures).
|
||||
|
||||
This function is retained ONLY for the defensive fallback path in
|
||||
`read_bulk_waveform_stream()` that triggers when STRT parsing fails or no
|
||||
chunks are fetched (= a malformed event or an unexpected device state).
|
||||
The fallback already logs a WARNING when it activates; if you see that
|
||||
warning, the bug is upstream — STRT should have been parseable.
|
||||
"""
|
||||
if len(key4) != 4:
|
||||
raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}")
|
||||
p = bytearray(10)
|
||||
p[0] = key4[0]
|
||||
p[1] = key4[1]
|
||||
p[2] = (counter >> 8) & 0xFF
|
||||
return bytes(p)
|
||||
|
||||
|
||||
def bulk_waveform_term_v2(
|
||||
key4: bytes,
|
||||
end_offset: int,
|
||||
last_chunk_counter: int,
|
||||
) -> tuple[int, bytes]:
|
||||
"""
|
||||
⛔ SUPERSEDED 2026-10-26 by `build_5a_request` / `parse_strt_end_key` -- no
|
||||
production caller; kept for tests/test_5a_protocol.py. See build_5a_request.
|
||||
|
||||
Compute the SUB 5A TERM frame's offset_word and 10-byte params block.
|
||||
|
||||
Confirmed across 3 events (4-27-26 + 5-1-26 captures):
|
||||
|
||||
next_boundary = last_chunk_counter + 0x0200
|
||||
offset_word = end_offset - next_boundary (residual byte count)
|
||||
params[0] = key4[0] (= 0x01 on every observed device)
|
||||
params[1] = key4[1] (= 0x11)
|
||||
params[2] = (next_boundary >> 8) & 0xFF
|
||||
params[3] = next_boundary & 0xFF
|
||||
params[4:10] = zeros
|
||||
|
||||
Verification:
|
||||
| end_offset | last_chunk | next_boundary | offset_word | params[2:4] |
|
||||
| 0x1ABE | 0x1800 | 0x1A00 | 0x00BE | 1A 00 |
|
||||
| 0x21F2 | 0x1E00 | 0x2000 | 0x01F2 | 20 00 |
|
||||
| 0x417E | 0x3E38 | 0x4038 | 0x0146 | 40 38 |
|
||||
|
||||
The device receives `requested_address = (params[2] << 8) | offset_word`
|
||||
and replies with `(end_offset - next_boundary)` bytes of waveform tail
|
||||
starting at `next_boundary` — including the 26-byte file footer.
|
||||
|
||||
Args:
|
||||
key4: 4-byte waveform key for this event.
|
||||
end_offset: Event-end pointer (= `(end_key[2] << 8) | end_key[3]`
|
||||
from the STRT record at data[23:27] of A5[0]).
|
||||
last_chunk_counter: Counter of the last full 0x0200-byte chunk fetched
|
||||
(the chunk that covers [last_chunk_counter,
|
||||
last_chunk_counter + 0x0200)).
|
||||
|
||||
Returns:
|
||||
(offset_word, params10) tuple. Pass as
|
||||
`build_5a_frame(offset_word, params)`.
|
||||
|
||||
Raises:
|
||||
ValueError: on inconsistent inputs.
|
||||
"""
|
||||
if len(key4) != 4:
|
||||
raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}")
|
||||
next_boundary = last_chunk_counter + 0x0200
|
||||
if next_boundary > 0xFFFF:
|
||||
raise ValueError(
|
||||
f"next_boundary 0x{next_boundary:04X} exceeds uint16; check inputs"
|
||||
)
|
||||
if end_offset <= last_chunk_counter:
|
||||
raise ValueError(
|
||||
f"end_offset 0x{end_offset:04X} must be > "
|
||||
f"last_chunk_counter 0x{last_chunk_counter:04X}"
|
||||
)
|
||||
offset_word = end_offset - next_boundary
|
||||
if offset_word < 0:
|
||||
# Last chunk overshot end_offset; caller should have stopped one chunk
|
||||
# earlier. Treat as zero residual.
|
||||
offset_word = 0
|
||||
if offset_word > 0xFFFF:
|
||||
raise ValueError(
|
||||
f"offset_word 0x{offset_word:04X} exceeds uint16"
|
||||
)
|
||||
p = bytearray(10)
|
||||
p[0] = key4[0]
|
||||
p[1] = key4[1]
|
||||
p[2] = (next_boundary >> 8) & 0xFF
|
||||
p[3] = next_boundary & 0xFF
|
||||
return offset_word, bytes(p)
|
||||
|
||||
|
||||
# ── End-offset extraction from STRT record ────────────────────────────────────
|
||||
|
||||
STRT_MARKER = b"STRT"
|
||||
@@ -567,7 +308,8 @@ def parse_strt_end_offset(a5_data: bytes) -> Optional[int]:
|
||||
"""
|
||||
⛔ SUPERSEDED 2026-10-26 by `parse_strt_end_key`: this keeps only the low 16
|
||||
bits (the 64 KB page bug) and misreads an end whose low bytes hold an escaped
|
||||
02/03/04. No production caller; kept for tests/test_5a_protocol.py.
|
||||
02/03/04. No production caller; tests/test_5a_blastware_walk.py keeps it
|
||||
to show that misread.
|
||||
|
||||
Extract the event-end offset from the STRT record in an A5 response payload.
|
||||
|
||||
|
||||
+3
-2
@@ -24,6 +24,7 @@ dependencies = [
|
||||
test = ["pytest>=7", "httpx>=0.24"]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
# Auto-discovers minimateplus/, micromate/, sfm/, bridges/ as packages
|
||||
# The product's packages. bridges/ (bench tools) is not one of them: it runs
|
||||
# from a checkout and stays out of the image (ADR 0003).
|
||||
where = ["."]
|
||||
include = ["minimateplus*", "micromate*", "sfm*", "bridges*"]
|
||||
include = ["minimateplus*", "micromate*", "sfm*"]
|
||||
@@ -1,360 +0,0 @@
|
||||
"""
|
||||
scratch/next_experiment_skeleton.py — segment-channel scoring analyzer.
|
||||
|
||||
This is the suggested NEXT EXPERIMENT for cracking the waveform body codec.
|
||||
The goal is to figure out what segments 1+ contain, since segment 0 = Tran
|
||||
is solved but multi-segment continuation diverges from truth at sample ~512.
|
||||
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
The hypothesis to test
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Segments rotate through channels:
|
||||
|
||||
segment 0 → Tran samples 0..509
|
||||
segment 1 → Vert samples 0..507
|
||||
segment 2 → Long samples 0..507
|
||||
segment 3 → Mic samples 0..507
|
||||
segment 4 → Tran samples 510..N (continuation)
|
||||
...
|
||||
|
||||
This would explain why segment 0 works perfectly (it's pure Tran) and why
|
||||
applying segment 1's blocks as Tran continuation gives wrong values
|
||||
(it's actually Vert).
|
||||
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
What the analyzer should do
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
For each segment in each fixture event:
|
||||
|
||||
1. Run the segment-0 block-walker + RLE decode (the same algorithm that
|
||||
``decode_tran_initial`` uses) over the segment's blocks. Start from
|
||||
some anchor value and produce a cumulative trajectory of length =
|
||||
number-of-deltas-in-segment.
|
||||
|
||||
2. For each candidate channel C ∈ {Tran, Vert, Long, MicL}:
|
||||
For each candidate anchor location in the segment-header payload
|
||||
(try [0:2], [2:4], [4:6], [14:16], [16:18] as int16 BE):
|
||||
Compare the decoded trajectory against truth[C] starting from
|
||||
the segment's first sample index.
|
||||
Score = number of matches (or sum of squared errors).
|
||||
|
||||
3. Report the best (channel, anchor-location) combination per segment.
|
||||
|
||||
If the rotation hypothesis is correct, you'll see:
|
||||
segment 0 → best score for (Tran, preamble bytes [3:5]) ✓ already known
|
||||
segment 1 → best score for (Vert, <some-header-byte>)
|
||||
segment 2 → best score for (Long, <some-header-byte>)
|
||||
segment 3 → best score for (MicL, <some-header-byte>)
|
||||
segment 4 → best score for (Tran, continuing from segment 0's end)
|
||||
|
||||
If the rotation hypothesis is NOT correct, the scorer will at least narrow
|
||||
down what segment 1 actually carries. Maybe channels interleave at finer
|
||||
granularity, or maybe segments alternate by something other than channel.
|
||||
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
Why this is a scoring analyzer, not a hand-written decoder
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Direct hand-coding ("assume segment 1 is Vert with anchor at byte X") gets
|
||||
stuck when the assumption is wrong because the failure mode is silent —
|
||||
you get plausible-looking-but-wrong samples and have to manually diff
|
||||
against truth to debug.
|
||||
|
||||
The scorer is brute-force but cheap: every fixture event × every segment ×
|
||||
4 channels × 5 anchor-byte candidates is only ~hundreds of comparisons.
|
||||
The winning combination jumps out by score.
|
||||
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
Skeleton
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
from minimateplus.waveform_codec import walk_body, find_data_start, WaveformBlock
|
||||
|
||||
|
||||
# ── Reusable pieces ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
CHANNELS = ("Tran", "Vert", "Long", "MicL")
|
||||
LSB_INV = 200 # 1 in/s / 0.005 in/s/LSB; multiply BW-export floats by this
|
||||
# to get 16-count units (the body's native quantization).
|
||||
|
||||
|
||||
@dataclass
|
||||
class FixtureEvent:
|
||||
name: str # e.g. "M529LL1A.SP0"
|
||||
bin_path: str
|
||||
txt_path: str
|
||||
body: bytes
|
||||
truth: dict # {channel: list of int16-quantized samples}
|
||||
blocks: List[WaveformBlock]
|
||||
segment_starts: List[int] # block indices of each 40 02 segment header
|
||||
segment_sample_starts: List[int] # for each segment, the truth sample index it starts at
|
||||
|
||||
|
||||
def s4(n: int) -> int:
|
||||
"""4-bit signed nibble decode."""
|
||||
return n if n < 8 else n - 16
|
||||
|
||||
|
||||
def i8(b: int) -> int:
|
||||
"""int8 reinterpret of unsigned byte."""
|
||||
return b if b < 128 else b - 256
|
||||
|
||||
|
||||
def load_fixture(name: str) -> FixtureEvent:
|
||||
"""Load a fixture event with its truth values and parsed block stream."""
|
||||
# Find the fixture (search both subdirs of tests/fixtures/).
|
||||
base = os.path.join(os.path.dirname(__file__), "..", "tests", "fixtures")
|
||||
candidates = [
|
||||
os.path.join(base, "5-11-26", name),
|
||||
os.path.join(base, "decode-re-5-8-26", "event-a", name), # not used directly
|
||||
]
|
||||
bin_path = next((c for c in candidates if os.path.exists(c)), None)
|
||||
if bin_path is None:
|
||||
# Try a glob walk for the 5-8 fixtures (they're in subdirs).
|
||||
for root, _, files in os.walk(base):
|
||||
if name in files:
|
||||
bin_path = os.path.join(root, name)
|
||||
break
|
||||
if bin_path is None:
|
||||
raise FileNotFoundError(name)
|
||||
|
||||
txt_path = bin_path + ".TXT"
|
||||
with open(bin_path, "rb") as f:
|
||||
raw = f.read()
|
||||
body = raw[43:-26]
|
||||
truth = _parse_txt(txt_path)
|
||||
blocks = walk_body(body, find_data_start(body))
|
||||
|
||||
seg_idx = [i for i, b in enumerate(blocks) if b.tag_hi == 0x40]
|
||||
# Segment 0 starts at sample 0; subsequent segments start at the
|
||||
# cumulative sample count from previous segment(s). Tran's segment 0
|
||||
# is N samples; if rotation hypothesis is correct, segment 1's data
|
||||
# starts at sample 0 for a *different* channel. The analyzer should
|
||||
# try both "continues from previous segment" and "starts at sample 0
|
||||
# of a different channel."
|
||||
seg_sample_starts = _compute_segment_sample_starts(blocks, seg_idx)
|
||||
|
||||
return FixtureEvent(
|
||||
name=name, bin_path=bin_path, txt_path=txt_path,
|
||||
body=body, truth=truth, blocks=blocks,
|
||||
segment_starts=seg_idx, segment_sample_starts=seg_sample_starts,
|
||||
)
|
||||
|
||||
|
||||
def _parse_txt(path: str) -> dict:
|
||||
"""Parse BW ASCII TXT export into {channel: [int_samples_in_16_count_units]}."""
|
||||
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
||||
lines = f.read().splitlines()
|
||||
header_idx = next(
|
||||
(i for i, l in enumerate(lines)
|
||||
if all(c in l for c in CHANNELS)),
|
||||
None,
|
||||
)
|
||||
if header_idx is None:
|
||||
return {ch: [] for ch in CHANNELS}
|
||||
out = {ch: [] for ch in CHANNELS}
|
||||
for line in lines[header_idx + 1:]:
|
||||
parts = re.split(r"\s+", line.strip())
|
||||
if len(parts) < 4:
|
||||
continue
|
||||
try:
|
||||
vals = [float(p) for p in parts[:4]]
|
||||
except ValueError:
|
||||
continue
|
||||
for ch, v in zip(CHANNELS, vals):
|
||||
# Multiply by LSB_INV; geo channels are in in/s, MicL is in dB(L)
|
||||
# (which doesn't quantize the same way — leaving raw for MicL is fine,
|
||||
# the scorer should treat MicL specially).
|
||||
out[ch].append(round(v * LSB_INV) if ch != "MicL" else v)
|
||||
return out
|
||||
|
||||
|
||||
def _compute_segment_sample_starts(
|
||||
blocks: List[WaveformBlock], seg_idx: List[int]
|
||||
) -> List[int]:
|
||||
"""Cumulative sample-count up to each segment header (if all blocks treated
|
||||
as Tran continuation). Useful as one candidate for segment-1-Tran tests.
|
||||
|
||||
The scorer should ALSO try "segment 1 starts at sample 0 of a new channel"
|
||||
as the rotation hypothesis predicts.
|
||||
"""
|
||||
starts = []
|
||||
cum = 2 # T[0] + T[1] from preamble
|
||||
for i, b in enumerate(blocks):
|
||||
if i in seg_idx:
|
||||
starts.append(cum)
|
||||
if b.tag_hi == 0x10:
|
||||
cum += b.tag_lo
|
||||
elif b.tag_hi == 0x20:
|
||||
cum += b.tag_lo
|
||||
elif b.tag_hi == 0x00:
|
||||
cum += b.tag_lo
|
||||
# 30 NN and 40 02 don't contribute samples (for this hypothesis)
|
||||
return starts
|
||||
|
||||
|
||||
# ── The core algorithm: decode a segment's blocks as deltas ─────────────────
|
||||
|
||||
|
||||
def decode_segment_as_channel(
|
||||
blocks: List[WaveformBlock],
|
||||
seg_start_block_idx: int,
|
||||
seg_end_block_idx: int,
|
||||
anchor: int,
|
||||
) -> List[int]:
|
||||
"""Apply the segment-0 codec rules to a range of blocks, starting from *anchor*.
|
||||
|
||||
Returns a list of cumulative sample values (one per delta). Does NOT include
|
||||
the anchor itself in the output — the first returned value is anchor + first_delta.
|
||||
"""
|
||||
out = []
|
||||
cur = anchor
|
||||
for bi in range(seg_start_block_idx, seg_end_block_idx):
|
||||
blk = blocks[bi]
|
||||
if blk.tag_hi == 0x10:
|
||||
for byte in blk.data:
|
||||
for nib in ((byte >> 4) & 0xF, byte & 0xF):
|
||||
cur += s4(nib)
|
||||
out.append(cur)
|
||||
elif blk.tag_hi == 0x20:
|
||||
for byte in blk.data:
|
||||
cur += i8(byte)
|
||||
out.append(cur)
|
||||
elif blk.tag_hi == 0x00:
|
||||
for _ in range(blk.tag_lo):
|
||||
out.append(cur)
|
||||
# 30 NN: skip (content unknown)
|
||||
# 40 02: shouldn't appear in segment data (it's the segment header)
|
||||
return out
|
||||
|
||||
|
||||
def score_against_truth(
|
||||
decoded: List[int],
|
||||
truth: List[int],
|
||||
truth_start: int,
|
||||
) -> Tuple[int, int]:
|
||||
"""Compare *decoded* to truth[truth_start : truth_start + len(decoded)].
|
||||
|
||||
Returns (n_matches, n_compared).
|
||||
"""
|
||||
n = min(len(decoded), len(truth) - truth_start)
|
||||
if n <= 0:
|
||||
return (0, 0)
|
||||
matches = sum(1 for i in range(n) if decoded[i] == truth[truth_start + i])
|
||||
return (matches, n)
|
||||
|
||||
|
||||
# ── TODO for the next pass ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
def score_segment_against_all_channels(
|
||||
event: FixtureEvent,
|
||||
segment_index: int,
|
||||
) -> List[Tuple[str, int, int, int]]:
|
||||
"""For segment *segment_index* of *event*, find the best (channel, start_sample)
|
||||
fit.
|
||||
|
||||
For each candidate channel C and each candidate starting truth-sample index s,
|
||||
we pick the anchor that makes the FIRST decoded value match truth[C][s], then
|
||||
score the remaining decoded values against truth[C][s+1 : s+N].
|
||||
|
||||
Returns rows of (channel_name, start_sample, n_matches, n_compared)
|
||||
sorted by match-count descending.
|
||||
"""
|
||||
# Block range of this segment: from the segment header (inclusive) up to
|
||||
# the next segment header (exclusive), or end-of-blocks.
|
||||
seg_header_idx = event.segment_starts[segment_index]
|
||||
next_header_idx = (
|
||||
event.segment_starts[segment_index + 1]
|
||||
if segment_index + 1 < len(event.segment_starts)
|
||||
else len(event.blocks)
|
||||
)
|
||||
|
||||
# Decode the segment's data blocks (skip the segment-header block itself).
|
||||
# Use anchor=0 — we'll re-anchor when scoring against each channel.
|
||||
deltas_trajectory = decode_segment_as_channel(
|
||||
event.blocks, seg_header_idx + 1, next_header_idx, anchor=0
|
||||
)
|
||||
if not deltas_trajectory:
|
||||
return []
|
||||
|
||||
n = len(deltas_trajectory)
|
||||
results = []
|
||||
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
truth = event.truth.get(ch)
|
||||
if not truth or len(truth) < n + 1:
|
||||
continue
|
||||
# For each candidate starting sample s in truth, check if applying
|
||||
# the deltas starting from truth[s] reproduces truth[s+1:s+n+1].
|
||||
best = (0, -1)
|
||||
for s in range(len(truth) - n):
|
||||
anchor = truth[s]
|
||||
offset = anchor - deltas_trajectory[0] + truth[s + 1] - anchor
|
||||
# Recompute: trajectory[i] = anchor + cumulative_delta_through_i
|
||||
# but we already have deltas_trajectory computed from anchor=0,
|
||||
# so trajectory_relative[i] = anchor + deltas_trajectory[i].
|
||||
matches = 0
|
||||
for i in range(n):
|
||||
if truth[s + i + 1] == anchor + deltas_trajectory[i]:
|
||||
matches += 1
|
||||
# Note: we could break early on first mismatch for "matches start",
|
||||
# but counting total matches gives a more robust score.
|
||||
if matches > best[0]:
|
||||
best = (matches, s)
|
||||
results.append((ch, best[1], best[0], n))
|
||||
|
||||
results.sort(key=lambda r: -r[2])
|
||||
return results
|
||||
|
||||
|
||||
# ── Driver ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def main():
|
||||
"""Run the analyzer on all loud-bundle events and print best scores."""
|
||||
events = ["M529LL1A.SP0", "M529LL1A.SS0", "M529LL1A.SV0",
|
||||
"M529LL1L.JQ0", "M529LL1L.V70"]
|
||||
for name in events:
|
||||
try:
|
||||
event = load_fixture(name)
|
||||
except FileNotFoundError:
|
||||
print(f"{name}: fixture not found")
|
||||
continue
|
||||
|
||||
print(f"\n=== {name} ===")
|
||||
print(f" body bytes: {len(event.body)}")
|
||||
print(f" blocks: {len(event.blocks)}")
|
||||
print(f" segments: {len(event.segment_starts)}")
|
||||
print(f" segment sample-starts (if all blocks are 1 channel):")
|
||||
for si, sample_start in enumerate(event.segment_sample_starts):
|
||||
print(f" seg {si}: sample {sample_start}")
|
||||
|
||||
for si in range(len(event.segment_starts)):
|
||||
results = score_segment_against_all_channels(event, si)
|
||||
if not results:
|
||||
print(f" seg {si}: (no scorable data)")
|
||||
continue
|
||||
tag = "✓" if results[0][2] / max(results[0][3], 1) > 0.9 else " "
|
||||
top = results[0]
|
||||
print(f" seg {si}: best fit {tag} = {top[0]:<5} "
|
||||
f"starting at sample {top[1]:>5}, {top[2]:>4}/{top[3]:<4} match"
|
||||
+ (f" (next: {results[1][0]} @{results[1][1]} {results[1][2]}/{results[1][3]})"
|
||||
if len(results) > 1 else ""))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Backfill events.*_zc_freq / *_zc_above_range from .sfm.json sidecars.
|
||||
|
||||
Idempotent. Reads each event's sidecar bw_report and writes the per-channel
|
||||
ZC frequency into the DB columns via a direct UPDATE. Events with no sidecar
|
||||
(or no bw_report freq) are left untouched. Mirrors scripts/backfill_record_type.py.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
log = logging.getLogger("backfill_event_zc_freq")
|
||||
|
||||
|
||||
def _freqs_from_sidecar(sidecar: dict) -> dict | None:
|
||||
bw = (sidecar or {}).get("bw_report") or {}
|
||||
peaks = bw.get("peaks") or {}
|
||||
mic = bw.get("mic") or {}
|
||||
out = {}
|
||||
for axis in ("tran", "vert", "long"):
|
||||
chd = peaks.get(axis) or {}
|
||||
out[f"{axis}_zc_freq"] = chd.get("zc_freq_hz")
|
||||
out[f"{axis}_zc_above_range"] = 1 if chd.get("zc_freq_above_range") else 0
|
||||
out["mic_zc_freq"] = mic.get("zc_freq_hz")
|
||||
out["mic_zc_above_range"] = 1 if mic.get("zc_freq_above_range") else 0
|
||||
# None if there's literally no frequency anywhere.
|
||||
if all(out[f"{a}_zc_freq"] is None for a in ("tran", "vert", "long", "mic")):
|
||||
return None
|
||||
return out
|
||||
|
||||
|
||||
def backfill_zc_freq(db: SeismoDb, store, *, dry_run: bool = False) -> dict:
|
||||
counts = {"updated": 0, "skipped_no_sidecar": 0, "skipped_no_freq": 0}
|
||||
# Pull every event (paginate generously; adjust if a store has >100k events).
|
||||
rows = db.query_events(limit=1_000_000)
|
||||
for row in rows:
|
||||
serial = row.get("serial")
|
||||
filename = row.get("blastware_filename")
|
||||
if not serial or not filename:
|
||||
counts["skipped_no_sidecar"] += 1
|
||||
continue
|
||||
sidecar = store.load_sidecar(serial, filename)
|
||||
if sidecar is None:
|
||||
counts["skipped_no_sidecar"] += 1
|
||||
continue
|
||||
freqs = _freqs_from_sidecar(sidecar)
|
||||
if freqs is None:
|
||||
counts["skipped_no_freq"] += 1
|
||||
continue
|
||||
if dry_run:
|
||||
counts["updated"] += 1
|
||||
continue
|
||||
with db._connect() as conn:
|
||||
conn.execute(
|
||||
"""UPDATE events SET
|
||||
tran_zc_freq=?, vert_zc_freq=?, long_zc_freq=?, mic_zc_freq=?,
|
||||
tran_zc_above_range=?, vert_zc_above_range=?,
|
||||
long_zc_above_range=?, mic_zc_above_range=?
|
||||
WHERE id=?""",
|
||||
(freqs["tran_zc_freq"], freqs["vert_zc_freq"], freqs["long_zc_freq"],
|
||||
freqs["mic_zc_freq"], freqs["tran_zc_above_range"],
|
||||
freqs["vert_zc_above_range"], freqs["long_zc_above_range"],
|
||||
freqs["mic_zc_above_range"], row["id"]),
|
||||
)
|
||||
counts["updated"] += 1
|
||||
return counts
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--db-path", default=str(
|
||||
Path(__file__).resolve().parent.parent / "bridges" / "captures" / "seismo_relay.db"))
|
||||
p.add_argument("--store-root", default=None)
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
p.add_argument("-v", "--verbose", action="store_true")
|
||||
args = p.parse_args(argv)
|
||||
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
|
||||
db_path = Path(args.db_path).expanduser().resolve()
|
||||
store_root = (
|
||||
Path(args.store_root).expanduser().resolve()
|
||||
if args.store_root else db_path.parent / "waveforms"
|
||||
)
|
||||
db = SeismoDb(db_path)
|
||||
store = WaveformStore(store_root)
|
||||
counts = backfill_zc_freq(db, store, dry_run=args.dry_run)
|
||||
log.info("backfill_zc_freq: %s", counts)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,150 +0,0 @@
|
||||
"""
|
||||
scripts/backfill_record_type.py — fix `record_type` on legacy event
|
||||
rows whose value was hardcoded to "Waveform" regardless of actual type.
|
||||
|
||||
Why this is needed
|
||||
──────────────────
|
||||
Pre-v0.16.1 the BW file importer (`event_file_io.read_blastware_file`)
|
||||
hardcoded `ev.record_type = "Waveform"` for every imported event. Fixed
|
||||
in commit aac1c8e — new ingests now derive the type from the Blastware
|
||||
filename's extension last character (H=Histogram, W=Waveform, M=Manual,
|
||||
E=Event, C=Combo) per the V10.72+ MiniMate Plus AB0T filename scheme.
|
||||
|
||||
Effect on a server that imported events under the old code: every
|
||||
events row has `record_type = "Waveform"`, even for histograms,
|
||||
manuals, etc. Visible in terra-view's event-detail modal under the
|
||||
"Record Type" field. Terra-view also has a client-side workaround
|
||||
that derives the type from the filename for display purposes, so
|
||||
operators see the correct type in the UI even before this backfill.
|
||||
This script makes the DB column match what the UI is already showing,
|
||||
which matters for reporting and any downstream consumer that reads
|
||||
events.record_type directly.
|
||||
|
||||
This script
|
||||
───────────
|
||||
Walks the `events` table and updates each row's `record_type` to the
|
||||
derived value from its `blastware_filename`. Old S338 firmware files
|
||||
(3-char extensions ending in `0`) and any unrecognized suffix get
|
||||
left at the existing value (defaults to "Waveform").
|
||||
|
||||
Idempotent: re-running after a successful backfill finds zero rows
|
||||
needing updates and exits cleanly (it always re-derives but only
|
||||
writes when the value would change).
|
||||
|
||||
Usage
|
||||
─────
|
||||
# Dry-run (default): print what would change, don't touch the DB
|
||||
python -m scripts.backfill_record_type --db bridges/captures/seismo_relay.db
|
||||
|
||||
# Apply the backfill
|
||||
python -m scripts.backfill_record_type --db bridges/captures/seismo_relay.db --apply
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sqlite3
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# Must stay in sync with minimateplus.event_file_io._RECORD_TYPE_BY_EXT_SUFFIX.
|
||||
_TYPE_FROM_SUFFIX = {
|
||||
"H": "Histogram",
|
||||
"W": "Waveform",
|
||||
"M": "Manual",
|
||||
"E": "Event",
|
||||
"C": "Combo",
|
||||
}
|
||||
|
||||
|
||||
def derive_record_type(filename: str | None, default: str = "Waveform") -> str:
|
||||
"""Mirror of minimateplus.event_file_io.derive_record_type_from_filename.
|
||||
|
||||
Vendored here so this script runs without needing the seismo-relay
|
||||
package on the Python path (useful on prod where you might be
|
||||
running it via `docker exec` against a container's DB volume).
|
||||
"""
|
||||
if not filename:
|
||||
return default
|
||||
name = Path(filename).name
|
||||
if "." not in name:
|
||||
return default
|
||||
ext = name.rsplit(".", 1)[1]
|
||||
if not ext:
|
||||
return default
|
||||
return _TYPE_FROM_SUFFIX.get(ext[-1].upper(), default)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--db", required=True, help="Path to seismo_relay.db")
|
||||
ap.add_argument("--apply", action="store_true",
|
||||
help="Actually write changes (default is dry-run).")
|
||||
ap.add_argument("--default", default="Waveform",
|
||||
help="Fallback record_type when filename doesn't encode one. "
|
||||
"Default: Waveform (matches the pre-fix bug's behavior).")
|
||||
args = ap.parse_args()
|
||||
|
||||
db_path = Path(args.db)
|
||||
if not db_path.exists():
|
||||
print(f"ERROR: database not found at {db_path}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
conn = sqlite3.connect(str(db_path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
|
||||
cur.execute("""
|
||||
SELECT id, blastware_filename, record_type
|
||||
FROM events
|
||||
WHERE blastware_filename IS NOT NULL
|
||||
AND blastware_filename != ''
|
||||
""")
|
||||
rows = cur.fetchall()
|
||||
total = len(rows)
|
||||
print(f"Scanning {total:,} event rows…")
|
||||
print()
|
||||
|
||||
# Tally proposed changes.
|
||||
transitions: Counter[tuple[str, str]] = Counter()
|
||||
update_ids: list[tuple[str, str]] = []
|
||||
unrecognized = 0
|
||||
|
||||
for row in rows:
|
||||
derived = derive_record_type(row["blastware_filename"], default=args.default)
|
||||
current = row["record_type"] or ""
|
||||
if derived == current:
|
||||
continue
|
||||
transitions[(current, derived)] += 1
|
||||
update_ids.append((row["id"], derived))
|
||||
|
||||
if not update_ids:
|
||||
print("Nothing to update — all rows already match.")
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
print(f"{len(update_ids):,} row(s) need updating:")
|
||||
for (old, new), count in sorted(transitions.items(), key=lambda x: -x[1]):
|
||||
print(f" {count:>6,} {old!r:14s} → {new!r}")
|
||||
print()
|
||||
|
||||
if not args.apply:
|
||||
print("(dry-run — re-run with --apply to write changes)")
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
print("Applying changes…")
|
||||
cur.executemany(
|
||||
"UPDATE events SET record_type = ? WHERE id = ?",
|
||||
[(new, eid) for eid, new in update_ids],
|
||||
)
|
||||
conn.commit()
|
||||
print(f"Done. Updated {cur.rowcount:,} row(s).")
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,91 +0,0 @@
|
||||
"""Re-ingest a prod IDFW + IDFH via the patched save_imported_idf and
|
||||
render both PDFs to confirm charts have data."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import json
|
||||
import datetime
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from sfm import report_pdf
|
||||
import h5py
|
||||
|
||||
|
||||
class FakeDb:
|
||||
def __init__(self, event):
|
||||
self.event = event
|
||||
def get_event(self, _id):
|
||||
return self.event
|
||||
|
||||
|
||||
def to_ts_iso(ts):
|
||||
if ts is None:
|
||||
return None
|
||||
try:
|
||||
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second).isoformat()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def render_case(idf_path: Path, serial: str, out_pdf: Path, h5_summary: bool = True):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
store = WaveformStore(Path(td))
|
||||
ev, rec = store.save_imported_idf(
|
||||
idf_path.read_bytes(),
|
||||
idf_path,
|
||||
idf_report_text=None, # production worst case: no .txt
|
||||
)
|
||||
print(f"=== {idf_path.name} ===")
|
||||
print(f" h5: {rec['hdf5_filename']}, sidecar: {rec['sidecar_filename']}")
|
||||
|
||||
h5p = Path(td) / serial / f"{idf_path.name}.h5"
|
||||
if h5p.exists() and h5_summary:
|
||||
with h5py.File(h5p) as h:
|
||||
for ch in ("Tran", "Vert", "Long", "MicL"):
|
||||
ds = h.get(f"samples/{ch}")
|
||||
if ds is not None:
|
||||
n = ds.shape[0]
|
||||
mx = float(abs(ds[...]).max()) if n else 0
|
||||
print(f" samples/{ch}: n={n} max_abs={mx:.5f}")
|
||||
|
||||
record_type = "Histogram" if idf_path.suffix.upper() == ".IDFH" else "Waveform"
|
||||
fake_row = {
|
||||
"serial": serial,
|
||||
"blastware_filename": rec["filename"],
|
||||
"record_type": record_type,
|
||||
"timestamp": to_ts_iso(ev.timestamp),
|
||||
"sample_rate": ev.sample_rate,
|
||||
"project": ev.project_info.project if ev.project_info else None,
|
||||
"client": ev.project_info.client if ev.project_info else None,
|
||||
"operator": ev.project_info.operator if ev.project_info else None,
|
||||
"sensor_location": ev.project_info.sensor_location if ev.project_info else None,
|
||||
"created_at": None,
|
||||
}
|
||||
rd = report_pdf.gather_report_data(FakeDb(fake_row), store, event_id="test-1")
|
||||
print(f" ReportData: channels={ {k: len(v) for k,v in rd.channels.items()} }")
|
||||
if rd.is_histogram:
|
||||
print(f" histogram n_intervals={rd.histogram_n_intervals} interval_size={rd.histogram_interval_size}")
|
||||
pdf = report_pdf.render_event_report_pdf(rd)
|
||||
out_pdf.write_bytes(pdf)
|
||||
print(f" PDF: {out_pdf} ({len(pdf)} bytes)")
|
||||
|
||||
|
||||
def main():
|
||||
out_dir = Path("/tmp/thor_render_test"); out_dir.mkdir(exist_ok=True)
|
||||
cases = [
|
||||
# IDFW that decoded to preamble-only under the old codec
|
||||
("/home/serversdown/seismo-relay-prod-snap/waveforms/UM6047/UM6047_20250804154137.IDFW", "UM6047"),
|
||||
# IDFW that worked under the old codec (validates no regression)
|
||||
("/home/serversdown/seismo-relay-prod-snap/waveforms/UM6047/UM6047_20250804104450.IDFW", "UM6047"),
|
||||
# IDFH histogram
|
||||
("/home/serversdown/seismo-relay-prod-snap/waveforms/UM6047/UM6047_20250804190047.IDFH", "UM6047"),
|
||||
]
|
||||
for path, serial in cases:
|
||||
render_case(Path(path), serial, out_dir / f"{Path(path).name}.pdf")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,252 +0,0 @@
|
||||
"""
|
||||
test_5a_protocol.py — Regression test for the v0.14.x SUB 5A protocol fixes.
|
||||
|
||||
Verifies that SFM's framing helpers reproduce Blastware's exact wire bytes
|
||||
for every 5A request frame in the 5-1-26 "bwcap3sec" capture, AND that the
|
||||
file builder produces a byte-identical file when fed the BW capture's A5
|
||||
responses.
|
||||
|
||||
Together these two tests protect all four v0.14.x fixes:
|
||||
|
||||
v0.14.0 — STRT-bounded chunk walk (probe @ 0, metadata pages @ 0x1002 +
|
||||
0x1004, samples @ 0x0600..0x1E00 step 0x0200, TERM at residual)
|
||||
v0.14.1 — event-N probe counter is `start_offset`, not `start_offset+0x46`
|
||||
(covered by the multi-event captures, not this 3-sec event-1
|
||||
capture — but the helpers are the same code path)
|
||||
v0.14.2 — file body assembly is contiguous concatenation, no de-duplication
|
||||
v0.14.3 — partial DLE stuffing of `0x10` bytes in 5A params (counter=0x1000
|
||||
wire bytes are `10 10 00`, not `10 00`)
|
||||
|
||||
If any of these fixes regresses, this test fails immediately with a clear
|
||||
byte-level diff.
|
||||
|
||||
Run:
|
||||
python -m pytest tests/test_5a_protocol.py -v
|
||||
or:
|
||||
python tests/test_5a_protocol.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
# Allow running from the project root without installation
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from minimateplus.framing import (
|
||||
S3FrameParser,
|
||||
build_5a_frame,
|
||||
bulk_waveform_params,
|
||||
bulk_waveform_term_v2,
|
||||
)
|
||||
|
||||
|
||||
# ── Capture loading ────────────────────────────────────────────────────────────
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Reference BW MITM capture: BW saving a 3-sec event 0 (start_key=01110000,
|
||||
# end_offset=0x21F2). 17 5A frames: probe + 2 metadata pages + 13 samples + TERM.
|
||||
BW_TX_PATH = os.path.join(
|
||||
ROOT,
|
||||
"bridges/captures/5-1-26/comcheck/bwcap3sec/"
|
||||
"raw_bw_20260501_165723_copy_3sec_waveform_to_disk.bin",
|
||||
)
|
||||
BW_S3_PATH = os.path.join(
|
||||
ROOT,
|
||||
"bridges/captures/5-1-26/comcheck/bwcap3sec/"
|
||||
"raw_s3_20260501_165723_copy_3sec_waveform_to_disk.bin",
|
||||
)
|
||||
|
||||
# BW's saved Blastware file for the same event (used for file-builder verification).
|
||||
BW_SAVED_FILE = os.path.join(
|
||||
ROOT, "example-events/decode_test/5-1-26/bw/M529LKIQ.G10",
|
||||
)
|
||||
|
||||
|
||||
def _split_bw_frames(data: bytes) -> list[bytes]:
|
||||
"""Split BW TX bytes into individual frames (ACK STX … bare ETX)."""
|
||||
frames: list[bytes] = []
|
||||
i = 0
|
||||
while i < len(data):
|
||||
if data[i] != 0x41 or i + 1 >= len(data) or data[i + 1] != 0x02:
|
||||
i += 1
|
||||
continue
|
||||
j = i + 2
|
||||
while j < len(data):
|
||||
if data[j] == 0x03:
|
||||
break
|
||||
if data[j] == 0x10 and j + 1 < len(data):
|
||||
j += 2
|
||||
continue
|
||||
j += 1
|
||||
if j >= len(data):
|
||||
break
|
||||
frames.append(data[i : j + 1])
|
||||
i = j + 1
|
||||
return frames
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def bw_5a_frames() -> list[bytes]:
|
||||
"""All 5A frames from the BW TX capture, in wire order."""
|
||||
if not os.path.exists(BW_TX_PATH):
|
||||
pytest.skip(f"BW capture not found: {BW_TX_PATH}")
|
||||
raw = open(BW_TX_PATH, "rb").read()
|
||||
frames = [
|
||||
f for f in _split_bw_frames(raw)
|
||||
if len(f) >= 6 and f[5] == 0x5A # body[3] == 0x5A (SUB)
|
||||
]
|
||||
assert len(frames) == 17, f"expected 17 5A frames in capture, got {len(frames)}"
|
||||
return frames
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def bw_a5_frames():
|
||||
"""All A5 (response) frames from the matching S3 capture."""
|
||||
if not os.path.exists(BW_S3_PATH):
|
||||
pytest.skip(f"BW S3 capture not found: {BW_S3_PATH}")
|
||||
raw = open(BW_S3_PATH, "rb").read()
|
||||
p = S3FrameParser()
|
||||
p.feed(raw)
|
||||
a5 = [f for f in p.frames if f.sub == 0xA5]
|
||||
assert len(a5) == 17, f"expected 17 A5 frames in capture, got {len(a5)}"
|
||||
return a5
|
||||
|
||||
|
||||
# ── 5A request frame byte-perfect verification ────────────────────────────────
|
||||
|
||||
KEY4 = bytes.fromhex("01110000") # start_key for the 3-sec event 0
|
||||
END_OFFSET = 0x21F2 # parsed from STRT in the BW capture
|
||||
LAST_CHUNK_COUNTER = 0x1E00 # last full 0x0200-byte chunk before TERM
|
||||
|
||||
SAMPLE_COUNTERS = (
|
||||
0x0600, 0x0800, 0x0A00, 0x0C00, 0x0E00,
|
||||
0x1000, 0x1200, 0x1400, 0x1600, 0x1800,
|
||||
0x1A00, 0x1C00, 0x1E00,
|
||||
)
|
||||
|
||||
|
||||
def _meta_params(key: bytes, counter: int) -> bytes:
|
||||
"""Build the 12-byte metadata-page params block (matches BW for 0x1002 / 0x1004)."""
|
||||
return bytes(
|
||||
[
|
||||
0x00, key[0], key[1],
|
||||
(counter >> 8) & 0xFF, counter & 0xFF,
|
||||
0, 0, 0, 0, 0, 0, 0,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_probe_frame_byte_perfect(bw_5a_frames):
|
||||
"""Probe @ counter=0x0000 (frame 0)."""
|
||||
sfm = build_5a_frame(0x1002, bulk_waveform_params(KEY4, 0, is_probe=True))
|
||||
assert sfm == bw_5a_frames[0], (
|
||||
f"\nSFM: {sfm.hex()}\nBW: {bw_5a_frames[0].hex()}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("idx,counter", [(1, 0x1002), (2, 0x1004)])
|
||||
def test_metadata_page_frames_byte_perfect(bw_5a_frames, idx, counter):
|
||||
"""Metadata pages @ counter=0x1002 and 0x1004 (frames 1 and 2)."""
|
||||
sfm = build_5a_frame(0x1002, _meta_params(KEY4, counter))
|
||||
assert sfm == bw_5a_frames[idx], (
|
||||
f"\nSFM: {sfm.hex()}\nBW: {bw_5a_frames[idx].hex()}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("i,counter", list(enumerate(SAMPLE_COUNTERS)))
|
||||
def test_sample_chunk_frames_byte_perfect(bw_5a_frames, i, counter):
|
||||
"""
|
||||
Sample chunks @ counter=0x0600..0x1E00, step 0x0200 (frames 3..15).
|
||||
|
||||
Critically, frame 8 (counter=0x1000) requires the v0.14.3 partial DLE
|
||||
stuffing fix — wire params include `10 10 00` for the counter, not `10 00`.
|
||||
"""
|
||||
sfm = build_5a_frame(0x1002, bulk_waveform_params(KEY4, counter))
|
||||
bw_idx = 3 + i
|
||||
assert sfm == bw_5a_frames[bw_idx], (
|
||||
f"\ncounter=0x{counter:04X}"
|
||||
f"\nSFM: {sfm.hex()}"
|
||||
f"\nBW: {bw_5a_frames[bw_idx].hex()}"
|
||||
)
|
||||
|
||||
|
||||
def test_term_frame_byte_perfect(bw_5a_frames):
|
||||
"""TERM frame at residual (frame 16)."""
|
||||
offset_word, params = bulk_waveform_term_v2(KEY4, END_OFFSET, LAST_CHUNK_COUNTER)
|
||||
sfm = build_5a_frame(offset_word, params)
|
||||
assert sfm == bw_5a_frames[16], (
|
||||
f"\nSFM: {sfm.hex()}\nBW: {bw_5a_frames[16].hex()}"
|
||||
)
|
||||
|
||||
|
||||
def test_strt_end_offset_parsing(bw_a5_frames):
|
||||
"""The probe response (A5[0]) carries STRT at byte 17 with end_offset=0x21F2."""
|
||||
from minimateplus.framing import parse_strt_end_offset
|
||||
|
||||
end_offset = parse_strt_end_offset(bw_a5_frames[0].data)
|
||||
assert end_offset == END_OFFSET, (
|
||||
f"expected end_offset=0x{END_OFFSET:04X}, got "
|
||||
f"{f'0x{end_offset:04X}' if end_offset is not None else 'None'}"
|
||||
)
|
||||
|
||||
|
||||
# ── File builder byte-perfect verification ────────────────────────────────────
|
||||
|
||||
def test_blastware_file_builder_byte_perfect(bw_a5_frames):
|
||||
"""
|
||||
Feed the BW capture's A5 frames into write_blastware_file() and verify the
|
||||
output is byte-identical to BW's saved M529LKIQ.G10 reference file.
|
||||
|
||||
This protects the v0.14.2 strip-removal fix and the file-builder skip
|
||||
values (probe=38, meta=13, samples=12, TERM=11).
|
||||
"""
|
||||
if not os.path.exists(BW_SAVED_FILE):
|
||||
pytest.skip(f"BW saved file not found: {BW_SAVED_FILE}")
|
||||
|
||||
import tempfile
|
||||
|
||||
from minimateplus.blastware_file import write_blastware_file
|
||||
from minimateplus.models import Event
|
||||
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = KEY4
|
||||
ev.rectime_seconds = 3
|
||||
ev.timestamp = None # let the builder pull the footer from the TERM frame
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".G10", delete=False) as tf:
|
||||
tmp_path = tf.name
|
||||
try:
|
||||
write_blastware_file(ev, bw_a5_frames, tmp_path)
|
||||
sfm_bytes = open(tmp_path, "rb").read()
|
||||
finally:
|
||||
os.unlink(tmp_path)
|
||||
|
||||
bw_bytes = open(BW_SAVED_FILE, "rb").read()
|
||||
|
||||
assert len(sfm_bytes) == len(bw_bytes), (
|
||||
f"file size mismatch: SFM={len(sfm_bytes)} BW={len(bw_bytes)}"
|
||||
)
|
||||
|
||||
if sfm_bytes != bw_bytes:
|
||||
# Find first diff for actionable error message
|
||||
for i in range(len(bw_bytes)):
|
||||
if bw_bytes[i] != sfm_bytes[i]:
|
||||
ctx_start = max(0, i - 8)
|
||||
ctx_end = min(len(bw_bytes), i + 16)
|
||||
pytest.fail(
|
||||
f"file diverges at byte 0x{i:04X}\n"
|
||||
f" BW : {bw_bytes[ctx_start:ctx_end].hex()}\n"
|
||||
f" SFM: {sfm_bytes[ctx_start:ctx_end].hex()}\n"
|
||||
f" {' ' * (i - ctx_start)}^^"
|
||||
)
|
||||
|
||||
|
||||
# ── Standalone runner ─────────────────────────────────────────────────────────
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(pytest.main([__file__, "-v"]))
|
||||
@@ -123,52 +123,3 @@ def test_upsert_updates_zc_freq(tmp_path: Path):
|
||||
row = db.query_events(serial="BE11529")[0]
|
||||
assert row["vert_zc_freq"] == 91.0
|
||||
|
||||
|
||||
def test_backfill_zc_freq_from_sidecar(tmp_path: Path):
|
||||
import importlib
|
||||
mod = importlib.import_module("scripts.backfill_event_zc_freq")
|
||||
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
# Insert an event WITHOUT freq (simulates a pre-feature row), with a filename.
|
||||
from minimateplus.models import Event, Timestamp
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex("01110000")
|
||||
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0,
|
||||
month=6, day=25, hour=8, minute=50, second=0)
|
||||
ev.record_type = "Waveform"
|
||||
db.insert_events([ev], serial="BE11529",
|
||||
waveform_records={"01110000": {"filename": "M529AAAA.AB0T"}})
|
||||
|
||||
class FakeStore:
|
||||
def load_sidecar(self, serial, filename):
|
||||
return {"bw_report": {
|
||||
"peaks": {"vert": {"zc_freq_hz": 85.0},
|
||||
"tran": {"zc_freq_hz": 100.0, "zc_freq_above_range": True}},
|
||||
"mic": {"zc_freq_hz": 51.0}}}
|
||||
|
||||
counts = mod.backfill_zc_freq(db, FakeStore())
|
||||
assert counts["updated"] == 1
|
||||
row = db.query_events(serial="BE11529")[0]
|
||||
assert row["vert_zc_freq"] == 85.0
|
||||
assert row["tran_zc_above_range"] == 1
|
||||
assert row["mic_zc_freq"] == 51.0
|
||||
|
||||
|
||||
def test_backfill_skips_event_without_sidecar(tmp_path: Path):
|
||||
import importlib
|
||||
mod = importlib.import_module("scripts.backfill_event_zc_freq")
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
from minimateplus.models import Event, Timestamp
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex("01110000")
|
||||
ev.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0,
|
||||
month=6, day=25, hour=8, minute=50, second=0)
|
||||
db.insert_events([ev], serial="BE11529",
|
||||
waveform_records={"01110000": {"filename": "M529AAAA.AB0T"}})
|
||||
|
||||
class NoneStore:
|
||||
def load_sidecar(self, serial, filename): return None
|
||||
|
||||
counts = mod.backfill_zc_freq(db, NoneStore())
|
||||
assert counts["updated"] == 0
|
||||
assert counts["skipped_no_sidecar"] == 1
|
||||
Reference in new issue
Block a user