Compare commits
99
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dedf1f02c9 | ||
|
|
b2ef02ebcc | ||
|
|
a3b69a62a6 | ||
|
|
306104354b | ||
|
|
4c58a532de | ||
|
|
9bb95003e9 | ||
|
|
260bf0bc67 | ||
|
|
ef1e99b0a0 | ||
|
|
e449ac04af | ||
|
|
4f8224a751 | ||
|
|
5d3963b545 | ||
|
|
0f6c9d930f | ||
|
|
b6b6ee0331 | ||
|
|
686ab6e7a6 | ||
|
|
37043a47e9 | ||
|
|
4a581e0e67 | ||
|
|
7aae0208f8 | ||
|
|
5ffa92ab87 | ||
|
|
f73c8eec91 | ||
|
|
23e4f585a8 | ||
|
|
d9cc5f1780 | ||
|
|
5247e78669 | ||
|
|
ac67e83bcf | ||
|
|
c982512e17 | ||
|
|
e64e3bcd3e | ||
|
|
54c4182023 | ||
|
|
a894b001b1 | ||
|
|
cec82038ea | ||
|
|
2539f903de | ||
|
|
eb92b13aac | ||
|
|
aebb5644bd | ||
|
|
ddf6a73292 | ||
|
|
1744eb1803 | ||
|
|
9a71d5b914 | ||
|
|
248276d141 | ||
|
|
12401b917c | ||
|
|
6e2994acdd | ||
|
|
b56eb8c692 | ||
|
|
280b3d25ec | ||
|
|
7edd0a1265 | ||
|
|
916e6fcabb | ||
|
|
31660d24e9 | ||
|
|
25386cab8b | ||
|
|
6cb619ecc4 | ||
|
|
1ed86244d0 | ||
|
|
b2c565f217 | ||
|
|
43f440812a | ||
|
|
23e83908c2 | ||
|
|
bee118506b | ||
|
|
defd17d9c2 | ||
|
|
e42956a20b | ||
|
|
9fd52ddabb | ||
|
|
9b71ead44b | ||
|
|
1bccc44b88 | ||
|
|
a3cc44d30a | ||
|
|
6a73523e4d | ||
|
|
780b45a371 | ||
|
|
f6abe3caa0 | ||
|
|
ad2702d4bf | ||
|
|
86325b9bab | ||
|
|
6381dcb312 | ||
|
|
53c05d93e2 | ||
|
|
a5888e1b5c | ||
|
|
b9f8bbb220 | ||
|
|
b59f886cb7 | ||
|
|
87aec3f4d1 | ||
|
|
ace542cba5 | ||
|
|
8cbda09917 | ||
|
|
3457ed0072 | ||
|
|
d21e3b5298 | ||
|
|
ad2b553c7b | ||
|
|
dfbc8b8520 | ||
|
|
411ef8139e | ||
|
|
ed926de3f4 | ||
|
|
5d5441604b | ||
|
|
784f2cca36 | ||
|
|
6abfadae4f | ||
|
|
fd0e28657d | ||
|
|
c14a8c54db | ||
|
|
460006e5cd | ||
|
|
8710b8f327 | ||
|
|
db657bcac9 | ||
|
|
35842ac50a | ||
|
|
49a524d0d4 | ||
|
|
9ef424d098 | ||
|
|
ed6982c512 | ||
|
|
d506ebc103 | ||
|
|
e949232875 | ||
|
|
bc5a2d3f19 | ||
|
|
88549bc659 | ||
|
|
76bce0b5a3 | ||
|
|
7183b953e4 | ||
|
|
c3c7fe559c | ||
|
|
fa9d3cdef2 | ||
|
|
c4648c1959 | ||
|
|
0e89125495 | ||
|
|
fffb363b2b | ||
|
|
e8682d49ad | ||
|
|
31d691b40b |
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
/bridges/captures/
|
||||
/example-events/
|
||||
|
||||
/tests/fixtures/
|
||||
/manuals/
|
||||
|
||||
# Python build artifacts
|
||||
|
||||
+594
@@ -4,6 +4,600 @@ All notable changes to seismo-relay are documented here.
|
||||
|
||||
---
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
---
|
||||
|
||||
## v0.26.0 — 2026-08-27
|
||||
|
||||
**Series-3 decode correctness.** Two body-model rewrites, a systematic
|
||||
scale error affecting every geophone reading ever produced, a recovered
|
||||
file format, and two artifact-hygiene bugs where stale files outlived the
|
||||
decodes that made them. All 11,603 series-3 binaries in the production
|
||||
snapshot now pass every check.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Series-3 health sweep: 11,603 / 11,603 binaries now clean on every check.**
|
||||
Swept every series-3 file with the live decoder against five independent
|
||||
checks — decode exceptions, zero samples, unequal geo channel lengths, peaks
|
||||
above range full scale, decoded peak vs the device-reported PPV, and waveform
|
||||
length vs the declared record time. Three real defects surfaced and were
|
||||
fixed:
|
||||
|
||||
- **`block[22]` is not a constant and must not be tested.** It was documented
|
||||
as always `0x00` but carries data on loud blocks, and rejecting those threw
|
||||
away the interval holding the event peak.
|
||||
`BE18350/T350L7HR.NL0H` block 92 has `block[22]=0x26` and a Tran peak of
|
||||
`0x0563` = 1379 counts = **6.895 in/s** — exactly the device-reported PPV —
|
||||
while the file as a whole decoded to 0.015 in/s. `block[0]==0x00`,
|
||||
`block[4]==0x0A` and the 4-byte tail are six bytes of constraint, which is
|
||||
what keeps trailer content out.
|
||||
|
||||
- **Block-model dispatch now goes on signature strength, not on whichever
|
||||
decoder returns first.** A multi-interval body also yields scattered
|
||||
standard-tail blocks by coincidence; dispatching on "first non-empty"
|
||||
handed 193 BE18193 files to the standard walker and produced peaks of
|
||||
149 in/s against a 10 in/s full scale.
|
||||
|
||||
- **Multi-interval stride detection requires the block counter to increment
|
||||
by exactly 1.** Without it the detector false-positives on ordinary
|
||||
standard-block bodies: those carry a header every 32 bytes, and
|
||||
`192 = 12 + 20×9` and `512 = 12 + 20×25` are both multiples of 32, so a
|
||||
stride "fits" while actually skipping 6 or 16 real blocks. That misrouted
|
||||
9,082 files.
|
||||
|
||||
Partial-block garbage is now trimmed within the final block only, stopping at
|
||||
the first slot with a non-zero tail word or a geo peak above full scale.
|
||||
Trimming purely from the end left garbage stranded behind one slot that
|
||||
happened to have a zero tail word; trimming on the tail word alone truncated
|
||||
four BE9440 files by up to 2,800 intervals.
|
||||
|
||||
- **Sub-minute histogram intervals are packed several to a block — 415 files
|
||||
recovered.** The device always writes one minute of data per block, so a
|
||||
shorter interval just means more intervals in a longer block:
|
||||
|
||||
| interval | intervals/block | stride |
|
||||
|---|---|---|
|
||||
| 1 min | 1 | 32 (the standard block) |
|
||||
| 15 s | 4 | 92 |
|
||||
| 2 s | 30 | 612 |
|
||||
|
||||
`stride = 12 + n * 20`. Each 20-byte record carries 8 × uint16
|
||||
**little**-endian values — peak and half-period per channel — plus a 2-word
|
||||
tail whose first word is `0000` on every real interval (a session ending
|
||||
mid-block leaves buffer garbage in the remaining slots, which decoded as
|
||||
peaks thousands of times the real value until that check was added).
|
||||
**The standard 32-byte block is big-endian; this variant is not.**
|
||||
|
||||
These 415 files (216 on BE18193 at 2 s intervals, 199 on BE9440 at 15 s)
|
||||
previously decoded to nothing at all — and before that were being accepted
|
||||
by the *waveform* codec, which returned garbage peaking up to 400× the
|
||||
device-reported PPV.
|
||||
|
||||
Ground truth `BE9440/K440L3AQ.T70H` — 5,710 intervals — matches its
|
||||
Blastware ASCII export on **17,130/17,130** geo peaks, **22,840/22,840**
|
||||
frequencies and **5,710/5,710** mic dB(L) values. Across all 455 affected
|
||||
files, **1,354/1,365 (99.2%)** channel peaks match the device-reported PPV;
|
||||
the 11 that don't are under-reads on BE9440 where the walk stops early.
|
||||
|
||||
- **`backfill_sidecars.py` now removes a stale `.h5` when nothing decodes.**
|
||||
It previously skipped the write "so we don't replace whatever's there with an
|
||||
empty placeholder", which silently preserved output from a superseded
|
||||
decoder. After the record-chain fix, 415 histogram files stopped decoding (an
|
||||
unmapped block variant on BE18193 and BE9440) but kept `.h5` files whose peaks
|
||||
ran up to **400× the device's own reported PPV** — garbage feeding the charts
|
||||
and the false-trigger detector with nothing marking it. Reports a
|
||||
`stale_h5_removed` count.
|
||||
|
||||
- **The series-3 waveform body is a RECORD CHAIN, not a tag stream — this
|
||||
supersedes the segment-header model, including the fixes made earlier the
|
||||
same day.**
|
||||
|
||||
Records are self-delimiting. `off+2` is a `uint16 BE` length and
|
||||
`next_record = off + 2 + len`; the chain ends on a record whose `chan_id` is
|
||||
`0x06`. `off+8` carries a 3-valued mode enum:
|
||||
|
||||
| mode | header | data section |
|
||||
|---|---|---|
|
||||
| `02 00` | 14 B | anchors, then **cumulative deltas** |
|
||||
| `01 00` | 10 B | no anchors, **absolute** values |
|
||||
| `00 03` | 10 B | **no tags at all** — raw 12-bit packed absolute |
|
||||
|
||||
**`40 NN` is an ordinary int16 BE data block** (`2*NN + 2`), never a segment
|
||||
header. Reading it as a `2*NN + 16` header is what made walks drift — and the
|
||||
"variable-prefix segment descriptors" reported earlier today were not a format
|
||||
feature at all, just walker drift of exactly
|
||||
`4 - (old_stop - true_record_start)` on all 25 affected files.
|
||||
|
||||
Measured against the production snapshot:
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| all four channels equal length | 156 / 1388 | **1388 / 1388** |
|
||||
| ASCII sample-count exact | 72 / 75 | **75 / 75** |
|
||||
| ASCII fully exact | 70 / 75 | **73 / 75** |
|
||||
| device PPV, waveform (live decode) | 1288 / 1306 | **1306 / 1306** |
|
||||
| device PPV, histogram (live decode) | 4434 / 4459 | **4458 / 4459** |
|
||||
|
||||
Mean absolute PPV ratio error on waveforms is now 0.00000. The 2 remaining
|
||||
ASCII imperfections differ by exactly 1 LSB on samples sitting at the
|
||||
±10.000 in/s rail.
|
||||
|
||||
**This also eliminated the walker-over-read class.** 24 of those 35 files
|
||||
were histograms that `read_blastware_file` fed to the *waveform* codec first;
|
||||
the old walker accepted them and returned garbage (one yielded 98,923
|
||||
"intervals"), while the record-chain decoder correctly returns `None` so they
|
||||
fall through to `histogram_codec`.
|
||||
|
||||
`00 03` records are decoded rather than skipped. Skipping them does not merely
|
||||
lose samples — it silently shifts the time base of everything after them on
|
||||
that channel (observed on `BE9558/K558LOF2.820W`, MicL displaced by exactly
|
||||
512 samples with nothing marking the gap).
|
||||
|
||||
Footer detection now prefers whichever `0e 08` candidate yields a chain
|
||||
terminating on `0x06`, since the signature can occur inside a sample stream.
|
||||
Blast radius: 1 file of 1,388.
|
||||
|
||||
The superseded model is retained as `decode_waveform_legacy` and pinned by
|
||||
`micromate/idf_file.py`, whose Thor IDFW body-offset search trial-decodes
|
||||
candidate offsets and keeps whichever yields the most samples — the new
|
||||
decoder correctly returns `None` where the old one returned garbage, which
|
||||
changes that heuristic's winner. Switching Thor over is deferred until that
|
||||
search is reworked to use the record chain directly.
|
||||
|
||||
- **Series-3 histogram block is uniformly big-endian, and the stream's final
|
||||
block has its own tail — the codec was clipping large peaks and dropping the
|
||||
last interval of nearly every histogram.**
|
||||
|
||||
- **Peaks and half-periods are `uint16` big-endian**, not `uint8` plus an
|
||||
"annotation" byte: `T_peak` `[5:7]`, `T_halfperiod` `[7:9]`, `V_peak`
|
||||
`[9:11]`, and so on. Only `block_ctr` `[2:4]` is little-endian. The old
|
||||
model silently **clipped any peak above 1.275 in/s** — the final interval
|
||||
of `BE18193/T193LQ9K.OE0H` reads 8.270 in/s in Blastware's own export and
|
||||
decoded as 0.590. The "annotation" byte was the half-period's high byte,
|
||||
which is why it was non-zero exactly on the sub-Hz intervals BW renders
|
||||
as `<1.0`.
|
||||
- **The marker is `block[4]` alone.** Testing `[4:6]` as a `uint16 LE`
|
||||
marker forced `block[5] == 0` — which is what capped the peak at one byte
|
||||
in the first place.
|
||||
- **The last block of each stream carries tail `9c 06 00 42`** instead of
|
||||
`1e 0a 00 00`, with arbitrary bytes at `[21:23]`. Rejecting it dropped
|
||||
the final interval of nearly every histogram, and that interval is
|
||||
frequently the one holding the event peak — so the file's reported PPV
|
||||
came out low.
|
||||
|
||||
Verified against **1211 production histograms** paired with their preserved
|
||||
Blastware ASCII exports, which carry a full per-interval data table:
|
||||
**1211/1211 now decode exactly** (interval count plus every per-interval
|
||||
peak), and 842,442 per-interval frequency comparisons match with zero
|
||||
mismatches. Before this fix: **1 of 1196**.
|
||||
|
||||
`decode_histogram_body_full` records now expose `is_terminal` in place of
|
||||
the removed `annotations` tuple.
|
||||
|
||||
- **Geophone full scale is 32000 ADC counts, not 32768 — every geo reading was
|
||||
2.3% low.** The verified body codec emits geo samples in 16-count units whose
|
||||
documented LSB is exactly 0.005 in/s, and `decoded_to_adc_counts` multiplies
|
||||
by 16, so one ADC count is `0.005/16` in/s and Normal range (10.000 in/s) is
|
||||
`10.0 / (0.005/16)` = **32000** counts. Both `sfm/event_hdf5.py` and
|
||||
`minimateplus/event_file_io.py` divided by 32768, scaling every geophone
|
||||
sample and every derived peak down by `1 - 32000/32768` = **2.34%**.
|
||||
|
||||
Measured against 216 per-channel comparisons with preserved Blastware ASCII
|
||||
exports: **32768 → 151/216 exact** (worst error 0.238 in/s on a 10 in/s
|
||||
event); **32000 → 216/216 exact**, worst error 0.005 in/s (exactly 1 LSB —
|
||||
pure quantization). The error scales with amplitude, so it was invisible on
|
||||
quiet events and worst on the loud ones that matter for compliance.
|
||||
|
||||
The mic path is unaffected — it back-solves its own per-count factor from the
|
||||
device-reported peak.
|
||||
|
||||
**Scope:** the scale lives in `_samples_to_float`, which every event passes
|
||||
through regardless of which codec produced the samples — so this affected
|
||||
**waveforms, histograms and series-4 (Thor IDF) alike**, not just waveforms.
|
||||
Verified after regeneration: series-3 histogram peaks vs their ASCII reports
|
||||
now sit at a median ratio of 1.0000 across 1,137 comparisons (0.9766 under
|
||||
32768); series-4 peaks vs device peaks moved from a median 0.960 to 0.983
|
||||
across 1,468 comparisons. The four block-framing fixes below are
|
||||
waveform-only — histograms decode via `histogram_codec.decode_histogram_body`,
|
||||
which is untouched.
|
||||
|
||||
- **Series-3 waveform codec: four block-framing cases caused silent channel
|
||||
truncation.** `walk_body` hit its unknown-tag `break` mid-stream and every
|
||||
channel decoded after that point came out short — typically Vert/Long/MicL,
|
||||
sometimes at a third of their true length, with no error raised.
|
||||
|
||||
- **Wide-NN RLE `0X NN`** — the 12-bit NN encoding already handled for
|
||||
`1X NN` / `2X NN` also applies to the `00 NN` RLE tag. Runs longer than
|
||||
252 samples must use the wide form (e.g. `01 0c` = 268 repeats).
|
||||
- **`30 NN` with NN > 0x10** — the `0 < NN <= 0x10` guard was arbitrary;
|
||||
data-section `30 NN` blocks reach at least NN = 0x18. The length formula
|
||||
(`NN × 1.5 + 2`) was already correct.
|
||||
- **Variable-width `40 NN` segment headers** — NN is the *count of
|
||||
previous-channel continuation deltas*, so the header is `2 × NN + 16`
|
||||
bytes and every field after the deltas shifts by `2 × NN`. Only `40 02`
|
||||
(20 bytes) was handled; `40 01` (18) and `40 03` (22) both occur.
|
||||
- **Tagless segment headers** — a segment header can appear with no
|
||||
`40 NN` tag at all: just the 14-byte tail
|
||||
`[field2:2][len:2][channel_id:4][marker:2][anchors:4]`. This is the NN=0
|
||||
case (no continuation deltas needed, so no tag and no delta bytes). It is
|
||||
where the walk stopped in 7 of the 8 events still truncating after the
|
||||
first three fixes.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Segment channel now comes from the header's own channel-id byte** rather
|
||||
than from rotation position. The field previously documented as a
|
||||
"monotonic uint32 LE counter" is really `[channel][00][00][segment_index]`
|
||||
with `0x46`=Tran `0x47`=Vert `0x48`=Long `0x49`=MicL — verified on
|
||||
**1697 of 1697** segment headers across the ground-truth corpus with zero
|
||||
disagreements. Rotation-by-position is kept only as a fallback for unknown
|
||||
ids; it was fragile because a single missed or extra header (exactly what
|
||||
tagless headers caused) desynced every channel after it.
|
||||
|
||||
- **`parse_segment_header` return shape** — now `n_prev_deltas`,
|
||||
`prev_deltas`, `marker`, `anchors`, `channel`, `segment_index` in place of
|
||||
the fixed-offset `anchor_bytes` / `fixed_pattern` / `tail` keys. The old
|
||||
`fixed_pattern` (`02 00 00 01`) conflated the 2-byte constant marker with
|
||||
the first anchor. `counter` is retained as the raw uint32 of the id field.
|
||||
|
||||
### Verification
|
||||
|
||||
Against the 75 ground-truth events (BW binary paired with its preserved
|
||||
`_ASCII.TXT` export), decoding end-to-end through the production path:
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| exact (full length, within 1 LSB) | 37 | **72** |
|
||||
| truncated | 23 | **3** |
|
||||
| full length, value error > 2 LSB | 15 | **0** |
|
||||
|
||||
Worst remaining error among the 72: 0.0050 in/s = exactly 1 LSB.
|
||||
|
||||
No regressions — the byte-exact fixture suite still passes, and the full-suite
|
||||
failure list is unchanged from baseline (16 pre-existing failures from
|
||||
gitignored fixtures).
|
||||
|
||||
### Notes
|
||||
|
||||
- **The "DC offset" symptom is _not_ a decode bug.** Events whose geo trace
|
||||
sits at a constant level instead of oscillating around zero
|
||||
(dominant-axis `|mean| / peak` >> 0) reproduce *exactly* in Blastware's own
|
||||
ASCII export — e.g. `BE12599/N599LQD7.8E0W` Tran reads mean +0.345,
|
||||
min +0.335, max +0.355 in both. It is a known recurring hardware fault (the
|
||||
operators call it an "offset"): the affected channel's baseline exceeds the
|
||||
unit's own geo trigger level, so the unit retriggers continuously and floods
|
||||
the ACH queue with garbage events. Store-wide it affects 2 units of 21 across
|
||||
6 episodes; see `scratch/offset_candidates.csv` and the project memory notes.
|
||||
|
||||
- ~~**Still open:** 3 of 75 ground-truth events truncate at a segment-header
|
||||
variant with a variable-width prefix.~~ **Resolved later the same day** — the
|
||||
record-chain rewrite (above) showed there is no variable prefix; it was
|
||||
walker drift. All 75 are now sample-count exact.
|
||||
|
||||
- **Still open after this release:**
|
||||
- **Series-4 (Thor / Micromate) is not verified** — UM-series sits at ~48%
|
||||
against device peaks with a ~1.7% systematic bias and a near-zero tail.
|
||||
Thor IDFW is pinned to `decode_waveform_legacy` deliberately.
|
||||
- **14 sensitive-range files** show a decoded/truth ratio of exactly 8.0
|
||||
(= 10.0/1.25) — a units bug, not a codec one. Never chased.
|
||||
- **`backfill_sidecars.py --force` also inserts DB rows** for store files
|
||||
that have none (1,286 on the snapshot; one-time per store), and the
|
||||
dry-run does not report that count before you commit to it.
|
||||
- **Verification is uneven:** per-sample proof on the 11% of files with a
|
||||
preserved `_ASCII.TXT`, peak-and-structure consistency on the other 89%.
|
||||
|
||||
---
|
||||
|
||||
## v0.25.0 — 2026-08-25
|
||||
|
||||
**reviewed_real 3-state review flag + twin review-propagation.** The
|
||||
`events` table and the `/db/events` feed now carry `reviewed_real`, a
|
||||
3-state review flag mutually exclusive with `false_trigger`, mirrored from
|
||||
the sidecar review block — plus histogram/waveform twin review-propagation
|
||||
(flagging one flags both, matched by serial + identical PVS + timestamp
|
||||
window).
|
||||
|
||||
### Added
|
||||
|
||||
- **`events` column** `reviewed_real` — `INTEGER NOT NULL DEFAULT 0`, added
|
||||
via the existing incremental `_migrate` ADD COLUMN pass (auto-migrates on
|
||||
`SeismoDb()` construction, no manual migration). `query_events` /
|
||||
`get_event` (and thus `/db/events`) return it automatically (`SELECT *`).
|
||||
- **Mutual exclusivity with `false_trigger`** — setting `reviewed_real=1`
|
||||
clears `false_trigger`, and vice versa, enforced on both review paths:
|
||||
the sidecar review PATCH (`update_event_review`) and the quick
|
||||
`PATCH /db/events/{id}/false_trigger` endpoint (`set_false_trigger`).
|
||||
- **`find_twins`** — matches an event's histogram/waveform twins by serial +
|
||||
identical peak-vector-sum + a timestamp window.
|
||||
- **`propagate_review_to_twins`** — copies an event's `false_trigger`/
|
||||
`reviewed_real` state onto its twins, wired into both the
|
||||
`PATCH /db/events/{id}/sidecar` review path and the quick
|
||||
`PATCH /db/events/{id}/false_trigger` path, so flagging one flags both
|
||||
regardless of which endpoint made the change.
|
||||
|
||||
---
|
||||
|
||||
## v0.24.0 — 2026-08-22
|
||||
|
||||
**Waveform-shape metrics on events.** The `events` table and the `/db/events`
|
||||
feed now carry per-event crest factor and points-near-peak, computed from the
|
||||
decoded waveform samples at ingest — groundwork for Terra-View's
|
||||
false-trigger detection (Phase B).
|
||||
|
||||
### Added
|
||||
|
||||
- **`events` columns** `shape_crest_factor`, `shape_near_peak_count`,
|
||||
`shape_sample_count`, `shape_axis`. Added via the existing incremental
|
||||
`_migrate` ADD COLUMN pass — **auto-migrates on `SeismoDb()` construction,
|
||||
no manual migration**. `query_events` / `get_event` (and thus `/db/events`)
|
||||
return them automatically (`SELECT *`).
|
||||
- **Populated at ingest** — crest factor + near-peak-count are computed from
|
||||
the decoded samples in every save path (`shape_from_h5`/
|
||||
`shape_from_samples`), and `insert_events` persists them on INSERT and
|
||||
UPSERT.
|
||||
- **Backfill** `scripts/backfill_event_shape.py` — fills the columns for
|
||||
existing events from their on-disk `.h5` waveform samples (idempotent,
|
||||
UPDATE-only).
|
||||
|
||||
### Upgrade Notes
|
||||
|
||||
Run the backfill once after deploying, against the events DB + waveform store:
|
||||
`python3 scripts/backfill_event_shape.py --db-path <seismo_relay.db> --store-root <waveforms/>`
|
||||
Events with no decodable samples (or no waveform file) stay NULL and render
|
||||
"—" downstream.
|
||||
|
||||
---
|
||||
|
||||
## v0.23.0 — 2026-08-04
|
||||
|
||||
**Per-channel ZC frequency in the events store.** The `events` table and the
|
||||
`/db/events` feed now carry per-channel zero-crossing frequency, so consumers
|
||||
(Terra-View's Vibration Summary) get frequency in bulk instead of one sidecar
|
||||
fetch per event.
|
||||
|
||||
### Added
|
||||
|
||||
- **`events` columns** `tran_zc_freq`, `vert_zc_freq`, `long_zc_freq`, `mic_zc_freq`
|
||||
(Hz) + `*_zc_above_range` flags (the Blastware `>N Hz` device-ceiling case). Added
|
||||
via the existing incremental `_migrate` ADD COLUMN pass — **auto-migrates on
|
||||
`SeismoDb()` construction, no manual migration**. `query_events` / `get_event`
|
||||
(and thus `/db/events`) return them automatically (`SELECT *`).
|
||||
- **Populated at ingest** — `PeakValues` gains the ZC-freq fields; both
|
||||
`apply_report_to_event` and `apply_bw_report_dict_to_event` copy per-channel
|
||||
`zc_freq_hz` / `zc_freq_above_range` from the parsed report onto them, and
|
||||
`insert_events` persists them on INSERT and UPSERT.
|
||||
- **Backfill** `scripts/backfill_event_zc_freq.py` — fills the columns for existing
|
||||
events from their `.sfm.json` sidecars (idempotent, UPDATE-only).
|
||||
|
||||
### Fixed
|
||||
|
||||
- `sfm/server.py` app-version string was stale at `0.17.0`; now tracks the real version.
|
||||
|
||||
### Upgrade Notes
|
||||
|
||||
Run the backfill once after deploying, against the events DB + waveform store:
|
||||
`python3 scripts/backfill_event_zc_freq.py --db-path <seismo_relay.db> --store-root <waveforms/>`
|
||||
Events whose sidecar carries no frequency (or that have no sidecar) stay NULL and
|
||||
render "—" downstream.
|
||||
|
||||
---
|
||||
|
||||
## v0.22.0 — 2026-07-03
|
||||
|
||||
Full-snapshot bundle support (SFM side). Adds the DB-snapshot, recent-waveform,
|
||||
and gated-restore endpoints Terra-View drives to pull a complete prod→dev refresh
|
||||
— the `seismo_relay.db` plus the waveform files behind recent events — in one
|
||||
pass. Pairs with **Terra-View v0.17.0**'s "Create full snapshot (incl. SFM)"
|
||||
control on Settings → Database. New logic lives in `sfm/db_snapshot.py`, kept
|
||||
out of `server.py` so it's unit-testable without HTTP.
|
||||
|
||||
### Added
|
||||
|
||||
- **`GET /db/snapshot`** — streams a WAL-safe point-in-time copy of
|
||||
`seismo_relay.db`, taken through the SQLite online backup API (not a raw
|
||||
file grab), so the download stays consistent even while the ACH server is
|
||||
writing under WAL.
|
||||
- **`GET /db/waveforms/recent.zip?n=…`** — zips the on-disk files (event file
|
||||
+ its `.h5` / sidecar siblings) for the *n* most-recent events, arcname
|
||||
`<serial>/<filename>`, so a dev box can restore chart-openable events without
|
||||
hauling the entire waveform store. Events with no resolvable files on disk
|
||||
are skipped.
|
||||
- **`POST /db/restore`** — gated by `SFM_DB_RESTORE_ENABLED` (dormant → 404
|
||||
unless explicitly enabled; dev-only). Validates the uploaded DB first, takes
|
||||
a WAL-safe `.pre-restore-<ts>` safety backup of the current DB, then swaps in
|
||||
the restored DB + waveforms. Zip entries are path-traversal-guarded before
|
||||
extraction.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Restore no longer blocks the event loop.** `/db/restore` runs its
|
||||
synchronous DB/file work in a threadpool instead of `async def`, so a large
|
||||
restore can't stall inbound ACH connections or other API requests.
|
||||
|
||||
---
|
||||
|
||||
## v0.21.1 — 2026-06-01
|
||||
|
||||
Bug fixes against v0.21.0 surfaced after the first prod redeploy. Three
|
||||
production-visible symptoms — blank waveform charts on most Thor events,
|
||||
blank histogram charts on all Thor events, and a mic chart that
|
||||
auto-scaled against a dB(L) value treated as psi — all root-caused and
|
||||
fixed.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Dynamic IDFW body offset.** The v0.21.0 codec hardcoded the body
|
||||
at file offset `0x0f1f` based on the example corpus, but only ~52%
|
||||
of production IDFW events use that offset; the rest sit at offsets
|
||||
from `0x1033` up to `0x3082` depending on header padding. At
|
||||
`0x0f1f` the codec would find a coincidentally-matching `00 02 00`
|
||||
magic, read the 2-byte Tran preamble, and return empty V/L/M
|
||||
arrays — producing near-empty .h5 files and blank charts.
|
||||
`micromate.idf_file._find_waveform_body_offset()` now scans every
|
||||
`00 02 00` magic position past `0x0E00`, trial-decodes each one,
|
||||
and picks the offset with the most samples. Validated across 483
|
||||
prod IDFW files: 0 preamble-only events (was ~50%), 355/483 fully
|
||||
decode, 126/483 partial (BW codec walker-stops-early on loud
|
||||
events — pre-existing limitation, samples reached are correct).
|
||||
|
||||
- **IDFH histograms now render bar charts.** Histograms previously
|
||||
skipped the .h5 write because there are no per-sample arrays, but
|
||||
the renderer drives the per-interval bar chart from .h5 channel
|
||||
data + `bw_report.histogram.n_intervals`. `save_imported_idf` now
|
||||
synthesizes a 1-sample-per-interval array from the decoded
|
||||
`IdfhInterval` peak counts and writes an .h5 so the existing
|
||||
renderer works unchanged — each "sample" is the per-interval peak
|
||||
ADC count, so the writer's `count × geo_fs/32768` conversion
|
||||
yields the right bar height.
|
||||
|
||||
- **Mic chart scaling on Thor events.** `PeakValues.micl` (consumed
|
||||
by the h5 writer's per-count mic scale factor) expects psi, but
|
||||
the Thor bridge was stuffing the dB(L) value (~99.4) into it,
|
||||
producing a per-count factor 5+ orders of magnitude too large and
|
||||
a flat-looking mic chart. Fixed by adding `IdfPeaks.mic_pspl_psi`
|
||||
alongside `mic_pspl_dbl`; `read_idf_file()` computes it from
|
||||
binary mic counts (`max(|MicL|) × 2.14e-6 psi/count`) for both
|
||||
IDFW and IDFH paths; `save_imported_idf` merges it onto the typed
|
||||
event after `IdfEvent.from_report`; the bridge feeds psi to
|
||||
`PeakValues.micl` with a dB(L)→psi formula fallback when only the
|
||||
dB(L) value is available. dB(L) for the report header still
|
||||
flows through `bw_report.mic.pspl_dbl` unchanged.
|
||||
|
||||
### Operator
|
||||
|
||||
After deploy, run `python scripts/backfill_thor_events.py` to refresh
|
||||
every existing Thor event's sidecar + .h5 with the corrected codec
|
||||
output. The script auto-skips events already at the current
|
||||
`TOOL_VERSION`, so the bump from `0.21.0` → `0.21.1` is what triggers
|
||||
the refresh.
|
||||
|
||||
---
|
||||
|
||||
## v0.21.0 — 2026-05-29
|
||||
|
||||
The "Thor / Series IV codec" release. Two big pieces landed: (1) the IDF binary codec actually decodes now, both IDFW and IDFH, and (2) a Thor→BW adapter lets Thor events flow through the existing Series III Event Report PDF pipeline. Combined effect: a Thor event ingested via `/db/import/idf_file` now lands in the DB with the same fidelity as a Blastware event, gets a per-event PDF on demand, and renders in Terra-View's modal chart with the same plotting code as a BW event.
|
||||
|
||||
### Added — Thor IDF binary codec (`micromate/idf_file.read_idf_file`)
|
||||
|
||||
- **IDFW (waveform)** — body sits at fixed file offset `0x0f1f`; reuses the verified `decode_waveform_v2()` walker from `minimateplus.waveform_codec`. Sample fidelity is **87–99% byte-exact** against the ASCII-sidecar reference values on quiet events; loud events hit the same walker-stops-early limitation as the BW codec on `SP0/SS0/SV0`-style events.
|
||||
- **IDFH (histogram)** — dedicated segment-based decoder for the Thor histogram body format: `[len_be][0a 00 00 00][00 NN][05 3f]` framing plus N × 72-byte interval records (4 × 16-byte per-channel min/max/halfp). **All 859 Thor IDFH corpus files decode**, totalling **181,071 intervals**; per-channel peaks match the sidecar within **~1.8% (ADC quantization)**.
|
||||
- **BW-aliased binary detection** — a small number of corpus files (e.g. `BE9439_*.IDFW/IDFH`) are actually Series III Blastware binaries that share the IDF filename convention by accident. `read_idf_file()` detects them via their BW `STRT` signature and raises `NotImplementedError` pointing the caller at `read_blastware_file()` instead of trying to decode them as IDF.
|
||||
- Full field layouts in `docs/idf_protocol_reference.md`; supporting analysis scripts in `analysis_idf/` (decode validators, per-file detail dumps, corpus accuracy reports).
|
||||
|
||||
### Added — Thor → BW report adapter (`micromate/idf_to_bw_report.py`)
|
||||
|
||||
- **`build_bw_report_from_idf(report_dict, binary_md=, intervals=, is_histogram=)`** projects a parsed Thor `IdfReport` plus binary-extracted metadata plus decoded IDFH intervals into the `bw_report`-shaped dict that `sfm.report_pdf.gather_report_data` consumes. No need to duplicate the renderer — Thor data is ~95% the same metric set as BW; the adapter handles the field-name mapping (`MicPSPL` → `pspl_dbl`, `>100` sentinel → `zc_freq_above_range`, free-form `Calibration : Nov 22, 2023 by Instantel` → `calibration_date` + `calibration_by`, etc.).
|
||||
- For IDFH events the adapter derives `histogram.interval_times` by stepping `IntervalSize` from `HistogramStartTime`, matching what the BW pipeline expects from a histogram-mode event.
|
||||
- **Wired into `WaveformStore.save_imported_idf`** — every Thor event ingested via `/db/import/idf_file` now gets a `bw_report` block in its sidecar in addition to the existing `extensions.idf_report` (the raw parsed Thor payload). Falls back gracefully (PDF renders from DB-only fields) if the adapter raises — logged as a warning rather than failing the ingest.
|
||||
|
||||
### Companion releases
|
||||
|
||||
- **Terra-View v0.13.0** ships in parallel — closes Phase 1 of the SFM integration. The shared event-detail modal now renders the SFM event story (Chart.js waveform/histogram chart, inline PDF preview, `.TXT` download, FT/reviewer/notes review form) without operators needing to bounce to the standalone SFM webapp on port 8200. Uses only existing seismo-relay endpoints — no API changes here, just better consumption.
|
||||
|
||||
### Migration / Operations
|
||||
|
||||
No DB migration needed. Existing Thor events already in the store don't automatically pick up the new `bw_report` block — they'd need a re-ingest (post the IDF binary + paired `.TXT` back to `/db/import/idf_file`) for the adapter to run. Alternatively, run `scripts/backfill_sidecars.py --reparse-txt` after a small adapter change (the script currently only re-runs the BW ASCII parser; extending it to handle Thor would be a small follow-up).
|
||||
|
||||
```bash
|
||||
cd /home/serversdown/terra-view
|
||||
docker compose build sfm && docker compose up -d sfm
|
||||
```
|
||||
|
||||
The bumped `TOOL_VERSION = "0.21.0"` in `minimateplus/event_file_io.py` means any subsequent `backfill_sidecars.py --force` pass will re-write sidecars with the new version stamp; that's expected and harmless.
|
||||
|
||||
---
|
||||
|
||||
## v0.20.0 — 2026-05-28
|
||||
|
||||
The "PDF + parser polish" release. Closes out the Event-Report PDF iteration started in v0.17.x: histogram layouts now render correctly against BW reference PDFs, the ASCII parser handles the real-world edge cases production events were tripping over (OORANGE, `>100 Hz`, histogram timestamps), and the `.TXT` preservation rollout lets parser fixes be applied retroactively to ingested events. Adds server-wide timezone support so operator-visible timestamps no longer drift into UTC. Rolls up the substantial "pre-v0.20" body of work that had accumulated under `[Unreleased]` (PDF generation, histogram codec fix, histogram parser fields, `.TXT` preservation, backfill safety) — see the trailing "pre-v0.20.0 work" section below for the full list.
|
||||
|
||||
### Added (2026-05-28)
|
||||
|
||||
- **Server-wide display timezone via `TZ` env var.** Both seismo-relay and terra-view now respect a `TZ` environment variable (default `America/New_York` on prod). Affects server log timestamps, the PDF report renderer's UTC→local conversions on the "Created" footer line, matplotlib's datetime axes, and any other naïve-vs-aware datetime rendering. DB columns (`created_at`, etc.) stay UTC regardless — this is a display-side fix, not a storage-side one. Dockerfile now installs `tzdata` (required for the env var to take effect under `python:slim`). Override per-deployment via the `TZ` line in `docker-compose.yml`.
|
||||
- **ZC Freq "above-range" handling — render `>100 Hz` instead of `—`.** BW writes `">100 Hz"` literally when the zero-crossing algorithm sees a peak too fast to count (device cuts off at 100 Hz on V10.72). Previously `_parse_number(">100")` returned None and the PDF stats table rendered `—`. Now the parser mirrors the OORANGE pattern: stores 100.0 on `zc_freq_hz` and sets a new `zc_freq_above_range` flag. Flag rides through the sidecar's `bw_report` block. Renders as `>100` in the PDF (per-channel + mic block), as `· >100 Hz` inline on the event modal's Peaks section, and as a dedicated column on the event-browser stats table. Verified against the real T190LD5Q.LK0W fixture from 2026-05-27 plus a synthetic test case.
|
||||
- **Per-channel ZC Freq surfaced in event modals.** Neither the main webapp modal (`sfm_webapp.html`) nor the standalone event browser (`event_browser.html`) previously exposed ZC Freq. Now both do — webapp shows it inline alongside PPV (`0.04500 in/s · 47 Hz`); event-browser gets a dedicated column on its per-channel stats table. Required wiring a parallel sidecar fetch into the event-browser's `loadEvent()` (it was only fetching `waveform.json`). Falls back to `—` for events without a preserved `.TXT` (pre-2026-05-27 ingests).
|
||||
- **`scripts/backfill_sidecars.py --reparse-txt` flag.** Before this, the backfill script preserved the `bw_report` block from existing sidecars verbatim — so parser-side fixes (like the `>100 Hz` addition above) couldn't reach old events. The new flag re-runs the current parser against the preserved `<serial>/<filename>_ASCII.TXT`, overwrites the bw_report block, and cascade-regenerates the sidecar. Implies sidecar regeneration on every event (bypasses the sha/version skip). No-op for events without a preserved .TXT (legacy ingests pre-2026-05-27 .TXT-preservation rollout). Idempotent. Run with `--skip-hdf5` to skip waveform regen — recommended when only the bw_report needs refreshing. Validated end-to-end on prod: 9,999 events refreshed cleanly, ZC Freq + OORANGE flags now populated where the original .TXT had them.
|
||||
|
||||
### Fixed (2026-05-28)
|
||||
|
||||
- **Histogram PDFs no longer 500 on the missing `histogram_interval_size_s` attribute.** The histogram-interval-times derivation block in `gather_report_data` referenced `rd.histogram_interval_size_s`, but the field was never declared on the `ReportData` dataclass nor read from the sidecar projection (it was inlined into `gather_report_data` without the seconds-numeric counterpart making it onto the dataclass). Every histogram PDF render raised `AttributeError → 500`. Waveform PDFs were unaffected. Fix: add the field, read it from the projection's existing `bw_report.histogram.interval_size_s` key.
|
||||
- **Histogram PDF geo channels now share a single nice-quantized y-axis.** Previously each geo subplot auto-scaled independently — Tran, Vert, and Long all showed different per-channel maxes, so bar heights weren't directly comparable across channels. The footer "Amplitude Geo: X in/s/div" label was also computed as `max(first_geo_channel) / 5` with no LSB quantization, producing nonsense values like `0.003 in/s/div` when the geophone LSB is 0.005. Fix: compute a single shared geo y-axis range from `max(Tran, Vert, Long)`, quantize the per-division step to BW's 1-2-5 sequence rounded to the 0.005 in/s LSB (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, ...), apply the same `ylim` + ticks to all three subplots, and use that step for the footer label. MicL stays on its own auto-scale (different units). Matches BW's chart styling.
|
||||
|
||||
### Docs (2026-05-28)
|
||||
|
||||
- **Roadmap entry for a second undecoded histogram body sub-format.** BE17353 (S353) events observed on 2026-05-28 use a histogram body where `byte[5] = 0x00` (looks like a valid block header by every prior signal) but the walker finds zero data blocks. Different from the existing `byte[5] != 0` roadmap entry (T190 / O121). Operationally identical impact — ingestion succeeds, DB peaks come from the bw_report overlay, only the chart is empty. Sample events captured in the roadmap entry for future RE work.
|
||||
|
||||
### Migration / Operations
|
||||
|
||||
- **Re-parse existing events to pick up the new parser fields.** Run on whichever box hosts the live waveform store:
|
||||
```bash
|
||||
docker exec terra-view-sfm-1 python /app/scripts/backfill_sidecars.py \
|
||||
--reparse-txt --skip-hdf5 --dry-run -v | tail
|
||||
# Looks reasonable? Run for real:
|
||||
docker exec terra-view-sfm-1 python /app/scripts/backfill_sidecars.py \
|
||||
--reparse-txt --skip-hdf5 -v | tee /tmp/reparse.log | tail -30
|
||||
```
|
||||
Idempotent; safe to re-run. Only touches sidecars on disk — no DB writes.
|
||||
- **terra-view docker-compose.yml**: add `TZ=America/New_York` (or your deployment's zone) to both the `terra-view` and `sfm` service `environment:` blocks. Without this, server-rendered timestamps stay in UTC even on the rebuilt SFM image.
|
||||
|
||||
### Pre-v0.20.0 work (rolled into this release)
|
||||
|
||||
The bullets below accumulated under `[Unreleased]` between v0.19.0 and v0.20.0; kept here so the historical narrative isn't lost.
|
||||
|
||||
#### Fixed
|
||||
|
||||
- **bw_ascii_report parser now handles `OORANGE` saturation marker.** BW writes `"OORANGE"` (truncation of "Out Of Range") in PPV / PVS / MicL PSPL fields when the underlying measurement exceeded the channel's full-scale. Previously our `_parse_number()` returned None → DB ended up with NULL peaks for legitimate high-amplitude events. Confirmed on real ASCII files pulled 2026-05-27 from the Windows watcher PC: T190LD5Q.LK0W (Vert saturated at Normal range 10 in/s), T438L713.RY0W (all three channels saturated at Sensitive range 1.25 in/s), K557L3YM.OE0W (Tran+Vert saturated + Mic PSPL OORANGE). New behavior:
|
||||
- Per-channel PPV: substitute `geo_range_ips` as a conservative lower bound + set `ppv_saturated` flag
|
||||
- Peak Vector Sum: substitute `sqrt(3) * geo_range_ips` (the theoretical max when all 3 channels are simultaneously at full-scale) + `peak_vector_sum_saturated` flag
|
||||
- MicL PSPL: substitute 140 dB(L) (conservative NL-43 max) + `pspl_saturated` flag
|
||||
- Saturation flags are propagated into the sidecar's `bw_report` block for downstream UI rendering (`> 10 in/s` or similar)
|
||||
- Five events on prod (T190 / T438 / K557 + 2 others matching the same fault pattern) will pick up correct DB peaks + saturation flags once re-forwarded
|
||||
- **bw_ascii_report parser handles `Peak Vector Sum TimeSum` typo'd label.** Real BW output uses this misspelled label (Sum appended twice instead of "Peak Vector Sum Time"). Now accepted as an alias. Confirmed against all three OORANGE example files — every one has the typo.
|
||||
|
||||
#### Added
|
||||
|
||||
- **Histogram per-interval aggregation in `waveform.json`.** Histogram events now render with one bar per BW-reported interval (matching the Blastware printout) instead of ~200 bars per event (the raw codec output). When the sidecar's `bw_report.histogram.n_intervals` is populated (events ingested with the new parser, see next bullet), the `/db/events/{id}/waveform.json` endpoint groups the codec samples into N intervals via max-per-group and returns the aggregated array. `time_axis` gains `histogram_aggregated: true`, `n_intervals`, `interval_size_s`, and `interval_times` (HH:MM:SS strings). Both the modal chart and the standalone event browser use those interval timestamps as x-axis labels when present. Defensive: no-op for events ingested before the parser extension landed (their sidecars lack `histogram.n_intervals`) — those continue to render with raw codec output.
|
||||
- **`bw_ascii_report` parser now captures histogram-specific fields.** Previously the parser dropped these fields silently (Roadmap item closed):
|
||||
- `Histogram Start Time` / `Histogram Start Date` (combined into `histogram_start: datetime`)
|
||||
- `Histogram Stop Time` / `Histogram Stop Date` (combined into `histogram_stop: datetime`)
|
||||
- `Number of Intervals` (`histogram_n_intervals: int`)
|
||||
- `Interval Size` ("1 minute" string + parsed seconds: `histogram_interval_size_str`, `histogram_interval_size_s`)
|
||||
- `<Channel> Peak Time` + `<Channel> Peak Date` for histogram events (combined into `channel_peak_when: dict`; waveforms continue to use `time_of_peak_s` relative)
|
||||
- `Peak Vector Sum Date` (combined with PVS Time into `peak_vector_sum_when: datetime`; clears the previous bogus `peak_vector_sum_time_s` parse that interpreted "22:33:52" as 22.0 seconds)
|
||||
- All new fields land in the sidecar's `bw_report.histogram` block via `_bw_report_to_dict`. Tested against synthetic K558LLB7.V20H-shaped input.
|
||||
- **Raw BW ASCII report (.TXT) preservation.** `save_imported_bw` now writes the paired `_ASCII.TXT` to `<store>/<serial>/<filename>_ASCII.TXT` alongside the binary at ingest time. Previously the .TXT was parsed into the sidecar's `bw_report` projection and then discarded — meaning parser bug fixes couldn't be applied retroactively without re-forwarding from the watcher PC. Now the raw .TXT lives in the waveform store permanently (~15 KB per event; ~210 MB total for a 14k-event store; negligible). Sidecar's `source.txt_filename` field records the saved path; backfill_sidecars preserves it across regens. New `GET /db/events/{id}/ascii_report.txt` endpoint serves the raw .TXT for any event ingested after this change. Events ingested before today still return 404 from that endpoint until re-forwarded. Architectural rationale: with BW Mail / Forwarding Agent being phased out of the operator workflow, the XML/PDF/WMF that those tools produced are no longer available — the binary + .TXT (created by BW ACH itself) are our authoritative source for everything going forward.
|
||||
|
||||
- **Event Report PDF generation** — `GET /db/events/{id}/report.pdf` returns a single-page letter-portrait PDF for any event with waveform data on disk. Covers every field a Blastware Event Report includes: header metadata (date/time, trigger source, range, sample rate, project/client/operator/location, serial+firmware, battery, calibration, file name), microphone block (PSPL in dB(L) + psi, ZC freq, channel test), per-channel stats table (rows differ for waveform vs histogram), Peak Vector Sum, and the 4-channel plot. Iterated against real Blastware reference PDFs (uploaded to `example-events/pdfsnstuff/`):
|
||||
- **Waveform layout**: header shows Date/Time, Trigger Source, Range, Sample Rate; stats table has PPV / ZC Freq / Time (Rel. to Trig) / Peak Accel / Peak Disp / Sensor Check; bottom plot is 4-channel line waveform (MicL top → Tran bottom), shared time axis in seconds, dashed trigger line + triangle marker at t=0, symmetric Y on geo channels, zero-anchored on mic, "0.0" baseline label on right per BW convention; footer shows `Time X sec/div Amplitude Geo: Y in/s/div Mic: 0.001 psi(L)/div` and the trigger window `▶━━◀` marker. USBM RI8507/OSMRE compliance chart placeholder upper-right.
|
||||
- **Histogram layout**: header shows Start / Finish / Intervals At Size / Range / Sample Rate (no Trigger Source — histograms aren't triggered); NO USBM chart; stats table has PPV / ZC Freq / Date / Time / Sensor Check; bottom plot is per-interval bar chart, Y-axis 0-to-peak (never negative), 0.0 baseline at the bottom; footer shows `Time INTERVAL_SIZE /div Amplitude Geo: Y in/s/div Mic: 0.001 psi(L)/div`.
|
||||
- Backed by matplotlib (vector PDF, no headless-browser dep). Adds matplotlib>=3.8 to deps.
|
||||
- **Known gap**: histogram codec returns per-block granularity (~200 bars for a 4-interval event) instead of BW's per-interval aggregation. Visual difference vs BW's 4-bar display. XML-driven data source (parsing the structured `_XML.XML` files BW also exports) is the planned fix; that route also resolves the bw_ascii_report PPV-miss bug.
|
||||
- **Stubbed**: USBM RI8507 / OSMRE compliance chart curves (separate work item; requires coding the regulatory piecewise functions).
|
||||
- **"Download PDF" button** in the event modal's footer — triggers the new endpoint; opens in a new tab so the browser handles save-or-display + surfaces any 404 / server errors visibly.
|
||||
|
||||
- **SFM webapp now opens to Database view by default** and the History table is fully interactive. Click any column header to sort ascending / descending (timestamp, serial, per-channel PPV, PVS, mic dB(L), project, client, record type, key — all sortable). Click any event row to open the event modal, which now renders a **4-channel waveform plot inline** (MicL / Long / Vert / Tran stacked, Instantel-printout order) alongside the existing sidecar review fields. Headers are sticky so the columns stay visible while scrolling long event lists. No more "where is the viewer" — pick a unit from the filter dropdown, scan the table, click the event, see the waveform.
|
||||
- **Stored-event browser** — new standalone HTML page at `GET /events` (`sfm/event_browser.html`). Pick a serial from the unit dropdown, scroll through that unit's events (newest-first), click any event to render its decoded waveform via the existing `/db/events/{id}/waveform.json` endpoint. Dark-themed Chart.js viewer, channels stacked vertically (MicL / Long / Vert / Tran — Instantel printout order, designed PDF-export-ready), trigger line at t=0, peak labels, search/filter, false-trigger flag honored. Companion to the existing live-device viewer at `/waveform`; the two routes are now clearly delineated in their docstrings. The webapp's inline plot at `/` is the primary path; `/events` remains a useful diagnostic when you want just a viewer.
|
||||
- **Histogram body codec — uint8 peak count fix.** Per-channel peak fields at `block[6]/[10]/[14]/[18]` are `uint8`, not `uint16 LE` spanning `block[6:8]` etc. The original interpretation was byte-exact on the N844 fixture corpus only because every annotation byte (`block[7]/[11]/[15]/[19]`) in those fixtures was zero. On non-N844 events with non-zero annotation bytes (observed across BE9558 Tran-drift and BE18003 Histogram+Continuous units), the old interpretation produced peaks up to 268 in/s per channel and 35× inflated PVS sums when first deployed to prod (rolled back same day; properly fixed in this release). Cross-correlated against BW's per-interval ASCII export on K558 / T003 / N599 / N844 corpora — 100% byte-exact on T/V/L, 99%+ on M (sub-precision rounding). Annotation byte preserved on each record as `record["annotations"]` for future RE. Verified against ~3,500 blocks across 5 in-repo fixtures + a synthetic K558 interval-12 regression block.
|
||||
- **`apply_bw_report_dict_to_event` helper** in `minimateplus.event_file_io`. Mirror of `apply_report_to_event` for the projected sidecar dict shape — used by the backfill path, which has the preserved `bw_report` block but not the original `.TXT` file. BW's reported peaks (and `sample_rate` / `record_time`) now win over codec output during `--force` backfill, matching ingest-path behavior.
|
||||
- **`scripts/check_bw_report_preservation.py`** — two-step snapshot/diff tool to verify that `backfill_sidecars.py` doesn't wipe the `bw_report` block from existing sidecars. Classifies every sidecar as PRESERVED / CHANGED / WIPED / STILL_MISSING / NEW / ADDED / REMOVED. Exit code 1 if any WIPED or CHANGED entries are found, so it can gate a CI step or deploy script.
|
||||
|
||||
#### Fixed
|
||||
|
||||
- **`scripts/backfill_sidecars.py` no longer wipes `bw_report`.** Before this fix, `event_to_sidecar_dict` silently dropped the preserved `bw_report` block during every backfill, since the function only emits a `bw_report` when called with a live `BwAsciiReport` dataclass (which the backfill doesn't have — only the projected sidecar dict). Now we read the existing sidecar's `bw_report` and overlay it onto the regenerated sidecar, alongside the existing `review` and `extensions` preservation.
|
||||
- **`scripts/backfill_sidecars.py --force` no longer overwrites BW-overlaid DB peaks with codec output.** The backfill path now calls `apply_bw_report_dict_to_event` before the DB upsert, mirroring what the ingest path does (`/db/import/blastware_file` parses the `.TXT` into a `BwAsciiReport`, calls `apply_report_to_event`, then upserts). Without this, events where the codec doesn't fully decode (waveform walker edge cases on SP0/SS0/SV0-style events, histogram `byte[5]!=0` sub-format) ended up with PVS=0 in the DB after a `--force` backfill; bit on prod 2026-05-22, rolled back the same day.
|
||||
- **Thor IDF files no longer attempted as BW events in backfill.** `scripts/backfill_sidecars.py` now filters out `.IDFW` / `.IDFH` files in `_looks_like_event_file()`; they share the `.X0W` / `.X0H` suffix shape but use a separate ingest path (`WaveformStore.save_imported_idf`) and aren't decodable by `event_file_io.read_blastware_file`.
|
||||
|
||||
#### Docs
|
||||
|
||||
- **CLAUDE.md** — added a three-tier conceptual architecture model (SFM / SDM / shared codec library) near the top of the file, with a placement rule for where new code goes. Documents that what is conceptually SDM (database, waveform store, ingest, `/db/*` endpoints) still lives under `sfm/` for historical reasons; rename deferred until the codebase is quiet enough for a clean refactor.
|
||||
- **README.md** — added a "Strategic direction" lead-in to the Roadmap that frames seismo-relay as a suite of cooperating components (not a single app), and an explicit "Terra-View ↔ SFM device control" roadmap section with a concrete implementation checklist (auth as hard prerequisite, embedded live-monitor view, action history, Series IV live-device support).
|
||||
- **`docs/histogram_codec_re_status.md`** updated with the uint8 retraction and the annotation-byte status.
|
||||
- Three known issues recorded in the Roadmap that were discovered during prod validation: (1) `bw_ascii_report` parser misses PPV / `vector_sum` on some `.TXT` formats (5 events on prod); (2) NULL-timestamp duplicate-row dedup needed (2 events on prod); (3) histogram body sub-format with `byte[5] != 0` not yet decoded (~3 events on prod with empty `.h5` plots).
|
||||
|
||||
---
|
||||
|
||||
## v0.19.0 — 2026-05-20
|
||||
|
||||
The "device-family separation" release. Tightens the boundary between Series III (MiniMate Plus / Blastware) and Series IV (Micromate / Thor) so the UI and storage layer dispatch deterministically by family instead of sniffing filename extensions or magnitude heuristics.
|
||||
|
||||
@@ -2,12 +2,139 @@
|
||||
|
||||
Ground-up Python replacement for **Blastware**, Instantel's Windows-only software for
|
||||
managing MiniMate Plus seismographs. Connects over direct RS-232 or cellular modem
|
||||
(Sierra Wireless RV50 / RV55). Current version: **v0.17.0**.
|
||||
(Sierra Wireless RV50 / RV55). Current version: **v0.26.0**.
|
||||
|
||||
---
|
||||
|
||||
## Where things stand (updated 2026-08-27)
|
||||
|
||||
Read this first when picking the project back up.
|
||||
|
||||
- **Series-3 decode is correct and verified.** All 11,603 series-3 binaries in
|
||||
the prod snapshot pass every check (channel lengths, peaks vs the device's
|
||||
own reported PPV, nothing above full scale, length vs declared record time).
|
||||
Ground truth: 1,211/1,211 histograms exact per-interval and 75/75 waveform
|
||||
sample counts exact against preserved Blastware ASCII exports.
|
||||
⚠ That is per-sample proof on 11% of files and peak-only consistency on the
|
||||
other 89% — see `docs/instantel_protocol_reference.md` §7.6.1.
|
||||
- **Series-4 (Thor / Micromate) is NOT verified.** UM-series sits at ~48%
|
||||
against device peaks with a ~1.7% systematic bias and a near-zero tail.
|
||||
Thor IDFW is pinned to `decode_waveform_legacy` deliberately.
|
||||
- **Open, not blocking:** 14 sensitive-range files show an exact 8x
|
||||
(= 10.0/1.25) units discrepancy; `scripts/backfill_sidecars.py --force` also
|
||||
inserts DB rows for store files that have none (one-time per store) and the
|
||||
dry-run does not report that count.
|
||||
- **After any codec change, regenerate the store** — `backfill_sidecars.py
|
||||
--force` then `backfill_event_shape.py`, DB backup first. Stored `.h5` files
|
||||
do not update themselves.
|
||||
- **Parked:** the "offset" hardware-fault investigation (Appendix E of the
|
||||
protocol reference) pending the multi-year BW archive.
|
||||
|
||||
|
||||
When new information about the protocol is discovered, please update the instantel_protocol_reference.md with the findings in addition to this document
|
||||
|
||||
---
|
||||
|
||||
## Architecture: three-tier conceptual model
|
||||
|
||||
seismo-relay is a **suite of cooperating components**, not a single app.
|
||||
The three tiers below are the canonical mental model — the current
|
||||
directory layout doesn't fully reflect them yet (some of what is
|
||||
conceptually SDM lives under `sfm/` today), but new code should be
|
||||
placed and named according to this model.
|
||||
|
||||
### 1. SFM — the device-side (active connection to physical units)
|
||||
|
||||
Replaces Blastware's *talk-to-the-meter* role. Lives where a connection
|
||||
to a physical seismograph is open.
|
||||
|
||||
In scope:
|
||||
- `minimateplus/{transport,framing,protocol,client}.py` — wire protocol
|
||||
- `seismo_lab.py` — diagnostic GUI (a thick client for SFM)
|
||||
- The `/device/*` HTTP endpoints in `sfm/server.py` —
|
||||
`/device/info`, `/device/events`, `/device/monitor/*`, `/device/call_home`,
|
||||
etc. Anything that opens a connection at the moment of the request.
|
||||
- Future: a Thor / Micromate live client (mirror `minimateplus/`)
|
||||
- Future: a control surface Terra-View can launch into — see the
|
||||
README's Roadmap.
|
||||
|
||||
Does NOT own a database. Outputs `Event` objects. Has a "spun up when
|
||||
needed" runtime profile rather than "always on".
|
||||
|
||||
### 2. SDM — the data-side (storage, ingest, and serving)
|
||||
|
||||
The new name for the receiving-and-storing role. Originally called SFM
|
||||
because the FastAPI service started life as a thin device proxy, but
|
||||
the actual role has migrated heavily toward data management. **For now
|
||||
the directory remains `sfm/`** — renaming requires touching ~30-50
|
||||
files in seismo-relay + ~10-15 in terra-view + a Docker volume
|
||||
migration; deferred until the codebase is quiet enough to do it as a
|
||||
clean refactor.
|
||||
|
||||
In scope:
|
||||
- `sfm/database.py` (`SeismoDb`)
|
||||
- `sfm/waveform_store.py`, `sfm/event_hdf5.py`
|
||||
- The `/db/*` HTTP endpoints — `events`, `units`, `monitor_log`,
|
||||
`sessions`, `false_trigger` mutations
|
||||
- The `/db/import/*` ingest endpoints — `blastware_file` (series3),
|
||||
`idf_file` (series4); anything that receives events FROM somewhere
|
||||
- `scripts/backfill_sidecars.py`, `scripts/check_bw_report_preservation.py`,
|
||||
and similar data-maintenance tools
|
||||
- The `.sfm.json` sidecars and `.h5` files in the waveform store
|
||||
- The shape that Terra-View consumes (Terra-View should never need to
|
||||
reach into SFM/device-side endpoints to populate its UI)
|
||||
|
||||
Always-on, scaled for storage/serving, has the DB and waveform store.
|
||||
|
||||
### 3. Codec library — pure data interpretation (used by both sides)
|
||||
|
||||
Neither SFM nor SDM — a shared library both depend on.
|
||||
|
||||
In scope:
|
||||
- `minimateplus/{waveform_codec,histogram_codec,event_file_io,bw_ascii_report,blastware_file}.py`
|
||||
- `micromate/{idf_ascii_report,idf_file}.py`
|
||||
|
||||
These modules take bytes (off the wire on the SFM side, or from a
|
||||
forwarded file on the SDM side) and return `Event` objects. They
|
||||
should not import from `sfm/`, must not touch a DB, and have no I/O
|
||||
beyond reading files passed as arguments. Keep them pure — both
|
||||
tiers can then depend on them without circularity.
|
||||
|
||||
#### Thor IDF binary codec (2026-05-28)
|
||||
|
||||
`micromate/idf_file.read_idf_file()` decodes both Thor IDFW
|
||||
(waveform) and IDFH (histogram) binaries.
|
||||
|
||||
- **IDFW** reuses `decode_waveform_v2()` on the body at fixed file
|
||||
offset `0x0f1f`. Sample fidelity is 87–99% byte-exact on quiet
|
||||
events; loud events hit the BW codec's known walker-stops-early
|
||||
limitation.
|
||||
- **IDFH** has its own segment-based decoder: `[len_be][0a 00 00 00]
|
||||
[00 NN][05 3f]` + N × 72-byte interval records (4 × 16-byte
|
||||
per-channel min/max/halfp). All 859 Thor IDFH corpus files
|
||||
decode (181,071 intervals); peak matches sidecar within ~1.8%
|
||||
(ADC quantization).
|
||||
|
||||
The two outlier `BE9439_*` files in the Thor example corpus are
|
||||
actually Series III Blastware binaries that share the `.IDFW`/`.IDFH`
|
||||
filename convention by accident. `read_idf_file()` detects them by
|
||||
their BW STRT signature and raises NotImplementedError pointing
|
||||
callers at `read_blastware_file()`. See
|
||||
`docs/idf_protocol_reference.md` for full field layouts.
|
||||
|
||||
### Practical consequences
|
||||
|
||||
When deciding where new code goes, ask:
|
||||
- *Does it need a connection to a device?* → SFM
|
||||
- *Does it operate on stored events / sidecars / DB rows?* → SDM
|
||||
- *Does it interpret bytes into structured data, with no I/O of its own?* → codec lib
|
||||
|
||||
Terra-View is downstream of SDM for data, and (per the roadmap) will
|
||||
eventually invoke into SFM's device-control endpoints to provide a
|
||||
"connect to unit" experience.
|
||||
|
||||
---
|
||||
|
||||
## Project layout
|
||||
|
||||
```
|
||||
@@ -123,6 +250,118 @@ custom delta + RLE + variable-width codec.
|
||||
`NN + 2` for int8 blocks). Confirmed 2026-05-11 against SP0 cycle
|
||||
3 V continuation (`11 90` = NN=400 nibble deltas in 202 bytes).
|
||||
|
||||
### ⚠ SUPERSEDED 2026-08-25 — the body is a RECORD CHAIN
|
||||
|
||||
Everything in this section below about `40 NN` segment headers, tagless
|
||||
headers, variable header widths and channel rotation describes a model that
|
||||
is **wrong**. The body is a chain of self-delimiting per-channel records:
|
||||
|
||||
off+2 len uint16 BE -> next_record = off + 2 + len
|
||||
off+4 chan_id 0x46 Tran / 0x47 Vert / 0x48 Long / 0x49 MicL / 0x06 = END
|
||||
off+8 mode 02 00 = deltas+anchors (14B hdr)
|
||||
01 00 = ABSOLUTE values (10B hdr)
|
||||
00 03 = raw 12-bit absolute, NO TAGS (10B hdr)
|
||||
|
||||
`40 NN` is an ordinary int16 BE data block (`2*NN + 2`), never a header. The
|
||||
"variable prefix" of 0/2/4/6/8 bytes was walker drift, exactly
|
||||
`4 - (old_stop - true_record_start)`.
|
||||
|
||||
All four channels now come out equal length in **1388/1388** files (was
|
||||
156/1388); ASCII sample-count exact **75/75**, fully exact **73/75**; device
|
||||
PPV on a live decode **1306/1306** waveform, **4458/4459** histogram.
|
||||
|
||||
The old model survives as `decode_waveform_legacy` because
|
||||
`micromate/idf_file.py` pins it for Thor IDFW body-offset search.
|
||||
|
||||
### Framing cases added 2026-05-11 → 2026-08-25
|
||||
|
||||
Four more block-framing cases, each of which had been causing **silent
|
||||
channel truncation** — `walk_body` ends its loop on an unrecognised tag
|
||||
and `decode_waveform_v2` returns whatever channels it got, so an
|
||||
unhandled tag surfaces as short channels with no error raised. Found by
|
||||
diffing 75 production events against their preserved Blastware ASCII
|
||||
exports (`<store>/<serial>/<file>_ASCII.TXT`).
|
||||
|
||||
- **Wide-NN RLE `0X NN`** — the 12-bit NN encoding documented above for
|
||||
`1X`/`2X` **also applies to the `00 NN` RLE tag**. A narrow run maxes
|
||||
out at NN=0xFC, so a quiet stretch longer than 252 samples must use
|
||||
the wide form (e.g. `01 0c` = 268 repeats).
|
||||
- **`30 NN` is not capped at NN=0x10** — data-section blocks reach at
|
||||
least NN=0x18. The `NN × 1.5 + 2` length formula was already right;
|
||||
only the guard was wrong.
|
||||
- **`40 NN` segment headers are variable width** — NN is the *count of
|
||||
int16 BE continuation deltas for the PREVIOUS channel*, so the header
|
||||
is `2*NN + 16` bytes and every field after the deltas shifts by
|
||||
`2*NN`. `40 01` (18 B) and `40 03` (22 B) both occur alongside the
|
||||
common `40 02` (20 B).
|
||||
- **Tagless segment headers** — a header can appear with **no `40 NN`
|
||||
tag at all**: just the 14-byte tail
|
||||
`[field2:2][len:2][channel_id:4][marker:2][anchors:4]`. This is the
|
||||
NN=0 case (previous channel needed no continuation deltas).
|
||||
|
||||
**The header "counter" is really a channel id.** The 4-byte field long
|
||||
documented as a "monotonic uint32 LE counter" is
|
||||
`[channel_id][00][00][segment_index]`, with `0x46`=Tran `0x47`=Vert
|
||||
`0x48`=Long `0x49`=MicL — verified on **1697/1697** segment headers
|
||||
across the corpus, zero disagreements. `decode_waveform_v2` now takes
|
||||
the channel from this field rather than from rotation position; a single
|
||||
missed or extra header (exactly what tagless headers caused) desyncs
|
||||
rotation and corrupts every channel after it.
|
||||
|
||||
Corpus result, end to end through the production path:
|
||||
**exact 37 → 72, truncated 23 → 3, full-length value errors 15 → 0.**
|
||||
|
||||
### Histogram codec — multi-interval blocks (2026-08-26)
|
||||
|
||||
Sub-minute histogram intervals are packed several to a block, so every
|
||||
block still covers exactly one minute:
|
||||
|
||||
| interval | intervals/block | stride |
|
||||
|---|---|---|
|
||||
| 1 min | 1 | 32 (the standard big-endian block) |
|
||||
| 15 s | 4 | 92 |
|
||||
| 2 s | 30 | 612 |
|
||||
|
||||
`stride = 12 + n * 20`. Block = `[00][segment][ctr uint16 LE][0a][00]`,
|
||||
then n x 20-byte records of 8 x uint16 **LITTLE**-endian values
|
||||
(`T_peak, T_halfp, V_peak, V_halfp, L_peak, L_halfp, M_peak, M_halfp`)
|
||||
plus a 2-word tail whose first word is `0000` on every real interval,
|
||||
then a 6-byte block trailer.
|
||||
|
||||
⚠ The standard 32-byte block is BIG-endian; this variant is LITTLE-endian.
|
||||
|
||||
Recovers **415 files** (216 on BE18193, 199 on BE9440) that decoded to
|
||||
nothing. Ground truth `BE9440/K440L3AQ.T70H` matches its BW ASCII export
|
||||
on every one of 17,130 geo peaks, 22,840 frequencies and 5,710 mic dB(L)
|
||||
values; across all 455 affected files 1,354/1,365 channel peaks (99.2%)
|
||||
match the device-reported PPV.
|
||||
|
||||
### Histogram codec — corrected 2026-08-25
|
||||
|
||||
The histogram block is **uniformly big-endian**, and the stream's final
|
||||
block has its own tail signature. Two long-standing errors:
|
||||
|
||||
- **Peaks and half-periods are `uint16` big-endian**, not `uint8` +
|
||||
an "annotation" byte. `T_peak` is `[5:7]`, `T_halfperiod` `[7:9]`,
|
||||
`V_peak` `[9:11]`, and so on; only `block_ctr` at `[2:4]` is LE.
|
||||
The old model silently **clipped any peak above 1.275 in/s** — the
|
||||
final interval of `BE18193/T193LQ9K.OE0H` reads 8.270 in/s in BW's
|
||||
export and decoded as 0.590. The "annotation" byte was the
|
||||
half-period's high byte, which is why it was non-zero exactly on the
|
||||
sub-Hz intervals BW renders as `<1.0`.
|
||||
- **The marker is `block[4]` alone.** Testing `[4:6]` as a uint16 LE
|
||||
marker forced `block[5] == 0`, which is what capped the peak at one
|
||||
byte in the first place.
|
||||
- **The last block of the stream carries tail `9c 06 00 42`** instead of
|
||||
`1e 0a 00 00`, with arbitrary bytes at `[21:23]`. Rejecting it
|
||||
dropped the final interval of nearly every histogram — frequently the
|
||||
one holding the event peak, so the file's PPV read low.
|
||||
|
||||
Verified against 1211 production histograms paired with their BW ASCII
|
||||
exports: **1211/1211 decode exactly** (interval count plus every
|
||||
per-interval peak), and 842,442 per-interval frequency comparisons match
|
||||
with zero mismatches. Before: 1 of 1196.
|
||||
|
||||
### What's NOT solved
|
||||
|
||||
- **MicL channel conversion to dB(L)** — the codec emits MicL as
|
||||
@@ -130,9 +369,25 @@ custom delta + RLE + variable-width codec.
|
||||
shows mic in dB(L) with ~6 dB quantization steps. Need to map
|
||||
ADC counts → dB(L) for direct comparison; likely
|
||||
`dB = 20*log10(|counts|) + offset` or similar.
|
||||
- **Walker edge cases** — SP0/SS0/SV0 don't walk the full event due
|
||||
to block-length quirks past the first few segments. Every sample
|
||||
reached is correct; the walker just needs robustness improvements.
|
||||
- **Variable-prefix segment descriptors** — 3 of the 75 ground-truth
|
||||
production events still truncate. The walk reaches a segment header
|
||||
whose channel-id field is preceded by a *variable-width* prefix (2, 4
|
||||
or 6 bytes observed; the standard tagless form always has 4), carrying
|
||||
an `01 00` marker instead of `02 00`. The marker is **not** simply an
|
||||
anchor count — `01 00` records appear with both 2- and 4-byte anchor
|
||||
fields in the same file. Examples: `BE12599/N599LPNB.JF0W` @1155,
|
||||
`BE12599/N599LPWJ.980W` @849, `BE9558/K558LOF2.820W` @1485.
|
||||
(The series-3 histogram codec was fixed 2026-08-25 — see below.)
|
||||
|
||||
- **Micromate (UM-series) IDF decode is ~1000× low** — e.g.
|
||||
`UM11402_20260406130113.IDFW` gives a Tran peak of 0.0009 in/s against
|
||||
a device-reported 1.1168. The Thor IDF path decodes sanely, so this
|
||||
is UM-specific.
|
||||
- **Thor IDF per-count LSB** — after the 32000 geo full-scale
|
||||
correction, series-4 Thor peaks sit at a median 0.983 of the
|
||||
device-reported peak (was 0.960 under 32768). Closer but not exact;
|
||||
Thor likely uses its own per-count LSB rather than the BW
|
||||
16-count/0.005 in/s convention.
|
||||
|
||||
### Decoded sample counts (across the fixture bundle)
|
||||
|
||||
@@ -164,6 +419,14 @@ then `decoded_to_adc_counts()` to scale to int16 ADC counts (geos × 16;
|
||||
mic pass-through). The `.h5` sidecars SFM produces now contain
|
||||
correct samples for any event without walker edge cases.
|
||||
|
||||
**Geo full scale is 32000 ADC counts, NOT 32768** (fixed 2026-08-25).
|
||||
One decoder unit = 16 ADC counts = exactly 0.005 in/s, so
|
||||
`10.000 in/s / (0.005/16)` = 32000. Consumers must use
|
||||
`sfm.event_hdf5._GEO_INT16_FS` / `event_file_io._GEO_INT16_FS` (both
|
||||
32000). Dividing by 32768 reads every geophone sample 2.34% low —
|
||||
that was a live bug in both modules until 2026-08-25. Mic is
|
||||
unaffected (it back-solves its scale from the device-reported peak).
|
||||
|
||||
The original int16 LE decoder is preserved as
|
||||
`_decode_a5_waveform_LEGACY` for reference but is not called.
|
||||
|
||||
|
||||
+12
-1
@@ -2,10 +2,21 @@ FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# tzdata is required for the TZ env var to take effect (python:slim
|
||||
# omits the timezone database). Without it, datetime.now() / logging
|
||||
# / matplotlib all stay in UTC regardless of TZ. Default zone gets
|
||||
# set further down via ENV; users override per-deployment via the
|
||||
# `TZ` env var in docker-compose.
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends curl && \
|
||||
apt-get install -y --no-install-recommends curl tzdata && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Default display timezone — applied to server logs, datetime.now(),
|
||||
# matplotlib rendered timestamps, and any naïve-vs-aware datetime
|
||||
# conversions in the PDF renderer. Override via TZ env var in
|
||||
# docker-compose; storage in the DB is always UTC regardless.
|
||||
ENV TZ=America/New_York
|
||||
|
||||
COPY pyproject.toml requirements.txt ./
|
||||
COPY minimateplus ./minimateplus
|
||||
COPY micromate ./micromate
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# seismo-relay `v0.19.0`
|
||||
# seismo-relay `v0.26.0`
|
||||
|
||||
A ground-up replacement for **Blastware** — Instantel's aging Windows-only
|
||||
software for managing seismographs. Supports both the **MiniMate Plus
|
||||
@@ -35,6 +35,30 @@ over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55).
|
||||
> and storage layer dispatch deterministically instead of sniffing
|
||||
> filenames. Self-applying migration backfills existing rows from the
|
||||
> binary filename extension.
|
||||
> **v0.20.0 (2026-05-28)** closes out the Event-Report PDF iteration
|
||||
> started in v0.17.x: histogram layouts render correctly against BW
|
||||
> reference PDFs, the ASCII parser handles real-world edge cases
|
||||
> (`OORANGE`, `>100 Hz`, histogram timestamps), and per-channel ZC
|
||||
> Freq is surfaced in both modals (event browser + main webapp).
|
||||
> Adds a server-wide `TZ` env var so operator-visible timestamps
|
||||
> render in local time instead of UTC. New
|
||||
> `scripts/backfill_sidecars.py --reparse-txt` lets parser fixes be
|
||||
> applied retroactively to existing events without re-forwarding,
|
||||
> using the `.TXT` files preserved at ingest time.
|
||||
> **v0.21.0 (2026-05-29)** is the Thor / Series IV decoder release —
|
||||
> `micromate/idf_file.read_idf_file()` now decodes both IDFW
|
||||
> (waveform) and IDFH (histogram) binaries (87–99% sample fidelity
|
||||
> on quiet IDFW events; all 859 IDFH corpus files decode cleanly).
|
||||
> A new `micromate/idf_to_bw_report.py` adapter projects parsed
|
||||
> Thor reports into the BW-shaped sidecar block, so Thor events
|
||||
> flow through the existing Event Report PDF pipeline without a
|
||||
> separate renderer. Terra-View v0.13.0 ships in parallel and
|
||||
> closes Phase 1 of the SFM integration — see its CHANGELOG.
|
||||
> **v0.22.0 (2026-07-03)** adds the SFM side of the full-snapshot
|
||||
> bundle: `GET /db/snapshot` (WAL-safe DB copy), `GET /db/waveforms/
|
||||
> recent.zip` (recent events' waveform files), and a gated
|
||||
> `POST /db/restore` (`SFM_DB_RESTORE_ENABLED`, dev-only). Terra-View
|
||||
> v0.17.0 drives them to pull a one-pass prod→dev refresh.
|
||||
> See [CHANGELOG.md](CHANGELOG.md) for full version history.
|
||||
|
||||
---
|
||||
@@ -58,7 +82,8 @@ seismo-relay/
|
||||
├── micromate/ ← Series IV (Micromate / Thor) client library (NEW v0.19)
|
||||
│ ├── models.py ← IdfEvent, IdfReport, IdfPeaks, IdfProjectInfo, IdfSensorCheck (mic in native dB(L))
|
||||
│ ├── idf_ascii_report.py ← Parse Thor .IDFW.txt / .IDFH.txt event sidecars
|
||||
│ └── idf_file.py ← Stub for the .IDFW / .IDFH binary codec (reverse-engineering pending)
|
||||
│ ├── idf_file.py ← Binary codec for .IDFW + .IDFH (v0.21.0+)
|
||||
│ └── idf_to_bw_report.py ← Adapter projecting Thor IDF into the BW report shape (v0.21.0+)
|
||||
│
|
||||
├── sfm/ ← SFM REST API server (FastAPI, port 8200)
|
||||
│ ├── server.py ← Live device endpoints + DB query + ingest endpoints + caching
|
||||
@@ -190,6 +215,18 @@ optionally paired with their ASCII sidecar reports; both dedup by
|
||||
| `POST` | `/db/import/blastware_file` | Series III: `.AB0*` / `.N00` binaries + paired `_ASCII.TXT`. Source: `series3-watcher`. |
|
||||
| `POST` | `/db/import/idf_file` | Series IV: `.IDFH` / `.IDFW` binaries + paired `.IDFW.txt` / `.IDFH.txt`. Source: `thor-watcher`. |
|
||||
|
||||
### DB snapshot / restore endpoints
|
||||
|
||||
Back the "full snapshot bundle" prod→dev refresh Terra-View orchestrates
|
||||
(Settings → Database). Snapshot/zip are read-only; restore is gated and
|
||||
dev-only.
|
||||
|
||||
| Method | URL | Description |
|
||||
|--------|-----|-------------|
|
||||
| `GET` | `/db/snapshot` | WAL-safe point-in-time copy of `seismo_relay.db` via the SQLite online backup API. |
|
||||
| `GET` | `/db/waveforms/recent.zip?n=…` | Zips the on-disk files (event file + `.h5` / sidecars) for the *n* most-recent events. |
|
||||
| `POST` | `/db/restore` | Validate-first restore of an uploaded DB + waveforms; takes a WAL-safe pre-restore safety backup, path-traversal-guards the zip. Gated by `SFM_DB_RESTORE_ENABLED` (dormant → 404). |
|
||||
|
||||
---
|
||||
|
||||
## minimateplus library
|
||||
@@ -415,7 +452,7 @@ Use **com0com** or **VSPD** to create the virtual COM pair on Windows.
|
||||
- [x] Thor IDF file ingest at `/db/import/idf_file` (paired with `thor-watcher`, v0.18.0+)
|
||||
- [x] Native `IdfEvent` / `IdfReport` typed models — mic in dB(L), full title strings, sensor self-check, calibration, firmware version
|
||||
- [x] Parser verified against 1,014 paired `.txt` sidecars in `thor-watcher/example-data/`
|
||||
- [ ] Binary `.IDFW` / `.IDFH` codec — pending (see Roadmap + [`docs/idf_protocol_reference.md`](docs/idf_protocol_reference.md))
|
||||
- [x] Binary `.IDFW` / `.IDFH` codec — ✅ v0.21.0. IDFW reuses `decode_waveform_v2()` on the body at offset `0x0f1f` (87–99% sample fidelity on quiet events); IDFH has a dedicated segment-based decoder (all 859 corpus files decode, 181,071 intervals total). See `micromate/idf_file.py` + `docs/idf_protocol_reference.md`.
|
||||
- [ ] Live-device protocol — pending codec
|
||||
|
||||
**Data persistence:**
|
||||
@@ -459,10 +496,76 @@ Use **com0com** or **VSPD** to create the virtual COM pair on Windows.
|
||||
|
||||
## Roadmap (Future)
|
||||
|
||||
### Strategic direction — where this is going
|
||||
|
||||
seismo-relay is being built as a **suite of cooperating components**
|
||||
that together replace and improve on Blastware's role. Three logical
|
||||
tiers:
|
||||
|
||||
1. **SFM** (device-side) — owns the active connection to a physical
|
||||
unit. Today: `minimateplus/`, `/device/*` HTTP endpoints,
|
||||
`seismo_lab.py`. Future: live Thor / Micromate support.
|
||||
2. **SDM** (data-side) — owns the database, waveform store, ingest
|
||||
pipelines, and the read-API that Terra-View consumes. Today this
|
||||
code lives under `sfm/` for historical reasons; the role has
|
||||
migrated and the eventual rename is on the long-tail cleanup list.
|
||||
3. **Codec library** — pure data-interpretation: `minimateplus/*_codec.py`,
|
||||
`bw_ascii_report.py`, `micromate/idf_*.py`. Used by both SFM and
|
||||
SDM, depends on neither.
|
||||
|
||||
Terra-View is downstream of SDM for fleet listings, event detail, etc.
|
||||
The long-term vision adds a **second link** from Terra-View → SFM for
|
||||
direct device interaction (see below).
|
||||
|
||||
The codec work in this repo isn't trying to replace BW's network
|
||||
layer — BW's ACH file forwarding and Thor's IDF call-home are
|
||||
battle-tested. The value is in the receiving and processing side: turn
|
||||
the stream of binary+ASCII pairs into something users can search,
|
||||
filter, alert on, and report from.
|
||||
|
||||
### Terra-View ↔ SFM device control (the long-term vision)
|
||||
|
||||
Today Terra-View only reads from SDM (event listings, dashboards,
|
||||
project reports). When a unit goes missing — operator notices in the
|
||||
Terra-View dashboard — there's no way to *do* anything from the UI.
|
||||
The path of least resistance is to RDP into a Windows box and open
|
||||
Blastware, which defeats the purpose of having Terra-View.
|
||||
|
||||
Target experience:
|
||||
- Operator notices a unit in Terra-View dashboard hasn't called in.
|
||||
- Clicks unit detail → "Connect to Device" button.
|
||||
- Terra-View opens an embedded view (modal or side-panel) that talks
|
||||
to SFM's `/device/*` endpoints over the network.
|
||||
- Live view: device clock, battery, memory, current monitor status.
|
||||
- Actions: start/stop monitoring, push compliance config changes, pull
|
||||
fresh events, run a sensor self-check, change call-home settings.
|
||||
- Audit log: every connect / action recorded in SDM for the unit
|
||||
history.
|
||||
|
||||
Implementation steps (concrete):
|
||||
- [ ] **SFM authentication & authorization layer.** Today `/device/*`
|
||||
endpoints are unauthenticated — anyone on the network can call
|
||||
them. Need at minimum a token-based auth, ideally with a "who
|
||||
can connect to which units" mapping. Hard prerequisite for
|
||||
letting Terra-View users into the control surface.
|
||||
- [ ] **Terra-View "Connect to Device" entry point** on the unit
|
||||
detail page. Renders only when unit has connection info on file
|
||||
and the user has permission.
|
||||
- [ ] **Embedded live-monitor view** in Terra-View — equivalent to
|
||||
`seismo_lab.py`'s Bridge tab, but in the browser. Polls SFM's
|
||||
`/device/monitor/status` on an interval; sends start/stop via
|
||||
`/device/monitor/{start,stop}`.
|
||||
- [ ] **Action history** — every connect / push / action call records
|
||||
a row in `unit_history`, viewable on the unit detail page.
|
||||
- [ ] **Series IV live-device support in SFM** — currently `/device/*`
|
||||
only supports MiniMate Plus. Blocks "Connect to Device" for
|
||||
Thor units until done. Depends on Thor wire-protocol capture
|
||||
and a `micromate/` parallel of the `minimateplus/` modules.
|
||||
|
||||
### High-impact (unblocks product features)
|
||||
|
||||
- [ ] **Series III waveform body codec reverse-engineering.** The 5A bulk-stream body is some kind of compressed/encoded format (not raw int16 LE as previously assumed — see §7.6.1 retraction in `docs/instantel_protocol_reference.md`). Structural framing is ~50% decoded on branch `claude/codec-re-cBGNe` (tagged-block walker, segment counters); per-byte sample mapping is still open. Until this lands, the in-app waveform viewer renders garbage and BW-import peak values fall back to `_peaks_from_samples()` saturation noise. Workaround: pair every BW-imported event with its `_ASCII.TXT` so the device-authoritative peaks land in the DB regardless of codec.
|
||||
- [ ] **Series IV (Thor IDF) binary codec reverse-engineering.** `.IDFH` / `.IDFW` files are currently stored opaquely by `WaveformStore.save_imported_idf`, with all metadata sourced from the paired `.txt` sidecar. This works because thor-watcher forwards both files together, but operators who haven't enabled Thor's TXT exporter get rows with NULL peaks. Cracking the binary closes that gap and unlocks waveform display. Starting-point reference at [`docs/idf_protocol_reference.md`](docs/idf_protocol_reference.md) — two observed file signatures (1,012 newer-firmware files + 2 old files whose layout matches the Series III STRT-record format), suggested first-session plan (~2-4 hrs), 1,014 paired binary+txt files available as ground truth in `thor-watcher/example-data/`. Code seam ready at `micromate/idf_file.py`.
|
||||
- [x] **Series IV (Thor IDF) binary codec reverse-engineering.** ✅ v0.21.0 — `micromate/idf_file.read_idf_file()` decodes both IDFW (waveform body at offset `0x0f1f`, reusing `decode_waveform_v2()`; 87–99% sample fidelity on quiet events) and IDFH (dedicated segment-based decoder: all 859 corpus files decode, 181,071 intervals, peaks within ~1.8% of sidecar values). `WaveformStore.save_imported_idf` now also projects parsed Thor data into a `bw_report` block via `micromate/idf_to_bw_report.py` so Thor events render in the existing Event Report PDF pipeline without a separate renderer.
|
||||
- [ ] **In-app waveform viewer accuracy.** Depends on Series III codec decode. Plot.v1 JSON pipeline + viewer skeleton already exist; will start showing real waveforms automatically once `_decode_a5_waveform` produces correct samples. Series IV waveforms come online when the IDF codec lands.
|
||||
- [ ] **Series IV live-device support.** Once the IDF binary is decoded, extend `micromate/` with `transport.py` / `framing.py` / `protocol.py` / `client.py` mirroring the `minimateplus/` package layout — depends on capturing Thor's wire protocol (TCP / RS-232 captures TBD).
|
||||
- [ ] **Terra-view integration** — seismo-relay router, unit detail page, VISON-style event listing.
|
||||
@@ -470,9 +573,10 @@ Use **com0com** or **VSPD** to create the virtual COM pair on Windows.
|
||||
|
||||
### BW ASCII report parser enhancements (built in v0.16.0)
|
||||
|
||||
- [ ] **Histogram-specific structural fields.** Current parser handles the shared fields (PPV, ZC Freq, sensor self-check, project) but silently drops histogram-only fields: `Histogram Start/Stop Time`, `Histogram Start/Stop Date`, `Number of Intervals`, `Interval Size`, per-channel `Peak Time` + `Peak Date` (absolute timestamps rather than the waveform's `Time of Peak` relative seconds).
|
||||
- [x] **PPV field misses on certain TXT formats.** ✅ v0.20.0 — root cause was the `OORANGE` (Out Of Range) saturation marker that BW writes when a channel exceeds its full-scale; `_parse_number()` returned None for the non-numeric value. Parser now substitutes `geo_range_ips` as a lower bound + sets `ppv_saturated` flag. All 5 prod events (T190LD5Q.LK0W, T438L713.RY0W, K557L3YM.OE0W, + 2 others) now parse cleanly.
|
||||
- [x] **Histogram-specific structural fields.** ✅ v0.20.0 — `Histogram Start/Stop Time+Date`, `Number of Intervals`, `Interval Size`, per-channel `Peak Time` + `Peak Date`, and `Peak Vector Sum Date` all parse now. Land in the sidecar's `bw_report.histogram` block.
|
||||
- [ ] **Histogram interval bin-table parsing.** Trailing 792-row table (per-interval Peak/Freq per channel + MicL) in histogram TXTs is unparsed. Probably too big for the sidecar JSON; may want a separate `.histogram.h5` companion file.
|
||||
- [ ] **`>100 Hz` value parsing.** Histogram TXTs use `>100 Hz` for out-of-range ZC freq; current `_parse_number()` returns `None` for these (loses information).
|
||||
- [x] **`>100 Hz` value parsing.** ✅ v0.20.0 — parser now mirrors the OORANGE pattern: stores 100.0 on `zc_freq_hz` + sets `zc_freq_above_range` flag. PDF + both modals render `>100 Hz` instead of `—`.
|
||||
|
||||
### Ingestion gaps
|
||||
|
||||
@@ -498,3 +602,7 @@ Use **com0com** or **VSPD** to create the virtual COM pair on Windows.
|
||||
- [ ] Locate "Sensor Check" byte in compliance config (need capture with Disabled vs Before-monitoring).
|
||||
- [ ] Call Home — map time slots 3/4 offsets; confirm `modem_power_relay_enabled`.
|
||||
- [ ] RV55 DCD/DTR — newer RV55 firmware doesn't assert DCD by default; units don't resume monitoring after call-home disconnect (`--restart-monitoring` flag deferred).
|
||||
- [ ] **NULL-timestamp duplicate-row dedup.** A small handful of events (2 known on prod as of 2026-05-22) have `events.timestamp IS NULL` because the codec couldn't extract a timestamp from the binary footer. The `UNIQUE(serial, timestamp)` constraint doesn't fire on `NULL` (SQL semantics: `NULL ≠ NULL`), so every `--force` backfill INSERTs a new row instead of UPSERTing the existing one. Cleanup: a one-shot SQL query that keeps only the newest row per `(serial, blastware_filename)` and deletes the rest. Longer-term: extend the unique key to `(serial, COALESCE(timestamp, blastware_filename))` or reject inserts with NULL timestamp.
|
||||
- [ ] **Histogram body sub-format with `byte[5] != 0`.** ~3 events on prod (`T190LD5Q.LD0H`, `O121L4L1.GU0H`) use a histogram body my walker doesn't recognize — the first block has `byte[5] = 0x01` or `0x07` instead of `0x00`, and the entire body lacks the `1e 0a 00 00` tail signature. Codec returns 0 valid blocks; their DB PVS comes from the bw_report ASCII overlay (which BW computed from the same binary, so the DB columns are correct). Only the `.h5` waveform plot is empty. Cracking the sub-format would unlock the plot. Needs binary+ASCII pairs from a few `byte[5]!=0` events; same RE approach as the K558 case.
|
||||
- [ ] **Histogram body sub-format with `byte[5] == 0x00` but undecodable.** Observed 2026-05-28 on BE17353 (S353) events: `S353L4H2.FZ0H`, `S353L4H2.P00H`, `S353L4H3.7O0H`, `S353L4H3.E10H`. Body starts `00 00 00 01 0a 00 XX 00 ...` which LOOKS like a valid histogram block header (marker 0x000a at byte[4:6] ✓, byte[5]=0x00 normal-format ✓), but the walker finds zero data blocks across the whole body. Likely an extra header before the block stream OR a different tail signature than `1e 0a 00 00`. Smaller body lengths (1900-2100 bytes) suggest these may be short-recording histogram variants. Same operational impact as the byte[5]!=0 case: event ingests cleanly, DB peaks correct via bw_report overlay, only the chart is empty. Worth dumping a hex view of one body to diagnose.
|
||||
- [ ] **Sensor-check waveform extraction from the BW binary.** BW's Event Report PDFs include a narrow panel on the right side of the waveform plot showing each channel's response to the sensor self-check signal (a damped sinusoid for geo, sawtooth-at-test-freq for mic). Our parser captures the test RESULTS (`test_freq_hz`, `test_ratio`, `test_amplitude_mv`, `test_results` pass/fail) and the PDF + modal display them as text — but BW's per-sample sensor-check waveform isn't accessible to us today. Two paths to add it: (a) RE the binary to find where the sensor-check samples are stored — could be a section before STRT, after the footer, or in a separate sub-record; protocol reference doesn't currently mention it. (b) If samples aren't in the binary, synthesize a representative waveform from the test parameters (damped sinusoid at `test_freq_hz` with damping from `test_ratio`). Path (a) is the honest answer; path (b) is decorative. Until either lands, the text-only sensor-check display in the report is fine.
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Run read_idf_file across the corpus and report per-channel accuracy vs sidecars."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from micromate.idf_file import read_idf_file
|
||||
from analysis_idf.recon import load_sidecar_samples
|
||||
|
||||
|
||||
def sidecar_path(idfw: Path) -> Path:
|
||||
return idfw.parent / "TXT" / f"{idfw.name}.txt"
|
||||
|
||||
|
||||
def main():
|
||||
root = REPO / "tests/fixtures/THORDATA_example"
|
||||
files = [f for f in root.rglob("*.IDFW") if not str(f).endswith(".CDB")]
|
||||
files.sort()
|
||||
GEO_LSB = 0.0003
|
||||
|
||||
n_ok = n_skip = 0
|
||||
overall = {"Tran": [], "Vert": [], "Long": []}
|
||||
|
||||
for f in files:
|
||||
try:
|
||||
res = read_idf_file(f)
|
||||
except Exception:
|
||||
n_skip += 1
|
||||
continue
|
||||
sc_path = sidecar_path(f)
|
||||
if not sc_path.exists():
|
||||
n_skip += 1
|
||||
continue
|
||||
try:
|
||||
sc = load_sidecar_samples(sc_path)
|
||||
except Exception:
|
||||
n_skip += 1
|
||||
continue
|
||||
|
||||
per_file = {}
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
sc_counts = [int(round(v / GEO_LSB)) for v in sc[ch]]
|
||||
dec = res.samples.get(ch, [])
|
||||
n = min(len(sc_counts), len(dec))
|
||||
if n == 0:
|
||||
per_file[ch] = 0.0
|
||||
continue
|
||||
exact = sum(1 for i in range(n) if sc_counts[i] == dec[i])
|
||||
pct = 100.0 * exact / n
|
||||
per_file[ch] = pct
|
||||
overall[ch].append(pct)
|
||||
n_ok += 1
|
||||
|
||||
print(f"Processed {n_ok} files (skipped {n_skip})")
|
||||
print("Per-channel exact-match % (mean / min / max):")
|
||||
for ch, vals in overall.items():
|
||||
if vals:
|
||||
avg = sum(vals) / len(vals)
|
||||
print(f" {ch}: mean={avg:.2f}% min={min(vals):.2f}% max={max(vals):.2f}% n={len(vals)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Find where decoded-vs-sidecar diverges for each channel."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from minimateplus.waveform_codec import decode_waveform_v2
|
||||
from analysis_idf.recon import TARGET, TXT, load_sidecar_samples
|
||||
|
||||
|
||||
def main():
|
||||
buf = TARGET.read_bytes()
|
||||
sc = load_sidecar_samples(TXT)
|
||||
decoded = decode_waveform_v2(buf[0x0f1f:])
|
||||
GEO_LSB = 0.0003
|
||||
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
sc_counts = [int(round(v / GEO_LSB)) for v in sc[ch]]
|
||||
dec = decoded[ch]
|
||||
# Find ALL transitions where mismatches start/stop
|
||||
first_diff = next((i for i in range(len(dec)) if dec[i] != sc_counts[i]), None)
|
||||
if first_diff is None:
|
||||
print(f"{ch}: NO MISMATCHES")
|
||||
continue
|
||||
print(f"{ch}: first diff at idx {first_diff}")
|
||||
# Show 5 before, 5 after
|
||||
for i in range(max(0, first_diff - 3), min(len(dec), first_diff + 8)):
|
||||
mark = " " if dec[i] == sc_counts[i] else "**"
|
||||
print(f" {mark} idx {i:4d}: sc={sc_counts[i]:6d} dec={dec[i]:6d} diff={dec[i]-sc_counts[i]:+d}")
|
||||
# Where does cumulative diff exceed 100?
|
||||
cum_match_run = 0
|
||||
max_match_run = 0
|
||||
match_run_start = 0
|
||||
diff_count = 0
|
||||
for i in range(len(dec)):
|
||||
if dec[i] == sc_counts[i]:
|
||||
cum_match_run += 1
|
||||
max_match_run = max(max_match_run, cum_match_run)
|
||||
else:
|
||||
cum_match_run = 0
|
||||
diff_count += 1
|
||||
print(f" total mismatches: {diff_count}/{len(dec)}, longest run of matches: {max_match_run}")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
"""End-to-end IDFH ingest verification."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import tempfile
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
|
||||
def main():
|
||||
idfh = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM13981/UM13981_20220805075441.IDFH"
|
||||
txt = idfh.parent / "TXT" / f"{idfh.name}.txt"
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
store = WaveformStore(Path(td))
|
||||
ev, rec = store.save_imported_idf(
|
||||
idfh.read_bytes(),
|
||||
idfh,
|
||||
idf_report_text=txt.read_text(errors="replace"),
|
||||
)
|
||||
print("=== save_imported_idf (IDFH) ===")
|
||||
print(f" serial: {rec['serial']}")
|
||||
print(f" filename: {rec['filename']}")
|
||||
print(f" filesize: {rec['filesize']}")
|
||||
print(f" h5: {rec['hdf5_filename']}") # expect None for histogram
|
||||
print(f" sidecar: {rec['sidecar_filename']}")
|
||||
print()
|
||||
print("=== Event ===")
|
||||
print(f" timestamp: {ev.timestamp}")
|
||||
print(f" record_type: {ev.record_type}")
|
||||
print(f" sample_rate: {ev.sample_rate}")
|
||||
print()
|
||||
# Inspect sidecar to confirm intervals were stashed
|
||||
sc_path = Path(td) / "UM13981" / f"{idfh.name}.sfm.json"
|
||||
sc = json.loads(sc_path.read_text())
|
||||
intervals = sc.get("extensions", {}).get("idf_intervals", [])
|
||||
print(f" sidecar intervals: {len(intervals)}")
|
||||
if intervals:
|
||||
print(f" first interval: {intervals[0]}")
|
||||
print(f" last interval: {intervals[-1]}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Verify the had_report=False path: ingest IDFW with no .txt."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
|
||||
def main():
|
||||
idfw = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719/UM11719_20231219162723.IDFW"
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
store = WaveformStore(Path(td))
|
||||
ev, rec = store.save_imported_idf(
|
||||
idfw.read_bytes(),
|
||||
idfw,
|
||||
serial_hint=None,
|
||||
idf_report_text=None, # ← no .txt!
|
||||
)
|
||||
print("=== IDFW without .txt ingest ===")
|
||||
print(f" serial: {rec['serial']}")
|
||||
print(f" timestamp: {ev.timestamp}")
|
||||
print(f" sample_rate: {ev.sample_rate}")
|
||||
print(f" record_type: {ev.record_type}")
|
||||
print(f" rectime_sec: {ev.rectime_seconds}")
|
||||
nT = len(ev.raw_samples.get('Tran', [])) if ev.raw_samples else 0
|
||||
nV = len(ev.raw_samples.get('Vert', [])) if ev.raw_samples else 0
|
||||
nL = len(ev.raw_samples.get('Long', [])) if ev.raw_samples else 0
|
||||
nM = len(ev.raw_samples.get('MicL', [])) if ev.raw_samples else 0
|
||||
print(f" raw_samples: Tran={nT} Vert={nV} Long={nL} MicL={nM}")
|
||||
if ev.peak_values:
|
||||
print(f" peak_values: tran={ev.peak_values.tran} vert={ev.peak_values.vert} long={ev.peak_values.long}")
|
||||
print(f" h5 written: {rec['hdf5_filename']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,102 @@
|
||||
"""End-to-end Thor report PDF rendering.
|
||||
|
||||
Ingests an IDFW + .txt via save_imported_idf, runs gather_report_data
|
||||
(faking a minimal DB row), and renders the PDF to disk.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import tempfile
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from sfm import report_pdf
|
||||
|
||||
|
||||
class FakeDb:
|
||||
"""Stand-in for SeismoDb.get_event(); the renderer only needs a few cols."""
|
||||
def __init__(self, event):
|
||||
self.event = event
|
||||
|
||||
def get_event(self, _id):
|
||||
return self.event
|
||||
|
||||
|
||||
def main():
|
||||
base = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719"
|
||||
idfw = base / "UM11719_20231219162723.IDFW"
|
||||
txt = base / "TXT" / f"{idfw.name}.txt"
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
store = WaveformStore(Path(td))
|
||||
ev, rec = store.save_imported_idf(
|
||||
idfw.read_bytes(),
|
||||
idfw,
|
||||
idf_report_text=txt.read_text(errors="replace"),
|
||||
)
|
||||
print(f"save_imported_idf: h5={rec['hdf5_filename']}, sidecar={rec['sidecar_filename']}")
|
||||
|
||||
# Verify sidecar has bw_report block
|
||||
sc_path = Path(td) / "UM11719" / f"{idfw.name}.sfm.json"
|
||||
sc = json.loads(sc_path.read_text())
|
||||
bw = sc.get("bw_report", {})
|
||||
print(f" bw_report.available: {bw.get('available')}")
|
||||
print(f" bw_report.peaks.tran.ppv_ips: {bw.get('peaks', {}).get('tran', {}).get('ppv_ips')}")
|
||||
print(f" bw_report.mic.pspl_dbl: {bw.get('mic', {}).get('pspl_dbl')}")
|
||||
print(f" bw_report.histogram.n_intervals: {bw.get('histogram', {}).get('n_intervals')}")
|
||||
|
||||
# Build a DB-row-shaped dict from the Event for gather_report_data
|
||||
import datetime
|
||||
ts = ev.timestamp
|
||||
ts_iso = None
|
||||
if ts is not None:
|
||||
try:
|
||||
ts_iso = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second).isoformat()
|
||||
except Exception:
|
||||
pass
|
||||
fake_row = {
|
||||
"serial": "UM11719",
|
||||
"blastware_filename": rec["filename"],
|
||||
"record_type": "Waveform",
|
||||
"timestamp": ts_iso,
|
||||
"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()
|
||||
print(f"=== ReportData ===")
|
||||
print(f" event_id: {rd.event_id}")
|
||||
print(f" serial: {rd.serial}")
|
||||
print(f" record_type: {rd.record_type}")
|
||||
print(f" event_datetime: {rd.event_datetime_str}")
|
||||
print(f" trigger: {rd.trigger_source}")
|
||||
print(f" geo_range: {rd.geo_range_str}")
|
||||
print(f" sample_rate: {rd.sample_rate_str}")
|
||||
print(f" firmware: {rd.firmware}")
|
||||
print(f" calibration: {rd.calibration_date} by {rd.calibration_by}")
|
||||
print(f" battery: {rd.battery_volts}")
|
||||
print(f" PVS: {rd.peak_vector_sum_ips} in/s at {rd.peak_vector_sum_time_s} sec")
|
||||
print(f" mic_pspl_dbl: {rd.mic_pspl_dbl}")
|
||||
print(f" mic_zc_freq_hz: {rd.mic_zc_freq_hz}")
|
||||
print(f" channel_stats: {len(rd.channel_stats)} rows")
|
||||
for cs in rd.channel_stats:
|
||||
print(f" {cs['name']}: PPV={cs['ppv_ips']} ZC={cs['zc_freq_hz']} ToP={cs['time_of_peak_s']} Acc={cs['peak_accel_g']} Disp={cs['peak_disp_in']} Test={cs['sensor_check']}")
|
||||
|
||||
# Render the PDF
|
||||
out_path = REPO / "analysis_idf" / "thor_report.pdf"
|
||||
pdf_bytes = report_pdf.render_event_report_pdf(rd)
|
||||
out_path.write_bytes(pdf_bytes)
|
||||
print()
|
||||
print(f" PDF written: {out_path} ({len(pdf_bytes)} bytes)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,91 @@
|
||||
"""End-to-end Thor IDFH histogram report PDF rendering."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import tempfile
|
||||
import json
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from sfm import report_pdf
|
||||
|
||||
|
||||
class FakeDb:
|
||||
def __init__(self, event):
|
||||
self.event = event
|
||||
|
||||
def get_event(self, _id):
|
||||
return self.event
|
||||
|
||||
|
||||
def main():
|
||||
# Use the multi-interval IDFH (81 + trigger row)
|
||||
idfh = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM13981/UM13981_20220805075441.IDFH"
|
||||
txt = idfh.parent / "TXT" / f"{idfh.name}.txt"
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
store = WaveformStore(Path(td))
|
||||
ev, rec = store.save_imported_idf(
|
||||
idfh.read_bytes(),
|
||||
idfh,
|
||||
idf_report_text=txt.read_text(errors="replace"),
|
||||
)
|
||||
print(f"save_imported_idf: h5={rec['hdf5_filename']}, sidecar={rec['sidecar_filename']}")
|
||||
|
||||
sc_path = Path(td) / "UM13981" / f"{idfh.name}.sfm.json"
|
||||
sc = json.loads(sc_path.read_text())
|
||||
bw = sc.get("bw_report", {})
|
||||
hist = bw.get("histogram", {})
|
||||
print(f" bw_report.histogram.start: {hist.get('start')}")
|
||||
print(f" bw_report.histogram.stop: {hist.get('stop')}")
|
||||
print(f" bw_report.histogram.n_intervals: {hist.get('n_intervals')}")
|
||||
print(f" bw_report.histogram.interval_size: {hist.get('interval_size')}")
|
||||
print(f" bw_report.histogram.interval_size_s: {hist.get('interval_size_s')}")
|
||||
print(f" bw_report.peaks.tran.ppv_ips: {bw.get('peaks', {}).get('tran', {}).get('ppv_ips')}")
|
||||
|
||||
ts = ev.timestamp
|
||||
ts_iso = None
|
||||
if ts is not None:
|
||||
try:
|
||||
ts_iso = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second).isoformat()
|
||||
except Exception:
|
||||
pass
|
||||
fake_row = {
|
||||
"serial": "UM13981",
|
||||
"blastware_filename": rec["filename"],
|
||||
"record_type": "Histogram",
|
||||
"timestamp": ts_iso,
|
||||
"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="hist-1")
|
||||
|
||||
print()
|
||||
print("=== ReportData (histogram) ===")
|
||||
print(f" is_histogram: {rd.is_histogram}")
|
||||
print(f" histogram_start: {rd.histogram_start_str}")
|
||||
print(f" histogram_stop: {rd.histogram_stop_str}")
|
||||
print(f" histogram_n_intervals: {rd.histogram_n_intervals}")
|
||||
print(f" histogram_interval_size:{rd.histogram_interval_size}")
|
||||
print(f" histogram_interval_times[:3]: {rd.histogram_interval_times[:3]}")
|
||||
print(f" histogram_interval_times[-2:]: {rd.histogram_interval_times[-2:]}")
|
||||
print(f" channel_stats: {len(rd.channel_stats)} rows")
|
||||
for cs in rd.channel_stats:
|
||||
print(f" {cs['name']}: PPV={cs['ppv_ips']} ZC={cs['zc_freq_hz']} peak_date={cs['peak_date']} peak_time={cs['peak_time']}")
|
||||
|
||||
pdf_bytes = report_pdf.render_event_report_pdf(rd)
|
||||
out_path = REPO / "analysis_idf" / "thor_report_idfh.pdf"
|
||||
out_path.write_bytes(pdf_bytes)
|
||||
print()
|
||||
print(f" PDF written: {out_path} ({len(pdf_bytes)} bytes)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""End-to-end ingest test: feed an IDFW + .txt to save_imported_idf in a tmp store."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import shutil
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
|
||||
def main():
|
||||
idfw = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719/UM11719_20231219162723.IDFW"
|
||||
txt = idfw.parent / "TXT" / f"{idfw.name}.txt"
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
store = WaveformStore(Path(td))
|
||||
ev, rec = store.save_imported_idf(
|
||||
idfw.read_bytes(),
|
||||
idfw,
|
||||
serial_hint=None,
|
||||
idf_report_text=txt.read_text(errors="replace"),
|
||||
)
|
||||
print("=== Save result ===")
|
||||
print(f" serial: {rec['serial']}")
|
||||
print(f" filename: {rec['filename']}")
|
||||
print(f" filesize: {rec['filesize']}")
|
||||
print(f" h5: {rec['hdf5_filename']}")
|
||||
print(f" sidecar: {rec['sidecar_filename']}")
|
||||
print()
|
||||
print("=== Event ===")
|
||||
print(f" serial: {ev.serial if hasattr(ev,'serial') else '(n/a)'}")
|
||||
print(f" timestamp: {ev.timestamp}")
|
||||
print(f" sample_rate: {ev.sample_rate}")
|
||||
print(f" record_type: {ev.record_type}")
|
||||
print(f" rectime_sec: {ev.rectime_seconds}")
|
||||
print(f" raw_samples: Tran={len(ev.raw_samples.get('Tran', [])) if ev.raw_samples else 0}, Vert={len(ev.raw_samples.get('Vert', [])) if ev.raw_samples else 0}, Long={len(ev.raw_samples.get('Long', [])) if ev.raw_samples else 0}, MicL={len(ev.raw_samples.get('MicL', [])) if ev.raw_samples else 0}")
|
||||
if ev.peak_values:
|
||||
print(f" peaks (txt): Tran={ev.peak_values.tran} Vert={ev.peak_values.vert} Long={ev.peak_values.long}")
|
||||
print()
|
||||
|
||||
# Verify the h5 file actually got written
|
||||
h5path = Path(td) / "UM11719" / f"{idfw.name}.h5"
|
||||
print(f" h5 exists: {h5path.exists()} size={h5path.stat().st_size if h5path.exists() else 0}")
|
||||
sidecar = Path(td) / "UM11719" / f"{idfw.name}.sfm.json"
|
||||
print(f" sidecar exists:{sidecar.exists()} size={sidecar.stat().st_size if sidecar.exists() else 0}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Decode IDFH histogram intervals + verify against sidecar."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import struct
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
|
||||
SEGMENT_MAGIC = b"\x02\xda\x0a\x00\x00\x00"
|
||||
SEGMENT_SIZE = 732 # = 10-byte header + 10 × 72-byte intervals + 2-byte tail
|
||||
INTERVAL_SIZE = 72
|
||||
CHANNELS = ("Tran", "Vert", "Long", "MicL")
|
||||
|
||||
|
||||
def decode_interval(buf72: bytes) -> dict:
|
||||
"""Decode one 72-byte interval into per-channel min/max/halfp."""
|
||||
out = {}
|
||||
for i, ch in enumerate(CHANNELS):
|
||||
block = buf72[i*16 : (i+1)*16]
|
||||
mn = struct.unpack_from(">h", block, 0)[0]
|
||||
mx = struct.unpack_from(">h", block, 2)[0]
|
||||
sb = struct.unpack_from(">h", block, 4)[0]
|
||||
halfp = struct.unpack_from(">H", block, 6)[0]
|
||||
f10 = struct.unpack_from(">H", block, 10)[0]
|
||||
f14 = struct.unpack_from(">H", block, 14)[0]
|
||||
peak_count = max(abs(mn), abs(mx))
|
||||
out[ch] = {
|
||||
"min": mn,
|
||||
"max": mx,
|
||||
"field4": sb,
|
||||
"halfp": halfp,
|
||||
"field10": f10,
|
||||
"field14": f14,
|
||||
"peak": peak_count,
|
||||
"freq_hz": (512.0 / halfp) if halfp > 5 else None,
|
||||
}
|
||||
out["_tail"] = buf72[64:].hex(" ")
|
||||
return out
|
||||
|
||||
|
||||
def walk_idfh(buf: bytes) -> list:
|
||||
"""Walk all interval records in an IDFH file."""
|
||||
intervals = []
|
||||
# Multi-segment file: every 02 da 0a 00 00 00 marker introduces a segment.
|
||||
# Single-interval file: just one body header at 0xf96 of form ?? ?? 0a 00 00 00.
|
||||
# Find them all.
|
||||
i = 0
|
||||
while True:
|
||||
j = buf.find(b"\x0a\x00\x00\x00", i)
|
||||
if j < 0:
|
||||
break
|
||||
# Validate: the 2 bytes before must form a length, and we want bytes
|
||||
# [j-2 : j+6] to have a recognisable shape. Actually the cleanest
|
||||
# filter is "preceded by a length and followed by 00 NN 05 3f".
|
||||
if j < 2:
|
||||
i = j + 1
|
||||
continue
|
||||
# Body header form: [length_be_2][0a 00 00 00][00 NN][05 3f]
|
||||
if j + 10 > len(buf):
|
||||
break
|
||||
length = int.from_bytes(buf[j-2:j], "big")
|
||||
# Verify the segment-marker shape: [length_be][0a 00 00 00][00 NN][05 3f]
|
||||
if buf[j+4] != 0x00:
|
||||
i = j + 1
|
||||
continue
|
||||
if buf[j+6:j+8] != b"\x05\x3f":
|
||||
i = j + 1
|
||||
continue
|
||||
# Header layout (10 bytes): [length_be 2B][0a 00 00 00 4B][00 NN 2B][05 3f 2B]
|
||||
# Followed by N interval records of 72 bytes each, then 2 tail bytes.
|
||||
# length value = (N × 72) + 10 (counts bytes from 0x0a... through interval data).
|
||||
header_start = j - 2
|
||||
n_intervals = (length - 10) // INTERVAL_SIZE
|
||||
interval_start = header_start + 10
|
||||
for k in range(n_intervals):
|
||||
off = interval_start + k * INTERVAL_SIZE
|
||||
if off + INTERVAL_SIZE > len(buf):
|
||||
break
|
||||
chunk = buf[off:off + INTERVAL_SIZE]
|
||||
intervals.append({"offset": off, **decode_interval(chunk)})
|
||||
i = header_start + length + 2
|
||||
return intervals
|
||||
|
||||
|
||||
def main():
|
||||
# Test against multi-segment IDFH
|
||||
target = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM13981/UM13981_20220805075441.IDFH"
|
||||
sc_path = target.parent / "TXT" / f"{target.name}.txt"
|
||||
buf = target.read_bytes()
|
||||
intervals = walk_idfh(buf)
|
||||
print(f"=== {target.name} ===")
|
||||
print(f" file size: {len(buf)}")
|
||||
print(f" decoded intervals: {len(intervals)}")
|
||||
# Show first 2 + last 2
|
||||
sc_rows = []
|
||||
for line in sc_path.read_text(errors="replace").splitlines():
|
||||
if line.startswith("2022-") or line.startswith("2023-"):
|
||||
sc_rows.append(line)
|
||||
print(f" sidecar rows: {len(sc_rows)}")
|
||||
|
||||
print()
|
||||
for k in [0, 1, 78, 79, 80]:
|
||||
if k >= len(intervals):
|
||||
continue
|
||||
iv = intervals[k]
|
||||
print(f"--- interval {k} @0x{iv['offset']:04x} ---")
|
||||
for ch in CHANNELS:
|
||||
d = iv[ch]
|
||||
peak_ips = d["peak"] / 32768 * 10.0
|
||||
print(f" {ch}: peak={d['peak']:5d} ({peak_ips:.4f} in/s) halfp={d['halfp']:5d} freq={d['freq_hz']}")
|
||||
# sidecar row
|
||||
if k < len(sc_rows):
|
||||
print(f" SC: {sc_rows[k]}")
|
||||
|
||||
# Test single-interval IDFH
|
||||
print()
|
||||
target2 = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719/UM11719_20231219162648.IDFH"
|
||||
sc2 = target2.parent / "TXT" / f"{target2.name}.txt"
|
||||
buf2 = target2.read_bytes()
|
||||
intervals2 = walk_idfh(buf2)
|
||||
print(f"=== {target2.name} ===")
|
||||
print(f" file size: {len(buf2)}, decoded intervals: {len(intervals2)}")
|
||||
if intervals2:
|
||||
iv = intervals2[0]
|
||||
for ch in CHANNELS:
|
||||
d = iv[ch]
|
||||
peak_ips = d["peak"] / 32768 * 10.0
|
||||
print(f" {ch}: peak={d['peak']:5d} ({peak_ips:.4f} in/s) halfp={d['halfp']:5d} freq={d['freq_hz']}")
|
||||
sc_rows2 = [l for l in sc2.read_text(errors='replace').splitlines() if l.startswith("2023-")]
|
||||
if sc_rows2:
|
||||
print(f" SC: {sc_rows2[0]}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Find IDFH interval period via auto-correlation of structural patterns."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from collections import Counter
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
|
||||
def main():
|
||||
target = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM13981/UM13981_20220805075441.IDFH"
|
||||
buf = target.read_bytes()
|
||||
body_start = 0xF96
|
||||
body_end = 0x270C
|
||||
body = buf[body_start:body_end]
|
||||
print(f"body size: {len(body)} bytes (file {len(buf)} bytes)")
|
||||
|
||||
# For each candidate interval size, count how many bytes at fixed offsets within
|
||||
# each interval are zero (consistent column-zero pattern indicates correct size).
|
||||
print()
|
||||
print("=== zero-column score by interval size (higher = more likely) ===")
|
||||
best = []
|
||||
for sz in range(16, 100):
|
||||
n = len(body) // sz
|
||||
if n < 30:
|
||||
continue
|
||||
# For each column position within an interval, count how many of n intervals have zero
|
||||
score = 0
|
||||
for col in range(sz):
|
||||
zeros = sum(1 for i in range(n) if body[i*sz + col] == 0)
|
||||
if zeros >= n * 0.9:
|
||||
score += 1
|
||||
best.append((score, sz, n))
|
||||
best.sort(reverse=True)
|
||||
for score, sz, n in best[:10]:
|
||||
print(f" size={sz:3d} n_intervals={n} consistently-zero-cols={score}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Per-file accuracy + sample-count details."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from micromate.idf_file import read_idf_file
|
||||
from analysis_idf.recon import load_sidecar_samples
|
||||
|
||||
|
||||
def main():
|
||||
root = REPO / "tests/fixtures/THORDATA_example"
|
||||
files = sorted([f for f in root.rglob("*.IDFW") if not str(f).endswith(".CDB")])
|
||||
GEO_LSB = 0.0003
|
||||
# Limit to first 15 successful files for detail.
|
||||
shown = 0
|
||||
for f in files:
|
||||
try:
|
||||
res = read_idf_file(f)
|
||||
except Exception:
|
||||
continue
|
||||
sc_path = f.parent / "TXT" / f"{f.name}.txt"
|
||||
if not sc_path.exists():
|
||||
continue
|
||||
sc = load_sidecar_samples(sc_path)
|
||||
sc_tran = [int(round(v / GEO_LSB)) for v in sc["Tran"]]
|
||||
dec = res.samples.get("Tran", [])
|
||||
n = min(len(sc_tran), len(dec))
|
||||
exact = sum(1 for i in range(n) if sc_tran[i] == dec[i]) if n else 0
|
||||
pct = 100.0 * exact / n if n else 0.0
|
||||
print(f"{f.name:40s} size={f.stat().st_size:6d} sc_n={len(sc_tran):4d} dec_n={len(dec):4d} exact={pct:.1f}%")
|
||||
shown += 1
|
||||
if shown >= 20:
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Look at what's at the divergence boundary."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from minimateplus.waveform_codec import walk_body, find_data_start, parse_segment_header
|
||||
from analysis_idf.recon import TARGET, TXT, load_sidecar_samples
|
||||
|
||||
|
||||
def main():
|
||||
buf = TARGET.read_bytes()
|
||||
body = buf[0x0f1f:]
|
||||
start = find_data_start(body)
|
||||
print(f"data_start: {start} (= file offset 0x{0x0f1f + start:04x})")
|
||||
|
||||
blocks = walk_body(body, start)
|
||||
print(f"{len(blocks)} blocks total")
|
||||
print()
|
||||
|
||||
# First 25 blocks
|
||||
print("=== first 30 blocks ===")
|
||||
for i, b in enumerate(blocks[:30]):
|
||||
body_off = 0x0f1f + b.offset
|
||||
if b.tag_hi == 0x40:
|
||||
hdr = parse_segment_header(b)
|
||||
print(f" [{i:3d}] @0x{body_off:04x} {b.kind} (segment header) counter={hdr['counter'] if hdr else '?'} field2={hdr['field2'].hex() if hdr else '?'} anchor={hdr['anchor_bytes'].hex() if hdr else '?'} tail={hdr['tail'].hex() if hdr else '?'}")
|
||||
else:
|
||||
print(f" [{i:3d}] @0x{body_off:04x} {b.kind} len={b.length} data={b.data[:16].hex()}")
|
||||
print()
|
||||
|
||||
# Cumulative sample counts per block to find which block contains sample 254
|
||||
print("=== cumulative samples through blocks ===")
|
||||
cur_ch = "Tran"
|
||||
rotation = ["Vert", "Long", "MicL", "Tran"]
|
||||
seg_count = 0
|
||||
samples_in_curseg = 2 # preamble Tran[0], Tran[1]
|
||||
for i, b in enumerate(blocks[:30]):
|
||||
if b.tag_hi == 0x40:
|
||||
seg_count += 1
|
||||
prev_ch = cur_ch
|
||||
cur_ch = rotation[(seg_count - 1) % 4]
|
||||
print(f" [{i:3d}] 40 02 -> end of {prev_ch} segment, start {cur_ch} (segment {seg_count})")
|
||||
samples_in_curseg = 2 # anchors
|
||||
elif (b.tag_hi & 0xF0) == 0x10:
|
||||
nn = ((b.tag_hi & 0x0F) << 8) | b.tag_lo
|
||||
samples_in_curseg += nn
|
||||
print(f" [{i:3d}] {b.kind} nibble: +{nn} samples, ch={cur_ch}, ch_total~{samples_in_curseg}")
|
||||
elif (b.tag_hi & 0xF0) == 0x20:
|
||||
nn = ((b.tag_hi & 0x0F) << 8) | b.tag_lo
|
||||
samples_in_curseg += nn
|
||||
print(f" [{i:3d}] {b.kind} int8: +{nn} samples, ch={cur_ch}, ch_total~{samples_in_curseg}")
|
||||
elif b.tag_hi == 0x00:
|
||||
samples_in_curseg += b.tag_lo
|
||||
print(f" [{i:3d}] {b.kind} RLE: +{b.tag_lo}, ch={cur_ch}, ch_total~{samples_in_curseg}")
|
||||
elif b.tag_hi == 0x30:
|
||||
samples_in_curseg += b.tag_lo
|
||||
print(f" [{i:3d}] {b.kind} packed12: +{b.tag_lo} samples, ch={cur_ch}, ch_total~{samples_in_curseg}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Reconnaissance helpers for cracking the Thor IDFW binary."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
TARGET = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719/UM11719_20231219162723.IDFW"
|
||||
TXT = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719/TXT/UM11719_20231219162723.IDFW.txt"
|
||||
|
||||
|
||||
def hex_at(buf: bytes, off: int, n: int = 32) -> str:
|
||||
chunk = buf[off : off + n]
|
||||
hexs = " ".join(f"{b:02x}" for b in chunk)
|
||||
asc = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
|
||||
return f"{off:04x}: {hexs} {asc}"
|
||||
|
||||
|
||||
def find_all(buf: bytes, needle: bytes) -> list[int]:
|
||||
out: list[int] = []
|
||||
i = 0
|
||||
while True:
|
||||
j = buf.find(needle, i)
|
||||
if j < 0:
|
||||
break
|
||||
out.append(j)
|
||||
i = j + 1
|
||||
return out
|
||||
|
||||
|
||||
def load_sidecar_samples(path: Path) -> dict[str, list[float]]:
|
||||
"""Parse the txt sample table — Tran/Vert/Long/MicL."""
|
||||
out = {"Tran": [], "Vert": [], "Long": [], "MicL": []}
|
||||
in_block = False
|
||||
for line in path.read_text(errors="replace").splitlines():
|
||||
if not in_block:
|
||||
if line.strip() == "Waveform Data Channels":
|
||||
in_block = True
|
||||
continue
|
||||
if line.startswith("Waveform Data USB Channels"):
|
||||
break
|
||||
parts = line.split("\t")
|
||||
# First row is the header "\tTran\tVert\tLong\tMicL"
|
||||
if len(parts) >= 5 and parts[1] == "Tran":
|
||||
continue
|
||||
if len(parts) < 5:
|
||||
continue
|
||||
try:
|
||||
out["Tran"].append(float(parts[1]))
|
||||
out["Vert"].append(float(parts[2]))
|
||||
out["Long"].append(float(parts[3]))
|
||||
out["MicL"].append(float(parts[4]))
|
||||
except ValueError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
buf = TARGET.read_bytes()
|
||||
samples = load_sidecar_samples(TXT)
|
||||
print(f"file size: {len(buf)} bytes")
|
||||
print(f"sample rows: Tran={len(samples['Tran'])} Vert={len(samples['Vert'])} Long={len(samples['Long'])} MicL={len(samples['MicL'])}")
|
||||
print(f"first 6 Tran samples: {samples['Tran'][:6]}")
|
||||
print(f"first 6 Vert samples: {samples['Vert'][:6]}")
|
||||
print(f"first 6 Long samples: {samples['Long'][:6]}")
|
||||
print(f"first 6 MicL samples: {samples['MicL'][:6]}")
|
||||
|
||||
print()
|
||||
print("=== BW magic '00 02 00' positions ===")
|
||||
hits = find_all(buf, b"\x00\x02\x00")
|
||||
print(f"{len(hits)} hits")
|
||||
for h in hits[:20]:
|
||||
print(hex_at(buf, h, 24))
|
||||
|
||||
print()
|
||||
print("=== '40 02' segment-header positions ===")
|
||||
hits = find_all(buf, b"\x40\x02")
|
||||
print(f"{len(hits)} hits")
|
||||
for h in hits:
|
||||
ctx_pre = buf[max(0, h - 4): h].hex()
|
||||
ctx_post = buf[h: h + 20].hex()
|
||||
# Show byte preceding to help identify real headers vs casual occurrences
|
||||
print(f" 0x{h:04x} pre={ctx_pre} post={ctx_post}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Find each segment boundary in the channel and check if errors reset there."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from minimateplus.waveform_codec import decode_waveform_v2
|
||||
from analysis_idf.recon import TARGET, TXT, load_sidecar_samples
|
||||
|
||||
|
||||
def main():
|
||||
buf = TARGET.read_bytes()
|
||||
sc = load_sidecar_samples(TXT)
|
||||
decoded = decode_waveform_v2(buf[0x0f1f:])
|
||||
GEO_LSB = 0.0003
|
||||
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
sc_counts = [int(round(v / GEO_LSB)) for v in sc[ch]]
|
||||
dec = decoded[ch]
|
||||
# Find every transition where error becomes zero from nonzero (or grows from zero)
|
||||
# Print indices where dec resyncs back to exact match.
|
||||
n = min(len(sc_counts), len(dec))
|
||||
events = []
|
||||
prev_match = True
|
||||
for i in range(n):
|
||||
match = sc_counts[i] == dec[i]
|
||||
if match != prev_match:
|
||||
kind = "RESYNC" if match else "DIVERGE"
|
||||
events.append((i, kind, sc_counts[i], dec[i]))
|
||||
prev_match = match
|
||||
print(f"{ch}: {len(events)} transitions")
|
||||
for i, kind, sc_v, dec_v in events[:20]:
|
||||
print(f" idx {i:4d} {kind:8s} sc={sc_v:6d} dec={dec_v:6d} diff={dec_v-sc_v:+d}")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Smoke-test read_idf_file on IDFH across the corpus."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from micromate.idf_file import read_idf_file
|
||||
|
||||
|
||||
def main():
|
||||
target = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719/UM11719_20231219162648.IDFH"
|
||||
result = read_idf_file(target)
|
||||
ev = result.event
|
||||
print(f"=== {target.name} ===")
|
||||
print(f" signature: {result.signature}")
|
||||
print(f" serial: {ev.serial}")
|
||||
print(f" timestamp: {ev.timestamp}")
|
||||
print(f" sample_rate: {ev.sample_rate}")
|
||||
print(f" kind: {ev.kind}")
|
||||
print(f" intervals: {len(result.intervals or [])}")
|
||||
print(f" peaks: T={ev.peaks.transverse_ips:.4f} V={ev.peaks.vertical_ips:.4f} L={ev.peaks.longitudinal_ips:.4f}")
|
||||
print()
|
||||
|
||||
root = REPO / "tests/fixtures/THORDATA_example"
|
||||
files = list(root.rglob("*.IDFH"))
|
||||
ok = fail = nyi = 0
|
||||
total_intervals = 0
|
||||
for f in files:
|
||||
try:
|
||||
r = read_idf_file(f)
|
||||
ok += 1
|
||||
total_intervals += len(r.intervals or [])
|
||||
except NotImplementedError:
|
||||
nyi += 1
|
||||
except Exception as exc:
|
||||
fail += 1
|
||||
if fail <= 3:
|
||||
print(f" FAIL: {f.name}: {type(exc).__name__}: {exc}")
|
||||
print(f"Corpus: {len(files)} IDFH files | ok={ok} fail={fail} nyi={nyi}")
|
||||
print(f"Total intervals decoded: {total_intervals}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Smoke-test read_idf_file across the sample corpus."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from micromate.idf_file import read_idf_file, geo_count_to_ips, mic_count_to_psi
|
||||
|
||||
|
||||
def main():
|
||||
target = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719/UM11719_20231219162723.IDFW"
|
||||
result = read_idf_file(target)
|
||||
ev = result.event
|
||||
print(f"=== {target.name} ===")
|
||||
print(f" signature: {result.signature}")
|
||||
print(f" serial: {ev.serial}")
|
||||
print(f" timestamp: {ev.timestamp}")
|
||||
print(f" sample_rate: {ev.sample_rate}")
|
||||
print(f" record_time: {ev.record_time_sec}")
|
||||
print(f" calibration: {result.binary_metadata.calibration_date}")
|
||||
print(f" Tran samples: {len(result.samples['Tran'])}, peak_ips={ev.peaks.transverse_ips:.4f}")
|
||||
print(f" Vert samples: {len(result.samples['Vert'])}, peak_ips={ev.peaks.vertical_ips:.4f}")
|
||||
print(f" Long samples: {len(result.samples['Long'])}, peak_ips={ev.peaks.longitudinal_ips:.4f}")
|
||||
print(f" MicL samples: {len(result.samples['MicL'])}")
|
||||
print()
|
||||
|
||||
# Corpus sweep
|
||||
root = REPO / "tests/fixtures/THORDATA_example"
|
||||
files = [f for f in root.rglob("*.IDFW") if not str(f).endswith(".CDB")]
|
||||
ok = fail = nyi = 0
|
||||
for f in files:
|
||||
try:
|
||||
r = read_idf_file(f)
|
||||
ok += 1
|
||||
except NotImplementedError:
|
||||
nyi += 1
|
||||
except Exception as exc:
|
||||
fail += 1
|
||||
if fail <= 5:
|
||||
print(f" FAIL: {f.name}: {type(exc).__name__}: {exc}")
|
||||
print()
|
||||
print(f"Corpus: {len(files)} IDFW files | ok={ok} fail={fail} not-implemented={nyi}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Verify build_bw_report_from_idf against a known sidecar."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from micromate.idf_ascii_report import parse_idf_report
|
||||
from micromate.idf_to_bw_report import build_bw_report_from_idf
|
||||
from micromate.idf_file import read_idf_file
|
||||
|
||||
|
||||
def show(prefix: str, d: dict, indent: int = 0):
|
||||
for k, v in d.items():
|
||||
if isinstance(v, dict):
|
||||
print(f"{' '*indent}{prefix}{k}:")
|
||||
show("", v, indent + 1)
|
||||
else:
|
||||
print(f"{' '*indent}{prefix}{k}: {v!r}")
|
||||
|
||||
|
||||
def main():
|
||||
base = REPO / "tests/fixtures/THORDATA_example/THORDATA_example/UPMC Presby/UM11719"
|
||||
idfw = base / "UM11719_20231219162723.IDFW"
|
||||
txt = base / "TXT" / f"{idfw.name}.txt"
|
||||
|
||||
report_dict = parse_idf_report(txt.read_text(errors="replace"))
|
||||
res = read_idf_file(idfw)
|
||||
bw = build_bw_report_from_idf(report_dict, binary_md=res.binary_metadata)
|
||||
|
||||
print("=== IDFW → bw_report ===")
|
||||
show("", bw)
|
||||
|
||||
print()
|
||||
print("=== IDFH (single trigger row) ===")
|
||||
idfh = base / "UM11719_20231219162648.IDFH"
|
||||
txt_h = base / "TXT" / f"{idfh.name}.txt"
|
||||
rh = parse_idf_report(txt_h.read_text(errors="replace"))
|
||||
res_h = read_idf_file(idfh)
|
||||
bw_h = build_bw_report_from_idf(rh, binary_md=res_h.binary_metadata, intervals=res_h.intervals)
|
||||
show("", bw_h)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,73 @@
|
||||
"""Trace Tran sample-by-sample to find exactly where the codec drifts."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from analysis_idf.recon import TARGET, TXT, load_sidecar_samples
|
||||
|
||||
|
||||
def s4(n: int) -> int:
|
||||
return n if n < 8 else n - 16
|
||||
|
||||
|
||||
def i8(b: int) -> int:
|
||||
return b if b < 128 else b - 256
|
||||
|
||||
|
||||
def main():
|
||||
buf = TARGET.read_bytes()
|
||||
sc = load_sidecar_samples(TXT)
|
||||
GEO_LSB = 0.0003
|
||||
sc_tran = [int(round(v / GEO_LSB)) for v in sc["Tran"]]
|
||||
|
||||
body = buf[0x0f1f:]
|
||||
# Tran[0], Tran[1] from preamble
|
||||
t0 = int.from_bytes(body[3:5], "big", signed=True)
|
||||
t1 = int.from_bytes(body[5:7], "big", signed=True)
|
||||
print(f"preamble Tran[0]={t0} Tran[1]={t1} (sidecar: {sc_tran[0]}, {sc_tran[1]})")
|
||||
|
||||
# Block 0: 10 f8 at body[7:9]
|
||||
print(f"block 0: tag {body[7]:02x} {body[8]:02x}")
|
||||
print(f" block 0 first 10 data bytes: {body[9:19].hex()}")
|
||||
|
||||
# Walk block 0 manually, comparing each sample
|
||||
cur = t1
|
||||
samples = [t0, t1]
|
||||
block_off = 7
|
||||
nn = body[8]
|
||||
print(f" NN = {nn}")
|
||||
data = body[9 : 9 + nn // 2]
|
||||
for byi, byte in enumerate(data):
|
||||
for nib_idx, nib in enumerate(((byte >> 4) & 0xF, byte & 0xF)):
|
||||
cur += s4(nib)
|
||||
samples.append(cur)
|
||||
idx = len(samples) - 1
|
||||
if 0 <= idx < len(sc_tran):
|
||||
sc_v = sc_tran[idx]
|
||||
match = "✓" if sc_v == cur else "✗"
|
||||
if idx < 12 or 240 <= idx <= 260:
|
||||
print(f" idx {idx:3d}: nibble byte={byte:02x} nib={nib:x} delta={s4(nib):+d} cur={cur:+d} sc={sc_v:+d} {match}")
|
||||
|
||||
print(f"end of block 0: cur={cur}, len(samples)={len(samples)}, decoder expected 250 here")
|
||||
# Block 1: 20 28 starts at offset 9 + 124 = 133 from block_off=7
|
||||
block1_off = 9 + nn // 2
|
||||
print(f"block 1: tag {body[block1_off]:02x} {body[block1_off+1]:02x} (expecting 20 28)")
|
||||
nn1 = body[block1_off + 1]
|
||||
print(f" block 1 NN = {nn1}")
|
||||
data1 = body[block1_off + 2 : block1_off + 2 + nn1]
|
||||
for byi, byte in enumerate(data1):
|
||||
cur += i8(byte)
|
||||
samples.append(cur)
|
||||
idx = len(samples) - 1
|
||||
if idx < len(sc_tran):
|
||||
sc_v = sc_tran[idx]
|
||||
match = "✓" if sc_v == cur else "✗"
|
||||
if 248 <= idx <= 295:
|
||||
print(f" idx {idx:3d}: int8 byte={byte:02x} delta={i8(byte):+d} cur={cur:+d} sc={sc_v:+d} {match}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Feed candidate body offsets to the BW codec and compare with sidecar."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from minimateplus.waveform_codec import decode_waveform_v2, walk_body, find_data_start
|
||||
from analysis_idf.recon import TARGET, TXT, load_sidecar_samples
|
||||
|
||||
|
||||
def main():
|
||||
buf = TARGET.read_bytes()
|
||||
sc = load_sidecar_samples(TXT)
|
||||
# Sidecar samples in 0.0003 counts (Thor geo LSB).
|
||||
sc_tran = [int(round(v / 0.0003)) for v in sc["Tran"][:30]]
|
||||
sc_vert = [int(round(v / 0.0003)) for v in sc["Vert"][:30]]
|
||||
sc_long = [int(round(v / 0.0003)) for v in sc["Long"][:30]]
|
||||
sc_micl = [int(round(v / 1e-6)) for v in sc["MicL"][:30]] # 1 µ unit for mic? Will iterate.
|
||||
print(f"sidecar Tran (counts): {sc_tran}")
|
||||
print(f"sidecar Vert (counts): {sc_vert}")
|
||||
print(f"sidecar Long (counts): {sc_long}")
|
||||
print(f"sidecar MicL (×1e-6): {sc_micl}")
|
||||
print()
|
||||
|
||||
# Try candidate body start offsets.
|
||||
for off in (0x0f1f, 0x1057, 0x11f1, 0x1333, 0x1bde, 0x0d30):
|
||||
print(f"=== body @ 0x{off:04x} ===")
|
||||
body = buf[off:]
|
||||
decoded = decode_waveform_v2(body)
|
||||
if not decoded:
|
||||
print(" decode_waveform_v2 returned None")
|
||||
continue
|
||||
for ch in ("Tran", "Vert", "Long", "MicL"):
|
||||
arr = decoded.get(ch, [])
|
||||
print(f" {ch}[{len(arr)}]: {arr[:20]}")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Verify decode_waveform_v2 against sidecar across all 2304 samples per channel."""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from minimateplus.waveform_codec import decode_waveform_v2
|
||||
from analysis_idf.recon import TARGET, TXT, load_sidecar_samples
|
||||
|
||||
|
||||
def main():
|
||||
buf = TARGET.read_bytes()
|
||||
sc = load_sidecar_samples(TXT)
|
||||
body = buf[0x0f1f:]
|
||||
decoded = decode_waveform_v2(body)
|
||||
|
||||
print(f"Sidecar lengths: Tran={len(sc['Tran'])} Vert={len(sc['Vert'])} Long={len(sc['Long'])} MicL={len(sc['MicL'])}")
|
||||
print(f"Decoded lengths: Tran={len(decoded['Tran'])} Vert={len(decoded['Vert'])} Long={len(decoded['Long'])} MicL={len(decoded['MicL'])}")
|
||||
print()
|
||||
|
||||
GEO_LSB = 0.0003 # in/s per count
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
sc_counts = [int(round(v / GEO_LSB)) for v in sc[ch]]
|
||||
dec = decoded[ch]
|
||||
n = min(len(sc_counts), len(dec))
|
||||
matches = sum(1 for i in range(n) if sc_counts[i] == dec[i])
|
||||
first_mismatch = next((i for i in range(n) if sc_counts[i] != dec[i]), None)
|
||||
print(f"{ch}: compared {n}, exact matches {matches} ({100*matches/n:.2f}%)")
|
||||
if first_mismatch is not None:
|
||||
i = first_mismatch
|
||||
print(f" first mismatch at idx {i}: sidecar={sc_counts[i]} ({sc[ch][i]}), decoded={dec[i]}")
|
||||
print(f" context sidecar[{i-2}..{i+5}]: {sc_counts[max(0,i-2):i+5]}")
|
||||
print(f" context decoded[{i-2}..{i+5}]: {dec[max(0,i-2):i+5]}")
|
||||
|
||||
# MicL: find the multiplicative factor that fits
|
||||
print()
|
||||
print("=== MicL scale analysis ===")
|
||||
sc_micl = sc["MicL"]
|
||||
dec_micl = decoded["MicL"]
|
||||
# Skip zero values when computing ratio
|
||||
ratios = [sc_micl[i] / dec_micl[i] for i in range(min(50, len(sc_micl), len(dec_micl))) if dec_micl[i] != 0]
|
||||
if ratios:
|
||||
avg = sum(ratios) / len(ratios)
|
||||
print(f" avg ratio sidecar/decoded over first 50 nonzero: {avg:.4e} (n={len(ratios)})")
|
||||
print(f" ratios sample: {[f'{r:.4e}' for r in ratios[:6]]}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,212 @@
|
||||
> ## SUPERSEDED 2026-08-25 — the block is uniformly BIG-ENDIAN
|
||||
>
|
||||
> The `uint8` peak / `annotation` byte model described below is wrong,
|
||||
> though it decoded quiet data correctly. The real layout:
|
||||
>
|
||||
> - **Every per-channel field is `uint16` big-endian.** `T_peak` is
|
||||
> `[5:7]`, `T_halfperiod` `[7:9]`, `V_peak` `[9:11]`, and so on.
|
||||
> Only `block_ctr` at `[2:4]` is little-endian.
|
||||
> - The **marker is `block[4]` alone**, not a `uint16 LE` at `[4:6]`.
|
||||
> Testing `[4:6] == 10` forced `block[5] == 0`, which is exactly what
|
||||
> capped every geo peak at one byte (255 counts = 1.275 in/s).
|
||||
> - The **"annotation" byte was never an annotation** — it is the high
|
||||
> byte of the big-endian half-period. That is why it was non-zero
|
||||
> precisely on the sub-Hz intervals Blastware renders as `<1.0`.
|
||||
> - The **final block of the stream carries tail `9c 06 00 42`** instead
|
||||
> of `1e 0a 00 00`, and arbitrary bytes at `[21:23]`. Rejecting it
|
||||
> dropped the last interval of nearly every histogram — often the one
|
||||
> holding the event peak, so the file's PPV read low.
|
||||
>
|
||||
> Verified against 1211 production histograms paired with their Blastware
|
||||
> ASCII exports: **1211/1211 decode exactly** (interval count plus every
|
||||
> per-interval peak), and 842,442 per-interval frequency comparisons match
|
||||
> with zero mismatches. The uint8 model scored 1204/1211 — the seven
|
||||
> failures are exactly the files containing a peak above 1.275 in/s.
|
||||
>
|
||||
> The section below is retained as the reasoning trail.
|
||||
|
||||
# Histogram body codec — FULLY DECODED (2026-05-20)
|
||||
|
||||
Clean working status doc for the MiniMate Plus histogram-mode event
|
||||
body codec. Companion to `waveform_codec_re_status.md`. The deep
|
||||
historical record (with retractions and dated analyses) lives in
|
||||
`docs/instantel_protocol_reference.md §7.6.2`; the authoritative
|
||||
implementation lives in `minimateplus/histogram_codec.py`.
|
||||
|
||||
## TL;DR
|
||||
|
||||
**The codec is fully decoded.** Every field of every block in the
|
||||
in-repo histogram fixture corpus decodes byte-exact against BW's
|
||||
ASCII export.
|
||||
|
||||
26 regression tests pass against ~3,500 blocks across 5 in-repo
|
||||
fixtures, plus a synthetic regression block taken from a real
|
||||
BE9558 prod event to lock in the uint8-peak interpretation.
|
||||
|
||||
**Important correction (2026-05-21):** the per-channel peak count
|
||||
is `uint8` at byte[6]/[10]/[14]/[18], NOT `uint16 LE` at byte[6:8]
|
||||
etc. The N844 fixture corpus the original RE was done against has
|
||||
zero values in bytes [7]/[11]/[15]/[19] for every block, so the
|
||||
two interpretations happened to be equivalent. Cross-correlating
|
||||
non-N844 events (BE9558 Tran-drift, BE18003 Histogram+Continuous)
|
||||
against BW's per-interval ASCII export — 4 channels × ~1400 blocks
|
||||
per event × multiple events = 100% byte-exact only when the peak
|
||||
is read as uint8. Reading as uint16 LE produced peaks up to 268
|
||||
in/s per channel and 35× inflated PVS sums when first deployed to
|
||||
prod (rolled back, root-caused, and fixed in commit 7183b95+1).
|
||||
|
||||
## Body format
|
||||
|
||||
```
|
||||
body = [stream of 32-byte data blocks] + [small trailing remnant]
|
||||
```
|
||||
|
||||
Each block represents one histogram interval. Block layout:
|
||||
|
||||
```
|
||||
[0] 0x00 always-zero tag
|
||||
[1] segment_id (uint8) 0x00..0x03 — 256 blocks per segment
|
||||
[2:4] block_ctr (uint16 LE) resets each segment (0x0100, 0x0101, …)
|
||||
[4:6] 0x000a (uint16 LE) constant marker (= 10)
|
||||
[6] T_peak_count uint8 Tran peak (count × 0.005 → in/s at Normal,
|
||||
max 1.275 in/s — fits in uint8)
|
||||
[7] T_annotation uint8 empirically non-zero on intervals with sub-Hz
|
||||
or unmeasurable freq; meaning not fully RE'd
|
||||
[8:10] T_halfperiod uint16 LE Tran half-period in samples
|
||||
(freq_Hz = 512 / halfp; ≤ 5 means ">100 Hz")
|
||||
[10] V_peak_count uint8 Vert peak
|
||||
[11] V_annotation uint8
|
||||
[12:14] V_halfperiod uint16 LE Vert freq half-period
|
||||
[14] L_peak_count uint8 Long peak
|
||||
[15] L_annotation uint8
|
||||
[16:18] L_halfperiod uint16 LE Long freq half-period
|
||||
[18] M_peak_count uint8 MicL peak count
|
||||
(dB via waveform_codec.mic_count_to_db)
|
||||
[19] M_annotation uint8
|
||||
[20:22] M_halfperiod uint16 LE MicL freq half-period
|
||||
[22:24] 0x00 0x00 constant
|
||||
[24:28] 4-byte variable purpose unknown — possibly CRC,
|
||||
timestamp delta, or psi(L) numeric;
|
||||
not needed for waveform reconstruction
|
||||
[28:32] 0x1e 0x0a 0x00 0x00 constant block-end signature
|
||||
```
|
||||
|
||||
Reliable block-identification anchor:
|
||||
```python
|
||||
block[22:24] == b"\x00\x00" and block[28:32] == b"\x1e\x0a\x00\x00"
|
||||
```
|
||||
(The `1e 0a 00 00` constant tail is the most distinctive signature.)
|
||||
|
||||
## Per-channel encoding
|
||||
|
||||
| Channel | Peak encoding | Frequency encoding |
|
||||
|---|---|---|
|
||||
| Tran | count × 0.005 = in/s at Normal range | `freq_Hz = 512 / halfperiod` |
|
||||
| Vert | same | same |
|
||||
| Long | same | same |
|
||||
| MicL | count → dB via `mic_count_to_db(count)` (same formula as waveform codec) | same |
|
||||
|
||||
**`>100 Hz` sentinel**: when halfperiod ≤ 5 (giving ≥100 Hz from the
|
||||
512/halfp formula), BW displays `>100 Hz`. Codec's `half_period_to_hz`
|
||||
returns `None` in this range.
|
||||
|
||||
## Verified facts (cross-checked against fixture corpus)
|
||||
|
||||
Example: N844L6Z8.ZR0H block 130 → all 8 decoded fields byte-exact:
|
||||
|
||||
```
|
||||
binary samples [10, 6, 24, 4, 18, 5, 21, 5, 9]
|
||||
TXT row [0.030, 21, 0.020, 28, 0.025, 24, 0.040, 0.000, 95.92, 57]
|
||||
|
||||
slot[0] = 10 marker
|
||||
slot[1] = 6 × 0.005 = 0.030 in/s ✓ T_peak
|
||||
slot[2] = 24 → 512/24 = 21.3 → 21 Hz ✓ T_freq
|
||||
slot[3] = 4 × 0.005 = 0.020 in/s ✓ V_peak
|
||||
slot[4] = 18 → 512/18 = 28.4 → 28 Hz ✓ V_freq
|
||||
slot[5] = 5 × 0.005 = 0.025 in/s ✓ L_peak
|
||||
slot[6] = 21 → 512/21 = 24.4 → 24 Hz ✓ L_freq
|
||||
slot[7] = 5 → 81.94 + 20·log10(5) = 95.92 dB ✓ M_peak
|
||||
slot[8] = 9 → 512/9 = 56.9 → 57 Hz ✓ M_freq
|
||||
```
|
||||
|
||||
## Verified test coverage
|
||||
|
||||
`tests/test_histogram_codec.py` (24 tests):
|
||||
|
||||
- Block walking: yields one record per `.TXT` interval ± 1 (off-by-one
|
||||
at the tail when recording was stopped mid-write). Segment-ID
|
||||
groups of 256 blocks confirmed.
|
||||
- Geo peaks: every block of N844L20G, N844L6Z8, N844L6XE, N844L23B
|
||||
matches `.TXT` within the 0.0005 in/s quantization step.
|
||||
- Geo freqs: every block of N844L6Z8 and N844L6XE matches `.TXT`
|
||||
within 1 Hz (BW display rounds). `>100 Hz` sentinel handled correctly.
|
||||
- Mic dB: every block of N844L6XE, N844L23B, N844L6Z8 matches `.TXT`
|
||||
within 0.1 dB (BW display precision).
|
||||
- Mic freq: matches `.TXT` within 1 Hz across active blocks.
|
||||
|
||||
## What's NOT yet decoded
|
||||
|
||||
- **Annotation bytes (`block[7]/[11]/[15]/[19]`)**. Empirically
|
||||
non-zero on intervals where the per-channel ZC frequency comes
|
||||
out as `N/A` or sub-Hz (`<1.0`, `1.X`). Hypothesis tested in the
|
||||
RE session: byte != 0 ↔ sub-Hz freq. Only ~50% correlation
|
||||
across the K558 corpus, so the relationship is more complex.
|
||||
Possibilities: time-of-peak-within-interval, halfp extension for
|
||||
very-long-period signals, or a debug/diagnostic field the firmware
|
||||
writes opportunistically. Doesn't affect peak amplitudes or
|
||||
waveform reconstruction. Captured as `record["annotations"]` for
|
||||
future RE.
|
||||
- **4-byte variable metadata field (bytes 24:28)**. Not needed for
|
||||
waveform reconstruction. Speculation: per-block CRC, sub-second
|
||||
timestamp offset, or a Mic psi(L) count not in the 9 samples.
|
||||
Punt until something needs it.
|
||||
- **Geo PVS (TXT col 7, e.g. "0.040 in/s")**. Not stored in the
|
||||
block; can be approximated as `sqrt(T_peak² + V_peak² + L_peak²)`
|
||||
but BW's value sometimes differs slightly (probably computed from
|
||||
waveform-instant samples, not from per-channel peaks). Punt — the
|
||||
`.h5` consumers don't need PVS as a sample channel.
|
||||
- **Mic psi(L) value (TXT col 8)**. TXT shows it as a small psi value
|
||||
derived from the dB measurement. Not in the 9 samples. Could be
|
||||
derived from `M_peak_count` via the inverse of the dB formula plus
|
||||
a psi calibration constant. Defer.
|
||||
|
||||
## Output shape
|
||||
|
||||
`decode_histogram_body` returns the standard 4-channel dict that
|
||||
mirrors `waveform_codec.decode_waveform_v2`'s output:
|
||||
|
||||
```python
|
||||
{
|
||||
"Tran": [peak_count_per_interval, ...], # 16-count units (LSB = 0.005 in/s)
|
||||
"Vert": [..., ...],
|
||||
"Long": [..., ...],
|
||||
"MicL": [..., ...], # raw ADC counts
|
||||
}
|
||||
```
|
||||
|
||||
Run through `waveform_codec.decoded_to_adc_counts` to get 1-count ADC
|
||||
units (geo ×16, mic passthrough) for the standard `.h5` writer.
|
||||
|
||||
For the full per-interval record with frequencies + metadata, use
|
||||
`decode_histogram_body_full()`.
|
||||
|
||||
## Where it's wired
|
||||
|
||||
- `minimateplus/event_file_io.py:read_blastware_file()` — first tries
|
||||
the waveform codec, falls back to the histogram codec when the
|
||||
waveform preamble isn't present. Same output shape, same
|
||||
downstream pipeline.
|
||||
- `scripts/backfill_sidecars.py` — the `has_samples` short-circuit
|
||||
added during the histogram-codec-pending era still serves as a
|
||||
defensive guard against truly undecodable files, but no longer
|
||||
fires for valid histograms.
|
||||
|
||||
## Companion reference
|
||||
|
||||
- `docs/waveform_codec_re_status.md` — sibling status doc for the
|
||||
much-more-complex waveform-mode codec.
|
||||
- `docs/instantel_protocol_reference.md §7.6.2` — historical
|
||||
protocol-reference entry. Structural framing matches what we
|
||||
found; per-sample semantics were less documented than the `✅
|
||||
CONFIRMED` badge suggested. This doc supersedes §7.6.2 where they
|
||||
conflict on confidence level.
|
||||
@@ -6,11 +6,68 @@ Series IV event-file format. Sibling to
|
||||
Series III "Rosetta Stone") — this doc holds what we know so far and
|
||||
the open questions still to crack.
|
||||
|
||||
**Status (2026-05-20):** ASCII text sidecar fully decoded (1,014
|
||||
sample files round-trip). Binary `.IDFH` / `.IDFW` codec
|
||||
**not yet implemented** — binaries are stored opaquely by
|
||||
`WaveformStore.save_imported_idf`, with metadata sourced from the
|
||||
paired `.txt` sidecar.
|
||||
**Status (2026-05-28):** ASCII text sidecar fully decoded (1,014
|
||||
sample files round-trip). **Thor IDFW** binary now decodes via
|
||||
`micromate.idf_file.read_idf_file()` — reuses the BW segment-rotated
|
||||
block codec verbatim at fixed body offset `0x0f1f`; metadata (serial,
|
||||
timestamp, sample_rate, record_time, calibration_date) extracted from
|
||||
the binary header. Sample fidelity is 87–99% byte-exact on quiet
|
||||
events; loud events hit the BW codec's known walker-stops-early
|
||||
limitation. Residual ~3% drift on per-sample deltas (likely a
|
||||
Thor-specific 12-bit delta refinement not yet modelled).
|
||||
|
||||
**Thor IDFH histograms also decoded.** Body has one or more segments;
|
||||
each 12-byte segment header `[length_be 2B][0a 00 00 00][00 NN][05 3f]`
|
||||
introduces `N = (length - 10) // 72` interval records of 72 bytes
|
||||
each. Each interval = 4 × 16-byte per-channel records:
|
||||
`[int16 min][int16 max][int16 ??][uint16 halfp][2B 00][uint16 ??][2B 00][uint16 ??]`.
|
||||
Geo peak `= max(|min|, |max|) / 32768 × 10` in/s (matches sidecar
|
||||
~1.8%); freq `= 512 / halfp` Hz (None for halfp ≤ 5 → ">100"
|
||||
sentinel). Corpus: **all 859 Thor IDFH files decode, 181,071
|
||||
intervals**. Wired through `read_idf_file()` →
|
||||
`save_imported_idf()` → sidecar's `extensions.idf_intervals`.
|
||||
|
||||
**Note on the BE9439 outliers in the example corpus:** Two files
|
||||
(`BE9439_20200713131747.IDFW` and `BE9439_20200713124251.IDFH`) are
|
||||
**Series III Blastware** binaries, not Thor. Provenance: TMI tried
|
||||
to use Thor to manage auto-call-homes for Series III units; the
|
||||
experiment didn't work out, but it did leave a few BW event files
|
||||
in Thor's per-serial directory structure with `.IDFW`/`.IDFH`
|
||||
extensions — Thor's forwarder applied its own naming convention to
|
||||
the BW bodies it was relaying. Their header `10 00 01 80 00 00
|
||||
Instantel STRT ff fe <end_key> <start_key>` is the BW SUB 5A STRT
|
||||
record, not a Thor body preamble. The reader detects them by
|
||||
signature and raises `NotImplementedError` pointing callers at
|
||||
`read_blastware_file()`, which extracts BW-format peaks from them.
|
||||
|
||||
**Still NYI for Thor IDFH:** per-channel `int16 field4` (possibly
|
||||
time-of-peak); the two uint16 fields (probably PVS contributions);
|
||||
8-byte interval tail (PVS data); mic dB(L) exact conversion constant.
|
||||
|
||||
### Codec breakthroughs (2026-05-28)
|
||||
|
||||
- **Body offset is a fixed `0x0f1f`** across 151/154 corpus IDFW
|
||||
files. Preceded by a 4-byte record-type marker (`46 00 00 00`)
|
||||
+ magic preamble `00 02 00 [Tran[0] BE] [Tran[1] BE]`.
|
||||
- **Sample stream is BW's segment-rotated block codec verbatim.**
|
||||
Thor reuses `10 NN` (nibble), `20 NN` (int8), `00 NN` (RLE),
|
||||
`30 NN` (packed12), `40 02` (segment header) tags with the same
|
||||
semantics. Channel rotation Tran→Vert→Long→MicL.
|
||||
- **Geo LSB = 0.0003 in/s** (not BW's 0.005), because Thor's 16-bit
|
||||
ADC range maps to 10 in/s without the 16-count BW quantization step.
|
||||
- **Mic ≈ 2.14×10⁻⁶ psi/count** (rough scale; refine after channel
|
||||
block calibration constants are decoded).
|
||||
- **BW compliance anchor `\xbe\x80\x00\x00\x00\x00` reappears at
|
||||
IDFW offset 0x952** — sample_rate at anchor−6 (uint16 BE),
|
||||
record_time at anchor+6 (float32 BE), same layout as BW.
|
||||
- **Event timestamp at offset 0x97A** — 8 bytes `[day][month]
|
||||
[year_be][unk][hour][min][sec]`. Stop-time mirrors at 0x982.
|
||||
- **Serial as null-terminated ASCII at 0x14E**.
|
||||
- **Calibration date** at 0x194–0x197 (day, month, year_be).
|
||||
- Per-sample residual drift of ~3% suggests Thor encodes int8/nibble
|
||||
deltas with an extra refinement bit that BW doesn't carry —
|
||||
unsolved; errors resync within a few samples so cumulative impact
|
||||
is small.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
|
||||
| Date | Section | Change |
|
||||
|---|---|---|
|
||||
| 2026-08-26 | S7.6.2, S15 | **MULTI-INTERVAL HISTOGRAM BLOCKS - sub-minute intervals pack several per block.** The device always writes one minute of data per block, so a shorter histogram interval means more intervals packed into a longer block: 1 min -> 1 (the standard 32-byte block), 15 s -> 4 (stride 92), 2 s -> 30 (stride 612), with `stride = 12 + n * 20`. Each 20-byte record holds 8 x uint16 **little**-endian values (peak/half-period per channel) plus a 2-word tail whose first word is `0000` on every real interval. The standard block is big-endian - the variant is not. This recovers **415 files** (216 on BE18193 at 2 s, 199 on BE9440 at 15 s) that previously decoded to nothing, and before that were being accepted by the WAVEFORM codec and returning garbage up to 400x the device-reported PPV. |
|
||||
| 2026-08-25 (3) | S7.6.1, S15 | **THE WAVEFORM BODY IS A RECORD CHAIN, NOT A TAG STREAM — supersedes the segment-header model entirely.** Records are self-delimiting: `off+2` is a uint16 BE length and `next = off + 2 + len`; the chain ends on a record whose chan_id is `0x06`. `off+8` holds a 3-valued mode enum - `02 00` (14-byte header, anchors, cumulative deltas), `01 00` (10-byte, no anchors, ABSOLUTE values), `00 03` (10-byte, no tags at all, raw 12-bit absolute). **`40 NN` is an ordinary int16 BE data block of length 2*NN+2**, never a header; reading it as a 2*NN+16 header is what made walks drift, and the 'variable prefix' of 0/2/4/6/8 bytes reported earlier the same day was walker drift, exactly `4 - (old_stop - true_record_start)`. Verified: chain terminates on `06` in 1387/1388 files; all four channels equal length in **1388/1388** (was 156/1388); ASCII sample-count exact 72/75 -> **75/75**, fully exact 70/75 -> **73/75**; device PPV on a live decode **1306/1306** waveform (mean abs ratio error 0.00000) and **4458/4459** histogram. Also eliminated the walker-over-read class: 24 of those files were histograms the waveform codec was wrongly accepting. The superseded model is retained as `decode_waveform_legacy` because `micromate/idf_file.py` pins it for Thor IDFW body-offset search. |
|
||||
| 2026-08-25 (2) | S7.6.2, S15 | **HISTOGRAM BLOCK IS BIG-ENDIAN + terminal block tail.** The 32-byte histogram block's per-channel fields are uint16 **big-endian** (`T_peak` [5:7], `T_halfperiod` [7:9], `V_peak` [9:11], `V_halfperiod` [11:13], `L_peak` [13:15], `L_halfperiod` [15:17], `M_peak` [17:19], `M_halfperiod` [19:21]); only `block_ctr` [2:4] is little-endian. The marker is `block[4]` alone - the previous uint16 LE marker test at [4:6] forced `block[5] == 0` and thereby capped every geo peak at 255 counts (1.275 in/s), silently clipping larger peaks. The byte previously documented as a per-channel "annotation" is the high byte of the big-endian half-period, which is why it was non-zero exactly on sub-Hz intervals. Separately, the **final block of each stream carries tail `9c 06 00 42`** rather than `1e 0a 00 00` and holds arbitrary bytes at [21:23]; rejecting it dropped the last interval of nearly every histogram. Verified against 1211 production histograms paired with their Blastware ASCII exports: 1211/1211 decode exactly, plus 842,442 per-interval frequency comparisons with zero mismatches (previously 1 of 1196 files fully correct). |
|
||||
| 2026-08-25 | §7.6.1, §15, Appendix E (NEW) | **BODY CODEC + SCALE PASS — five findings, all verified against 75 production events paired with their preserved Blastware ASCII exports.** (1) **Geo full scale is 32000 ADC counts, not 32768** — one decoder unit (16 counts) is exactly 0.005 in/s, so 10.000 in/s = 32000 counts. Consumers dividing by 32768 read every geophone sample and derived peak **2.34% low**; the error scales with amplitude so it was invisible on quiet events and worst on loud ones. 216 per-channel comparisons: 32768 → 151/216 exact (worst 0.238 in/s on a 10 in/s event); 32000 → 216/216 exact, worst 1 LSB. Affects waveforms, histograms and series-4 alike. (2) **Wide-NN RLE `0X NN`** — the 12-bit NN encoding already known for `1X`/`2X` also applies to the `00 NN` RLE tag (runs > 252 samples). (3) **`30 NN` is not capped at NN=0x10** — data-section blocks reach at least 0x18; the length formula was already right. (4) **`40 NN` segment headers are variable width** — NN counts the previous-channel continuation deltas, so the header is `2*NN + 16` bytes; `40 01` and `40 03` occur alongside `40 02`. A header can also appear **tagless** (the NN=0 case): just the 14-byte tail. (5) **The header field documented as a "monotonic uint32 LE counter" is really `[channel_id][00][00][segment_index]`** with 0x46=Tran 0x47=Vert 0x48=Long 0x49=MicL — verified on 1697/1697 segment headers, zero disagreements. Decoders should take the channel from this field, not from rotation position. Items (2)–(5) each caused **silent channel truncation**: an unhandled tag ends the walk and the decoder returns short channels with no error. Corpus result end-to-end: exact 37 → 72, truncated 23 → 3, full-length value errors 15 → 0. New Appendix E documents the field-observed "offset" device fault. |
|
||||
| 2026-05-20 | §2, §3, §4.2, §5.1, §5.3, §6, §7.5b, §7.6.1, §7.6.3, §7.6.4, §7.7.2, §7.7.3, §7.7.5, §7.8.4, §7.8.7, §7.9, §8, §11, §12, §13, §14, §15, Appendix D | **DOC AUDIT PASS — accuracy sweep against `CLAUDE.md` + `minimateplus/` code.** Fixed: (1) S3 frames terminate on bare ETX, not DLE+ETX — §2/§3 rewritten. (2) §3 payload layout corrected — byte[1]=flags, byte[2]=SUB (was wrongly labelled DLE/ADDR). (3) §4.2 — probe responses do NOT carry data length; lengths are hardcoded `DATA_LENGTHS` constants. (4) §5.1 — removed stale duplicate "SUB 1C = TRIGGER CONFIG READ" row; SUB 0A lengths corrected from `0x30/0x26` to `0x46/0x2C` (real event / boundary marker). (5) §5.3 — added missing write-frame format (BW_CMD-only doubling, DLE-aware checksum, offset formula, ack format, SUB 71 chunk parameters). (6) §6 — fixed "SUB 06 → channel config read" → event storage range. (7) §7.5b / §8 — added the 10-byte `sub_code=0x03` continuous-mode timestamp variant alongside the 9-byte single-shot layout; peak vector sum location corrected from "fixed offset 87" to `tran_pos − 12` (label-relative). (8) §7.6 / §7.6.1 / §7.6.3 / §7.6.4 — switched compliance-anchor convention from the 10-byte form to the canonical 6-byte `\xbe\x80\x00\x00\x00\x00`; recording_mode confirmed at anchor−8 in BOTH read and write (was wrongly listed as anchor−3 write / anchor−4 read); sample_rate at anchor−6, histogram_interval at anchor−4, record_time at anchor+6; geo_range row added at channel_label+33. (9) §7.7.2 — token byte position corrected from `params[6]` to `params[7]`. (10) §7.8.4 — fi==9 skip marked FIXED (already removed from code); chunk-count totals updated. (11) §7.8.7 — TODO replaced with current state of `_decode_a5_metadata_into`. (12) §7.9 — Histogram Interval upgraded ❓ → ✅. (13) §11 — POLL example wire bytes corrected; SUB 5A row added to checksum table. (14) §13 — device-under-test updated for current primary unit (BE11529 / S338.17). (15) §14 — TCP Idle Timeout fixed (0→2 min); Data Forwarding Timeout units clarified. (16) §15 (renumbered from second §14) — open-question items already resolved in CLAUDE.md closed out. (17) Appendix D — extension taxonomy rewritten to reflect the AB0T timestamp encoding (D.5.2/D.5.3); EXTENSION REFUTED warning replaced with the resolved encoding. |
|
||||
| 2026-05-08 | §7.6.1 (RETRACTION) | **❌ RETRACTED — "raw int16 LE 8 bytes/sample-set" body codec was never validated.** The original 4-2-26 confirmation was based on misreading broken-decoder output (full-scale ±32K noise) as evidence the signal had saturated. BW's own 0C peaks for that capture (Tran=0.420 / Vert=3.870 / Long=0.495 in/s) prove the signal was NOT saturated — none of those exceed 13K ADC counts. No event in the project's archive has ever come close to saturation, yet the decoder consistently produces ±32K noise on every event. Conclusion: the body codec is not raw int16 LE; the actual encoding is open. Body byte distribution is heavily skewed (24% `0x00`, 10.5% `0x10`, lots of `10 XX` pairs) — likely a delta encoding with `0x10` as escape, but unverified. Retraction box added at top of §7.6.1; "fully-saturating event" claim removed from channel-identification note. The histogram codec in §7.6.2 IS verified and decoded correctly (different recording mode, 32-byte blocks); use it as a structural hint when reverse-engineering the waveform codec. |
|
||||
| 2026-02-26 | Initial | Document created from first hex dump analysis |
|
||||
@@ -1101,14 +1105,51 @@ Every block starts with a 2-byte tag. Five tag types are confirmed:
|
||||
|-----------|-------------------------------------|-----------------------|
|
||||
| ``10 NN`` | Small-delta data block | NN/2 + 2 bytes |
|
||||
| ``20 NN`` | Literal data block (int8-shaped) | NN + 2 bytes |
|
||||
| ``00 NN`` | 2-byte marker between data blocks | 2 bytes |
|
||||
| ``00 NN`` | RLE zero-delta run | 2 bytes |
|
||||
| ``30 NN`` | Trailer summary block | NN × 4 bytes |
|
||||
| ``40 02`` | Segment header | 20 bytes (fixed) |
|
||||
| ``40 NN`` | Segment header | 2 × NN + 16 bytes |
|
||||
|
||||
NN is always a multiple of 4. ``10 NN`` and ``20 NN`` data blocks
|
||||
alternate with ``00 NN`` markers — every ``10/20 NN`` block is
|
||||
followed by a ``00 NN`` marker before the next data block.
|
||||
|
||||
###### Wide-NN forms — ``0X NN`` (CONFIRMED 2026-08-25)
|
||||
|
||||
The 12-bit wide-NN encoding already documented for ``1X NN`` /
|
||||
``2X NN`` (low nibble of the tag byte carries the high nibble of NN,
|
||||
so effective ``NN = ((tag & 0x0F) << 8) | NN``) **also applies to the
|
||||
``00 NN`` RLE tag.** A narrow RLE run maxes out at NN = 0xFC, so a
|
||||
quiet stretch longer than 252 samples must use the wide form.
|
||||
|
||||
Confirmed against six production events, e.g. ``01 0c`` (NN = 268) in
|
||||
``BE9558/K558LKOF.460W``. Before this was handled, the walker hit its
|
||||
unknown-tag break at the first long quiet run and silently truncated
|
||||
every channel decoded after that point.
|
||||
|
||||
###### ``30 NN`` is not capped at NN = 0x10 (CONFIRMED 2026-08-25)
|
||||
|
||||
Data-section ``30 NN`` blocks occur with NN up to at least 0x18 (24),
|
||||
e.g. ``30 18`` in ``BE18193/T193LQ45.NN0W`` and ``30 14`` in
|
||||
``BE18193/T193LQ9W.AF0W``. The data-section length formula
|
||||
(``NN × 1.5 + 2``) holds for these; only the earlier ``NN ≤ 0x10``
|
||||
guard was wrong.
|
||||
|
||||
###### ``40 NN`` segment headers are variable width (CONFIRMED 2026-08-25)
|
||||
|
||||
``40 02`` is the common case, but **NN is the count of int16 BE
|
||||
continuation deltas the header carries for the *previous* channel**, so
|
||||
the header grows with NN and every field after the deltas shifts by
|
||||
``2 × NN``:
|
||||
|
||||
```
|
||||
length = 2 (tag) + 2 × NN (prev-channel deltas) + 14 (fixed tail)
|
||||
```
|
||||
|
||||
``40 01`` (18 bytes) and ``40 03`` (22 bytes) both occur in production
|
||||
files — see ``BE12599/N599LP1S.UO0W`` and ``BE18438/T438LO30.GA0W``.
|
||||
In each case the constant ``02 00`` marker sits at ``data[2×NN+8]`` and
|
||||
the following tag lands exactly on a valid block boundary.
|
||||
|
||||
##### Segments
|
||||
|
||||
The body is divided into segments separated by ``40 02`` segment headers.
|
||||
@@ -1129,32 +1170,179 @@ fit fewer. Observed first-segment sizes in the bundled fixtures:
|
||||
based on incomplete walks; that figure is wrong. Segments are
|
||||
flash-page-sized in bytes, not sample-count-sized.
|
||||
|
||||
The 18-byte ``40 02`` payload structure:
|
||||
The ``40 NN`` payload structure (offsets shown for the common NN=2 /
|
||||
18-byte-payload case; add ``2 × (NN − 2)`` to every offset from ``[4:6]``
|
||||
onward for other widths):
|
||||
|
||||
| Offset | Field | Status |
|
||||
|-----------|---------------------------------------------|-------------|
|
||||
| [0:2] | T_delta at first sample of new segment | ✅ confirmed|
|
||||
| | (int16 BE, in 16-count units) | |
|
||||
| [2:4] | Likely T_delta at sample seg_start+1 | 🟡 likely |
|
||||
| [4:6] | Unknown (varies; possibly a checksum) | ❓ open |
|
||||
| [6:8] | Byte length to next segment header − 2 | ✅ confirmed|
|
||||
| | (uint16 BE; useful for walker pre-scan) | |
|
||||
| [8:12] | Monotonic uint32 LE counter | ✅ confirmed|
|
||||
| | (starts ~0x47, increments by 1 per segment) | |
|
||||
| [12:14] | Constant ``02 00`` | ✅ confirmed|
|
||||
| [14:18] | Unknown 4-byte field | ❓ open |
|
||||
| Offset (NN=2) | Generic | Field | Status |
|
||||
|---------------|------------------|----------------------------------------|-------------|
|
||||
| [0:4] | [0 : 2NN] | NN × int16 BE continuation deltas for | ✅ confirmed|
|
||||
| | | the PREVIOUS channel (16-count units) | |
|
||||
| [4:6] | [2NN : 2NN+2] | Unknown (varies; possibly a checksum) | ❓ open |
|
||||
| [6:8] | [2NN+2 : 2NN+4] | Byte length to next segment header − 2 | 🟡 likely |
|
||||
| | | (uint16 BE; off by ±4 on some files) | |
|
||||
| [8:12] | [2NN+4 : 2NN+8] | Monotonic uint32 LE counter | ✅ confirmed|
|
||||
| | | (starts ~0x47, +1 per segment) | |
|
||||
| [12:14] | [2NN+8 : 2NN+10] | Constant ``02 00`` | ✅ confirmed|
|
||||
| [14:18] | [2NN+10 : 2NN+14]| THIS channel's 2-sample anchor pair | ✅ confirmed|
|
||||
| | | (2 × int16 BE) | |
|
||||
|
||||
Examples from event-c (1 sec single-shot):
|
||||
⚠️ An earlier draft listed ``[14:18]`` as an "unknown 4-byte field" and
|
||||
``[12:16]`` as a constant ``02 00 00 01``. Both were wrong: the constant
|
||||
is only the 2-byte ``02 00``, and the four bytes after it are the anchor
|
||||
pair the decoder needs. Corrected 2026-08-25.
|
||||
|
||||
###### Tagless segment headers (CONFIRMED 2026-08-25)
|
||||
|
||||
A segment header can appear with **no ``40 NN`` tag at all** — just the
|
||||
14-byte tail:
|
||||
|
||||
```
|
||||
Segment header 1 (offset 235):
|
||||
40 02 | 00 00 00 00 | 0a 4b 01 1e | 47 00 00 00 | 02 00 00 01 | 00 01
|
||||
^counter=0x47
|
||||
Segment header 2 (offset 523):
|
||||
40 02 | ff fe ff fe | 13 f5 01 06 | 48 00 00 00 | 02 00 00 01 | 00 02
|
||||
^counter=0x48 (+1)
|
||||
[field2:2][len_to_next:2][channel_id:4][marker:2][anchors:4]
|
||||
```
|
||||
|
||||
This is the NN=0 case: the previous channel needed no continuation
|
||||
deltas, so there is no tag and no delta bytes. Detect it by the six
|
||||
bytes at ``[4:10]`` — a known channel id, two zero bytes, a small
|
||||
segment index, then the ``01 00`` / ``02 00`` marker.
|
||||
|
||||
It is where the walk stopped in 7 of the 8 events that still truncated
|
||||
after the wide-RLE / ``30 NN`` / variable-width-``40 NN`` fixes.
|
||||
|
||||
###### The header "counter" is really a channel id (CONFIRMED 2026-08-25)
|
||||
|
||||
The 4-byte field previously documented as a *"monotonic uint32 LE
|
||||
counter (starts ~0x47, increments by 1 per segment)"* is actually:
|
||||
|
||||
```
|
||||
[channel_id:1][00][00][segment_index:1]
|
||||
```
|
||||
|
||||
| channel_id | channel |
|
||||
|---|---|
|
||||
| ``0x46`` | Tran |
|
||||
| ``0x47`` | Vert |
|
||||
| ``0x48`` | Long |
|
||||
| ``0x49`` | MicL |
|
||||
|
||||
Verified on **1697 of 1697** segment headers across the ground-truth
|
||||
corpus — every one agrees with the channel the rotation would assign,
|
||||
zero disagreements, no other id values observed. The old reading was
|
||||
plausible because the id byte cycles 0x46→0x47→0x48→0x49 and the
|
||||
segment index increments, which *looks* monotonic in LE.
|
||||
|
||||
Decoders should take the channel from this field rather than from
|
||||
rotation position: one missed or extra header (exactly what tagless
|
||||
headers used to cause) desyncs rotation and corrupts every channel
|
||||
after it.
|
||||
|
||||
###### Geophone full scale is 32000 counts, not 32768 (CONFIRMED 2026-08-25)
|
||||
|
||||
The body codec emits geo samples in 16-count units whose LSB is exactly
|
||||
**0.005 in/s**. With the consumer-side ``×16`` to ADC counts, one ADC
|
||||
count is ``0.005 / 16`` in/s, so Normal range (10.000 in/s) is
|
||||
|
||||
```
|
||||
10.0 / (0.005 / 16) = 32000 counts
|
||||
```
|
||||
|
||||
Dividing by 32768 scales every geophone sample and every derived peak
|
||||
down by ``1 - 32000/32768`` = **2.34%**. Measured on 216 per-channel
|
||||
comparisons against preserved Blastware ASCII exports: 32768 gave
|
||||
151/216 exact (worst error 0.238 in/s on a 10 in/s event); 32000 gives
|
||||
216/216 exact with a worst error of 0.005 in/s — exactly 1 LSB, i.e.
|
||||
pure quantization.
|
||||
|
||||
This also explains why Blastware reports geo peaks slightly above
|
||||
nominal full scale (e.g. 10.14 in/s): the ADC has headroom past 32000.
|
||||
|
||||
**Scope — this is not waveform-specific.** The scale is applied where
|
||||
ADC counts become physical units, which every event passes through
|
||||
regardless of which codec produced the samples. Verified after
|
||||
re-deriving the whole production store:
|
||||
|
||||
| source | median ratio ours/device, 32768 | with 32000 |
|
||||
|---|---|---|
|
||||
| series-3 waveform (vs ASCII sample table) | 0.9766 | **1.0000** |
|
||||
| series-3 histogram (vs ASCII PPV, n=1137) | 0.9766 | **1.0000** |
|
||||
| series-4 Thor IDF (vs device peak, n=1468) | 0.960 | **0.983** |
|
||||
|
||||
The series-4 figure is closer to correct but not exact — the Thor
|
||||
per-count LSB is its own open question (see §15).
|
||||
|
||||
###### SUPERSEDED 2026-08-25 — the body is a RECORD CHAIN, not a tag stream
|
||||
|
||||
Everything above about ``40 NN`` segment headers, tagless headers, variable
|
||||
header widths and channel rotation describes a model that is **wrong**. It
|
||||
produced nearly-correct output because the block table happens to tile the
|
||||
data sections correctly, but the framing is not what the device writes.
|
||||
|
||||
The body is a chain of **self-delimiting per-channel records**:
|
||||
|
||||
```
|
||||
off+0 field2 uint16 purpose unknown (not a length, not a checksum)
|
||||
off+2 len uint16 BE next_record = off + 2 + len <- authoritative
|
||||
off+4 chan_id 0x46 Tran / 0x47 Vert / 0x48 Long / 0x49 MicL
|
||||
0x06 = END OF WAVEFORM STREAM
|
||||
off+5 0x00
|
||||
off+6 0x00
|
||||
off+7 segment index
|
||||
off+8 mode 2 bytes, a 3-valued enum
|
||||
off+10 anchors 2 x int16 BE, ABSOLUTE -- present ONLY when mode == 02 00
|
||||
```
|
||||
|
||||
**Mode enum**, all three ground-truth verified:
|
||||
|
||||
| mode | header | data section |
|
||||
|---|---|---|
|
||||
| ``02 00`` | 14 bytes | anchors emitted, then blocks are **cumulative deltas** |
|
||||
| ``01 00`` | 10 bytes | no anchors, blocks carry **absolute** sample values |
|
||||
| ``00 03`` | 10 bytes | **no tags at all** — raw 12-bit packed absolute samples |
|
||||
|
||||
Census over the 1,388 production series-3 waveform binaries:
|
||||
``02 00`` x 32,617, ``01 00`` x 74, ``00 03`` x 71.
|
||||
|
||||
**``40 NN`` is an ordinary int16 BE data block** of length ``2*NN + 2``
|
||||
(1 <= NN <= 8), never a header. The superseded model read it as a header of
|
||||
length ``2*NN + 16``, which is exactly why walks drifted: the "variable prefix"
|
||||
of 0/2/4/6/8 bytes reported earlier was walker drift, precisely
|
||||
``4 - (old_stop - true_record_start)``, on all 25 affected files.
|
||||
|
||||
Block table for data sections (``NN = ((tag_hi & 0x0F) << 8) | tag_lo``):
|
||||
|
||||
| tag | length | samples |
|
||||
|---|---|---|
|
||||
| ``0X NN`` | 2 | NN (RLE hold — holds the previous value in BOTH delta and absolute modes) |
|
||||
| ``1X NN`` | NN/2 + 2 | NN (4-bit nibble) |
|
||||
| ``2X NN`` | NN + 2 | NN (int8) |
|
||||
| ``30 NN`` | NN*1.5 + 2 | NN (12-bit packed) |
|
||||
| ``40 NN`` | 2*NN + 2 | NN (int16 BE) |
|
||||
|
||||
The ``30 NN`` "trailer length = NN*4" fallback must NOT be applied inside a
|
||||
record — it corrupts records whose ``30 NN`` sits near a boundary.
|
||||
|
||||
**The preamble is segment 0's implicit Tran record.** ``body[1:3]`` carries
|
||||
the same mode pair: ``00 02 00`` (1,387 of 1,388 files) means two int16 BE
|
||||
anchors at ``body[3:7]`` then delta blocks; ``00 00 03`` (1 file,
|
||||
``BE13121/O121L4L1.KF0W``) means raw 12-bit absolute from ``body[3]``, which
|
||||
cannot be block-walked — the first record must be located by scanning.
|
||||
|
||||
**Verification.** The length chain terminates on a ``0x06`` record in 1,387 of
|
||||
1,388 files (the exception has an ambiguous footer signature inside its sample
|
||||
stream). All four channels come out at identical length in **1,388/1,388**,
|
||||
against 156/1,388 under the superseded model. Against the 75 events with a
|
||||
preserved Blastware ASCII export: sample-count exact **72/75 -> 75/75**, fully
|
||||
exact **70/75 -> 73/75** (the 2 remaining differ by exactly 1 LSB on samples
|
||||
sitting at the +-10.000 in/s rail). Against device-reported PPVs on a live
|
||||
decode: waveform **1306/1306** exact with mean absolute ratio error 0.00000;
|
||||
histogram **4458/4459**.
|
||||
|
||||
This also eliminated the walker-over-read class entirely. 24 of those 35
|
||||
"histogram" over-reads were histogram files that ``read_blastware_file`` fed to
|
||||
the *waveform* codec first; the old walker accepted them and returned garbage
|
||||
(one produced 98,923 "intervals"), while the record-chain decoder correctly
|
||||
returns None so they fall through to ``histogram_codec``.
|
||||
|
||||
##### Trailer
|
||||
|
||||
The trailer (after the last segment's data) is a sequence of 32-byte
|
||||
@@ -2867,7 +3055,7 @@ The `.bin` files produced by `s3_bridge` are **not raw wire bytes**. The logger
|
||||
|---|---|---|---|
|
||||
| Timestamp 6-byte format byte[3] — purpose of the separator `0x00` byte | LOW | 2026-02-26 | Not blocking; 9-byte waveform record format (§8.2) fully confirmed without this byte. |
|
||||
| `trail[0]` in serial number response — unit-specific byte, derivation unknown. `trail[1]` resolved as firmware minor version. | MEDIUM | 2026-02-26 | |
|
||||
| Full channel ID mapping in SUB `5A` stream (01/02/03/04 → which sensor?) | MEDIUM | 2026-02-26 | |
|
||||
| ~~Full channel ID mapping in SUB `5A` stream~~ — **RESOLVED 2026-08-25 for the waveform body:** every `40 NN` segment header carries `[channel_id][00][00][segment_index]` at `data[2*NN+4]`, with `0x46`=Tran `0x47`=Vert `0x48`=Long `0x49`=MicL. Verified on 1697/1697 segment headers with zero disagreements against the decoded channel rotation. See §7.6.1. | RESOLVED | 2026-02-26 | Resolved 2026-08-25 |
|
||||
| ~~Exact byte boundaries of project string fields in SUB `71` write frame~~ — **RESOLVED 2026-05-05:** project/client/operator/seis-loc/extended-notes come from SUB 5A metadata pages at counter `0x1002` / `0x1004` (§7.8.7), NOT from the SUB 71 write payload. `_decode_a5_metadata_into` locates them via ASCII label scans. | RESOLVED | 2026-02-26 | Resolved 2026-05-05 |
|
||||
| Purpose of SUB `09` / response `F6` — 202-byte read block | MEDIUM | 2026-02-26 | |
|
||||
| Purpose of SUB `2E` / response `D1` — 26-byte read block | MEDIUM | 2026-02-26 | |
|
||||
@@ -2894,6 +3082,11 @@ The `.bin` files produced by `s3_bridge` are **not raw wire bytes**. The logger
|
||||
| **ACH inbound server — RESOLVED.** `bridges/ach_server.py` implements full inbound ACH pipeline. `--clear-after-download` flag for delete-after-upload workflow. Post-erase key-reuse detection via `max_downloaded_key` high-water mark. | RESOLVED | 2026-04-11 | |
|
||||
| **Sensor Check dropdown byte location** — byte offset in 1A compliance config payload for the "Sensor Check: Before monitoring / After each event / Disabled" setting is NOT YET LOCATED. Confirmed: unit always runs with "Before monitoring" set. Need a capture with "Disabled" to diff. | MEDIUM | 2026-04-08 | Still open |
|
||||
| **RV55 DCD/DTR default** — newer Sierra Wireless RV55 firmware does not assert DCD/DTR by default, so the MiniMate Plus never detects TCP disconnect and stays idle instead of resuming monitoring. Root cause: RV55 ACEmanager `DCD Control` setting. Workaround not yet found. | MEDIUM | 2026-04-11 | Still open |
|
||||
| ~~**Variable-prefix segment descriptors**~~ - **RESOLVED 2026-08-25:** there is no variable prefix. The body is a chain of self-delimiting records (see S7.6.1); the 0/2/4/6/8-byte prefix was walker drift from reading `40 NN` as a segment header. All 25 affected files now chain cleanly to the `06` terminator. | RESOLVED | 2026-08-25 | Resolved 2026-08-25 |
|
||||
| ~~**Histogram codec drops trailing intervals (series-3)**~~ - **RESOLVED 2026-08-25.** Two errors, both in the block model. (1) The block is **uniformly big-endian**: peaks and half-periods are uint16 BE (`T_peak` [5:7], `T_halfperiod` [7:9], `V_peak` [9:11], ...); only `block_ctr` [2:4] is LE. The old uint8-peak + "annotation"-byte model silently clipped any peak above 1.275 in/s, and the "annotation" byte was really the half-period high byte - non-zero exactly on the sub-Hz intervals BW renders `<1.0`. The marker is `block[4]` alone; testing [4:6] as a uint16 LE marker forced `block[5] == 0`, which is what capped the peak at one byte. (2) The **final block of the stream carries tail `9c 06 00 42`** instead of `1e 0a 00 00`, with arbitrary bytes at [21:23]; rejecting it dropped the last interval of nearly every histogram - often the one holding the event peak. Verified on 1211 production histograms vs their BW ASCII exports: **1211/1211 exact** (interval count + every per-interval peak) and 842,442 frequency comparisons with zero mismatches; was 1/1196. | RESOLVED | 2026-08-25 | Resolved 2026-08-25 |
|
||||
| ~~**Unmapped histogram block variant (415 files, 2 units)**~~ - **RESOLVED 2026-08-26.** When the histogram interval is SHORTER than one minute the device packs several intervals into a single block so each block still covers exactly one minute: 1 min -> 1 interval (the standard 32-byte block), 15 s -> 4 (stride 92), 2 s -> 30 (stride 612). `stride = 12 + n * 20`. Block is `[00][segment][ctr uint16 LE][0a][00]` then n x 20-byte records of 8 x uint16 **LITTLE**-endian `T_peak,T_halfp,V_peak,V_halfp,L_peak,L_halfp,M_peak,M_halfp` plus a 2-word tail whose first word is `0000` on every real interval (a session ending mid-block leaves buffer garbage in the remaining slots), then a 6-byte block trailer. **Note the endianness flip** - the standard 32-byte block is big-endian. Ground truth `BE9440/K440L3AQ.T70H` (5,710 intervals at 15 s) decodes with 17,130/17,130 geo peaks, 22,840/22,840 frequencies and 5,710/5,710 mic dB(L) matching its Blastware ASCII export exactly; across all 455 affected files 1,354/1,365 channel peaks (99.2%) match the device-reported PPV. | RESOLVED | 2026-08-25 | Resolved 2026-08-26 |
|
||||
| **Micromate (UM-series) IDF decode is ~1000x low** — e.g. `UM11402_20260406130113.IDFW` decodes a Tran peak of 0.0009 in/s against a device-reported 1.1168. Distinct from the Thor IDF path, which decodes sanely. Suspect a different per-count LSB or a body offset that does not hold for UM-series files. | MEDIUM | 2026-08-25 | Still open |
|
||||
| **Thor IDF per-count LSB** — after the 32000 geo full-scale correction, series-4 Thor peaks sit at a median 0.983 of the device-reported peak (was 0.960 under 32768). Closer, but the residual ~1.7% suggests Thor uses its own per-count LSB rather than the BW 16-count/0.005 in/s convention. A code comment in `sfm/waveform_store.py` claims Thor's LSB is 0.0003 in/s, which would predict Thor reading *high* — the measurement shows the opposite, so that comment is unverified. | LOW | 2026-08-25 | Still open |
|
||||
|
||||
---
|
||||
|
||||
@@ -3319,4 +3512,137 @@ file[anc−3]: histogram_interval_LO
|
||||
|
||||
*All findings reverse-engineered from live RS-232 bridge captures.*
|
||||
*Cross-referenced from 2026-03-02 with Instantel MiniMate Plus Operator Manual (716U0101 Rev 15).*
|
||||
*This is a living document — append changelog entries and timestamps as new findings are confirmed or corrected.*
|
||||
*This is a living document — append changelog entries and timestamps as new findings are confirmed or corrected.*
|
||||
|
||||
---
|
||||
|
||||
## Appendix E — Known Device Faults (field-observed, 2026-08-25)
|
||||
|
||||
This appendix records *device* behaviour, not protocol. It exists
|
||||
because these signatures are easy to mistake for decoder bugs — and one
|
||||
of them was, for a while.
|
||||
|
||||
### E.1 The "offset" fault
|
||||
|
||||
**Symptom.** One geophone channel's baseline steps away from zero and
|
||||
stays there. The trace still carries the real AC signal, but it rides
|
||||
on a DC pedestal of a few tenths of an in/s. Operators call this an
|
||||
"offset"; it is a known recurring hardware fault, historically resolved
|
||||
by returning the unit to Instantel, shelving it until calibration, or a
|
||||
per-channel re-zero in an advanced/professional Blastware build.
|
||||
|
||||
**Why it floods the queue.** The pedestal exceeds the unit's own geo
|
||||
trigger level, so the channel sits permanently above threshold and the
|
||||
unit retriggers as fast as it can rearm — one event every 3–7 minutes
|
||||
for as long as the fault persists. In the surveyed snapshot the worst
|
||||
episode produced 193 events in 38 hours.
|
||||
|
||||
| unit | window | events | channel | pedestal | that unit's trigger level |
|
||||
|---|---|---|---|---|---|
|
||||
| BE9558 | 2026-05-15 → 05-16 | 193 | Long | +0.335 | 0.200 |
|
||||
| BE18438 | 2026-02-25 → 02-26 | 64 | Vert | +0.327 | 0.200 |
|
||||
| BE18438 | 2025-11-15 | 12 | Vert | +0.312 | 0.200 |
|
||||
| BE9558 | 2026-04-14 / 04-29 / 05-04 | 5 total | Tran | +0.29…+0.44 | 0.200 |
|
||||
|
||||
**It is NOT a decode artifact.** These events reproduce *exactly* in
|
||||
Blastware's own ASCII export — e.g. `BE12599/N599LQD7.8E0W` Tran reads
|
||||
mean +0.345, min +0.335, max +0.355 in both our decode and BW's. Any
|
||||
shape-based false-trigger detector must treat this as a real device
|
||||
condition, not corrupt data.
|
||||
|
||||
**Detection rule that works:**
|
||||
|
||||
```
|
||||
dominant geo axis: |mean| / peak > 0.7
|
||||
AND: |mean| >= 0.9 x that unit's geo trigger level
|
||||
group hits into episodes by serial with a 12 h gap
|
||||
```
|
||||
|
||||
A bare `|mean|/peak` threshold is useless — a quiet trace sitting at the
|
||||
0.010 in/s noise floor clears any ratio test. On the surveyed store the
|
||||
bare rule flagged 7,184 events; the rule above flags 274, all real.
|
||||
Candidate list: `scratch/offset_candidates.csv`.
|
||||
|
||||
**What the data rules out.**
|
||||
|
||||
- *Not the geophone.* The on-device sensor check passes on every unit,
|
||||
offset or not — test frequency 7.2–8.1 Hz, damping ratio 3.3–4.7,
|
||||
zero failures fleet-wide, including mid-episode. The coil and its
|
||||
mechanical response are healthy.
|
||||
- *Not the battery.* 6.6–6.8 V on the affected units, same as the rest.
|
||||
- *Not environmental.* Only 2 units of 21 ever show it. BE17353 logged
|
||||
395 waveform events over nine months with zero occurrences; BE7145,
|
||||
295 events, zero. Weather acts on all of them equally.
|
||||
- *Not condensation.* BE18438's Vert held 0.179 → 0.189 for 34 hours
|
||||
**including a 10-hour overnight gap**, then stepped to 0.33 at 13:24
|
||||
in the afternoon. Dew would peak overnight; it was flat overnight.
|
||||
|
||||
**What the data shows.** The pedestal is *piecewise constant* — it
|
||||
holds rock-steady, survives power-off gaps, and changes only in discrete
|
||||
steps. A small common-mode diurnal wobble rides on top of it, but that
|
||||
wobble is present on the healthy channels too (it is the unit's normal
|
||||
thermal breathing) and is not the fault.
|
||||
|
||||
**The fault is on the geophone side.** Operator report (2026-08-25):
|
||||
*attaching a different geophone to an affected unit makes the offset go
|
||||
away.* That is the channel-swap test, already run in the field many
|
||||
times, and it rules out the unit's analog front-end and any stored
|
||||
per-channel zero constant — a constant lives in the unit and would
|
||||
survive a sensor swap.
|
||||
|
||||
The stored data agrees. MicL — a separate transducer on its own cable —
|
||||
shows no offset during either episode (`|mean|/peak` = 0.17 and 0.02),
|
||||
while the geo channels on the same unit at the same moment are pinned.
|
||||
|
||||
**Two distinct failure patterns**, both geophone-side:
|
||||
|
||||
| unit | Tran | Vert | Long | MicL | reading |
|
||||
|---|---|---|---|---|---|
|
||||
| BE18438 | 0.16 | **0.97** | 0.18 | 0.02 | one element only |
|
||||
| BE9558 | 0.90 | 0.81 | **0.99** | 0.17 | all three, Long dominant |
|
||||
|
||||
(values are `\|mean\|/peak` on the dominant axis)
|
||||
|
||||
BE18438 has a single faulted conductor pair with the other two clean.
|
||||
BE9558 has all three geo channels offset by different amounts
|
||||
(Long +0.340, Tran +0.037, Vert −0.020) — that points at a shared return
|
||||
or ground path in the housing rather than one element.
|
||||
|
||||
**Candidate mechanisms.** A geophone coil is passive and cannot
|
||||
generate sustained DC on its own, so an offset originating on the sensor
|
||||
side has to come from one of:
|
||||
|
||||
1. *Galvanic corrosion at a connector or splice* — dissimilar metals
|
||||
plus moisture form a literal cell. This generates DC directly, in
|
||||
the tens-of-millivolts range that matches the measured offset
|
||||
(0.29 in/s ÷ 6.206053 in/s per volt ≈ 46 mV referred to the ADC
|
||||
input). Fits the discrete steps, surviving power cycles, and being
|
||||
cured by swapping the sensor.
|
||||
2. *A leakage path to shield or another conductor*, letting the unit's
|
||||
own bias/reference divide into the signal pair. Best fit for the
|
||||
BE9558 all-three-channels pattern.
|
||||
3. *Changed coil DC resistance* (partial short or degraded winding)
|
||||
interacting with the amplifier's input bias current —
|
||||
`V_offset = I_bias × R_source`. Best fit for the BE18438
|
||||
single-element pattern. Note the on-device sensor check would not
|
||||
catch this: it measures ring-down frequency and damping, not DC.
|
||||
|
||||
**Caveat on the swap test.** Swapping a geophone requires stopping and
|
||||
restarting monitoring, and these units run Sensor Check "Before
|
||||
monitoring" — so the restart also re-zeros the channels. The swap
|
||||
therefore does not cleanly separate *"new sensor"* from *"the restart
|
||||
re-zeroed it"*. Two cheap controls settle it: restart monitoring
|
||||
**without** swapping (if the offset clears, it was the re-zero), or swap
|
||||
the **original** sensor back (if the offset returns, it is the sensor).
|
||||
The operator's remedy being a swap rather than a restart is weak
|
||||
evidence for the sensor, since a restart is the easier thing to try
|
||||
first.
|
||||
|
||||
**Best single measurement when it recurs:** DC voltage across the
|
||||
suspect geophone's connector pins with the sensor **disconnected from
|
||||
the unit**. A galvanic cell (mechanism 1) shows an open-circuit
|
||||
voltage; mechanisms 2 and 3 do not.
|
||||
|
||||
**Note:** the surveyed population is subject to survivorship bias —
|
||||
flooded events were routinely deleted before this snapshot, so units
|
||||
that look clean here may have had episodes that were scrubbed.
|
||||
@@ -0,0 +1,628 @@
|
||||
# Waveform-shape FT detection — Phase A (seismo-relay) Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Compute per-event waveform-shape metrics (crest factor + points-near-peak) in SFM and store them as `events` columns, populated at ingest and by a backfill script, so Terra-View can read them from `/db/events`.
|
||||
|
||||
**Architecture:** A pure DSP module (`sfm/shape_metrics.py`) turns decoded `.h5` samples into shape metrics. New nullable `events.shape_*` columns are added via the existing `_migrate` ADD COLUMN loop. The three `WaveformStore.save*` paths compute shape from the just-written `.h5` and hand it to `insert_events`; a backfill script does the same over existing events. Mirrors exactly how per-channel ZC frequency was added.
|
||||
|
||||
**Tech Stack:** Python 3.10, numpy, h5py, sqlite3 (raw), pytest. seismo-relay venv: `/home/serversdown/seismo-relay/.venv/bin/python3`.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Metrics are read from the `.h5` `samples/{Tran,Vert,Long}` float32 arrays (physical in/s). The measured channel is the max-|peak| geophone channel.
|
||||
- All new columns are nullable; histogram records and events without usable samples store NULL (Terra-View falls back to cheap signals). Legacy rows stay valid.
|
||||
- Crest factor = `max(|x|) / rms(x)`; near-peak count = number of samples with `|x| ≥ 0.5·peak`. Threshold `0.5` is a module constant so calibration can tune it.
|
||||
- No manual migration: columns are added in `SeismoDb._migrate`, run at `SeismoDb()` construction.
|
||||
- `/db/events` needs no change — it returns all columns via `SELECT *` (verify with a test).
|
||||
- Run tests with `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Shape DSP module
|
||||
|
||||
**Files:**
|
||||
- Create: `sfm/shape_metrics.py`
|
||||
- Test: `tests/test_shape_metrics.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `channel_shape(x) -> dict | None` — `{"crest_factor": float, "near_peak_count": int, "sample_count": int}` or None for unusable input (size < 2, flat, all-zero).
|
||||
- `shape_from_samples(chans: dict[str, ArrayLike]) -> dict | None` — picks the max-peak geophone channel; returns `{"crest_factor","near_peak_count","sample_count","axis"}` or None.
|
||||
- `shape_from_h5(path) -> dict | None` — reads `samples/{Tran,Vert,Long}` and delegates to `shape_from_samples`; None on any read error.
|
||||
- Constant `NEAR_PEAK_FRACTION = 0.5`.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# tests/test_shape_metrics.py
|
||||
import numpy as np
|
||||
from sfm.shape_metrics import channel_shape, shape_from_samples
|
||||
|
||||
def test_needle_spike_high_crest_few_near_peak():
|
||||
x = np.zeros(1024); x[500] = 1.0 # one isolated spike
|
||||
s = channel_shape(x)
|
||||
assert s["sample_count"] == 1024
|
||||
assert s["crest_factor"] > 15 # peak towers over rms
|
||||
assert s["near_peak_count"] <= 3 # almost nothing near the peak
|
||||
|
||||
def test_ringing_low_crest_many_near_peak():
|
||||
t = np.arange(1024)
|
||||
x = np.sin(2*np.pi*t/32) * np.exp(-t/4000) # decaying oscillation
|
||||
s = channel_shape(x)
|
||||
assert s["crest_factor"] < 6
|
||||
assert s["near_peak_count"] > 30 # many samples near the peak
|
||||
|
||||
def test_channel_shape_none_for_unusable():
|
||||
assert channel_shape(np.zeros(1024)) is None # flat / all-zero
|
||||
assert channel_shape(np.array([1.0])) is None # too short
|
||||
|
||||
def test_shape_from_samples_picks_max_peak_axis():
|
||||
chans = {"Tran": np.zeros(1024), "Vert": np.zeros(1024), "Long": np.zeros(1024)}
|
||||
chans["Long"][10] = 0.5
|
||||
chans["Vert"] = np.sin(np.arange(1024)/5) * 0.01
|
||||
s = shape_from_samples(chans)
|
||||
assert s["axis"] == "Long" # Long has the biggest peak
|
||||
assert s["near_peak_count"] <= 3
|
||||
|
||||
def test_shape_from_samples_none_when_no_geo():
|
||||
assert shape_from_samples({"MicL": np.ones(1024)}) is None
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_shape_metrics.py -q`
|
||||
Expected: FAIL — `ModuleNotFoundError: sfm.shape_metrics`.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
```python
|
||||
# sfm/shape_metrics.py
|
||||
"""Waveform-shape metrics for false-trigger detection.
|
||||
|
||||
A false trigger is an isolated impulse (quiet → spike → quiet); a real event
|
||||
rings for many cycles. Two numbers separate them: crest factor (how far the
|
||||
peak stands above the typical sample) and how many samples sit near the peak.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import numpy as np
|
||||
|
||||
_GEO_CHANNELS = ("Tran", "Vert", "Long")
|
||||
NEAR_PEAK_FRACTION = 0.5 # a sample "near the peak" is >= this * peak amplitude
|
||||
|
||||
|
||||
def channel_shape(x) -> dict | None:
|
||||
x = np.asarray(x, dtype=float)
|
||||
if x.size < 2:
|
||||
return None
|
||||
peak = float(np.max(np.abs(x)))
|
||||
if peak <= 0:
|
||||
return None
|
||||
rms = float(np.sqrt(np.mean(x ** 2)))
|
||||
if rms <= 0:
|
||||
return None
|
||||
near = int(np.sum(np.abs(x) >= NEAR_PEAK_FRACTION * peak))
|
||||
return {"crest_factor": peak / rms, "near_peak_count": near,
|
||||
"sample_count": int(x.size)}
|
||||
|
||||
|
||||
def shape_from_samples(chans: dict) -> dict | None:
|
||||
best_axis, best_peak, best_x = None, -1.0, None
|
||||
for ax in _GEO_CHANNELS:
|
||||
x = chans.get(ax)
|
||||
if x is None:
|
||||
continue
|
||||
x = np.asarray(x, dtype=float)
|
||||
if x.size < 2:
|
||||
continue
|
||||
p = float(np.max(np.abs(x)))
|
||||
if p > best_peak:
|
||||
best_axis, best_peak, best_x = ax, p, x
|
||||
if best_axis is None:
|
||||
return None
|
||||
s = channel_shape(best_x)
|
||||
if s is None:
|
||||
return None
|
||||
s["axis"] = best_axis
|
||||
return s
|
||||
|
||||
|
||||
def shape_from_h5(path) -> dict | None:
|
||||
import h5py
|
||||
try:
|
||||
with h5py.File(path, "r") as f:
|
||||
chans = {ax: f[f"samples/{ax}"][:] for ax in _GEO_CHANNELS
|
||||
if f"samples/{ax}" in f}
|
||||
except Exception:
|
||||
return None
|
||||
return shape_from_samples(chans)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_shape_metrics.py -q`
|
||||
Expected: PASS (5 tests).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add sfm/shape_metrics.py tests/test_shape_metrics.py
|
||||
git commit -m "feat(shape): crest-factor + points-near-peak waveform metrics"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: shape_from_h5 round-trips a real .h5
|
||||
|
||||
**Files:**
|
||||
- Test: `tests/test_shape_metrics_h5.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `sfm.shape_metrics.shape_from_h5`; `h5py`.
|
||||
|
||||
- [ ] **Step 1: Write the failing test** (writes a tiny .h5 the same shape SFM writes, then reads it back)
|
||||
|
||||
```python
|
||||
# tests/test_shape_metrics_h5.py
|
||||
import numpy as np, h5py
|
||||
from sfm.shape_metrics import shape_from_h5
|
||||
|
||||
def _write_h5(path, chans):
|
||||
with h5py.File(path, "w") as f:
|
||||
g = f.create_group("samples")
|
||||
for k, v in chans.items():
|
||||
g.create_dataset(k, data=np.asarray(v, dtype="float32"))
|
||||
|
||||
def test_shape_from_h5_reads_dominant_axis(tmp_path):
|
||||
p = tmp_path / "ev.h5"
|
||||
long = np.zeros(1024, dtype="float32"); long[100] = 0.48
|
||||
_write_h5(p, {"Tran": np.zeros(1024), "Vert": np.zeros(1024), "Long": long,
|
||||
"MicL": np.ones(1024)})
|
||||
s = shape_from_h5(str(p))
|
||||
assert s["axis"] == "Long" and s["near_peak_count"] <= 3
|
||||
|
||||
def test_shape_from_h5_none_on_missing_or_degenerate(tmp_path):
|
||||
assert shape_from_h5(str(tmp_path / "nope.h5")) is None
|
||||
p = tmp_path / "degen.h5"
|
||||
_write_h5(p, {"Tran": np.zeros(1), "Vert": np.zeros(1), "Long": np.zeros(1)})
|
||||
assert shape_from_h5(str(p)) is None
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_shape_metrics_h5.py -q`
|
||||
Expected: FAIL (assertion or, if Task 1 incomplete, import error).
|
||||
|
||||
- [ ] **Step 3: Implementation** — none needed; `shape_from_h5` already exists from Task 1. If a test fails, fix `shape_from_h5` (not the test).
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_shape_metrics_h5.py -q`
|
||||
Expected: PASS (2 tests).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/test_shape_metrics_h5.py
|
||||
git commit -m "test(shape): shape_from_h5 round-trips a real .h5"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Add shape columns to the events schema + migration
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/database.py` — `_SCHEMA` CREATE TABLE `events` (after `mic_zc_above_range`); `_migrate` ADD COLUMN loop (the tuple around line 205-218).
|
||||
- Test: `tests/test_shape_columns.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `events` columns `shape_crest_factor REAL`, `shape_near_peak_count INTEGER`, `shape_sample_count INTEGER`, `shape_axis TEXT`.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# tests/test_shape_columns.py
|
||||
import sqlite3
|
||||
from sfm.database import SeismoDb
|
||||
|
||||
_SHAPE_COLS = {"shape_crest_factor", "shape_near_peak_count",
|
||||
"shape_sample_count", "shape_axis"}
|
||||
|
||||
def _cols(db):
|
||||
with sqlite3.connect(db.db_path) as c:
|
||||
return {r[1] for r in c.execute("PRAGMA table_info(events)")}
|
||||
|
||||
def test_fresh_db_has_shape_columns(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
assert _SHAPE_COLS <= _cols(db)
|
||||
|
||||
def test_existing_db_migrates_shape_columns(tmp_path):
|
||||
p = tmp_path / "s.db"
|
||||
db = SeismoDb(p)
|
||||
with sqlite3.connect(p) as c: # simulate an older DB missing the columns
|
||||
for col in _SHAPE_COLS:
|
||||
c.execute(f"ALTER TABLE events DROP COLUMN {col}")
|
||||
assert not (_SHAPE_COLS <= _cols(SeismoDb(p))) # sanity: dropped
|
||||
SeismoDb(p) # re-open triggers _migrate
|
||||
assert _SHAPE_COLS <= _cols(SeismoDb(p))
|
||||
```
|
||||
|
||||
> Note: sqlite `DROP COLUMN` needs sqlite ≥ 3.35 (bundled py3.10 has it). If the runner's sqlite lacks it, replace the "simulate older DB" block with building a table without the columns; keep the assertion that re-open adds them.
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_shape_columns.py -q`
|
||||
Expected: FAIL — columns absent.
|
||||
|
||||
- [ ] **Step 3: Implementation**
|
||||
|
||||
In `_SCHEMA`, after the `mic_zc_above_range INTEGER,` line in the `events` CREATE TABLE, add:
|
||||
|
||||
```
|
||||
shape_crest_factor REAL, -- peak / rms of the triggering channel
|
||||
shape_near_peak_count INTEGER, -- samples >= 0.5 * peak (FT: few; real: many)
|
||||
shape_sample_count INTEGER, -- total samples (to normalize near_peak_count)
|
||||
shape_axis TEXT, -- geophone channel measured ("Tran"/"Vert"/"Long")
|
||||
```
|
||||
|
||||
In `_migrate`, extend the ADD COLUMN tuple (the `for col, ddl in (...)` list) with:
|
||||
|
||||
```python
|
||||
("shape_crest_factor", "REAL"),
|
||||
("shape_near_peak_count", "INTEGER"),
|
||||
("shape_sample_count", "INTEGER"),
|
||||
("shape_axis", "TEXT"),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_shape_columns.py -q`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add sfm/database.py tests/test_shape_columns.py
|
||||
git commit -m "feat(db): shape_* columns on events (+ auto-migrate)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: insert_events persists shape from the waveform record
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/database.py` — `insert_events` INSERT (column list + placeholders + values) and the UPSERT `UPDATE` block.
|
||||
- Test: `tests/test_insert_events_shape.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: a `waveform_records` rec dict that may carry `shape_crest_factor`, `shape_near_peak_count`, `shape_sample_count`, `shape_axis`.
|
||||
- Produces: those four values stored on the row; refreshed on UPSERT.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# tests/test_insert_events_shape.py
|
||||
from sfm.database import SeismoDb
|
||||
from tests.helpers_events import make_event # existing helper used by other insert tests
|
||||
|
||||
def test_insert_stores_shape_from_record(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
ev = make_event(serial="BE1", key="0111abcd")
|
||||
rec = {ev._waveform_key.hex(): {
|
||||
"filename": "F.CE0W", "filesize": 10,
|
||||
"shape_crest_factor": 34.0, "shape_near_peak_count": 3,
|
||||
"shape_sample_count": 1024, "shape_axis": "Long"}}
|
||||
db.insert_events([ev], serial="BE1", waveform_records=rec)
|
||||
row = db.query_events(serial="BE1")[0]
|
||||
assert row["shape_crest_factor"] == 34.0
|
||||
assert row["shape_near_peak_count"] == 3
|
||||
assert row["shape_axis"] == "Long"
|
||||
```
|
||||
|
||||
> If `tests/helpers_events.make_event` doesn't exist, build the `Event` inline the way `tests/test_zc_freq_columns.py` does (copy its event-construction helper). Keep the assertion identical.
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_insert_events_shape.py -q`
|
||||
Expected: FAIL — `KeyError`/`sqlite3.OperationalError` (columns not in INSERT) or values are NULL.
|
||||
|
||||
- [ ] **Step 3: Implementation**
|
||||
|
||||
In `insert_events` INSERT: add `shape_crest_factor, shape_near_peak_count, shape_sample_count, shape_axis` to the column list, add four `?` placeholders, and add these to the VALUES tuple (after the `mic_zc_above_range` value):
|
||||
|
||||
```python
|
||||
rec.get("shape_crest_factor"),
|
||||
rec.get("shape_near_peak_count"),
|
||||
rec.get("shape_sample_count"),
|
||||
rec.get("shape_axis"),
|
||||
```
|
||||
|
||||
In the UPSERT `UPDATE ... SET`: add
|
||||
|
||||
```sql
|
||||
shape_crest_factor = COALESCE(?, shape_crest_factor),
|
||||
shape_near_peak_count = COALESCE(?, shape_near_peak_count),
|
||||
shape_sample_count = COALESCE(?, shape_sample_count),
|
||||
shape_axis = COALESCE(?, shape_axis),
|
||||
```
|
||||
|
||||
and the matching params (before `serial, ts`):
|
||||
|
||||
```python
|
||||
rec.get("shape_crest_factor") if rec else None,
|
||||
rec.get("shape_near_peak_count") if rec else None,
|
||||
rec.get("shape_sample_count") if rec else None,
|
||||
rec.get("shape_axis") if rec else None,
|
||||
```
|
||||
|
||||
(`COALESCE` on UPSERT so a re-import that lacks samples doesn't wipe a previously-computed shape.)
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_insert_events_shape.py -q`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add sfm/database.py tests/test_insert_events_shape.py
|
||||
git commit -m "feat(db): insert_events persists shape_* from waveform record"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Populate shape at ingest (the three save paths)
|
||||
|
||||
**Files:**
|
||||
- Modify: `sfm/waveform_store.py` — in `save`, `save_imported_bw`, `save_imported_idf`, after the `.h5` is written, add its shape to the returned `rec` dict.
|
||||
- Test: `tests/test_save_shape.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `sfm.shape_metrics.shape_from_h5`.
|
||||
- Produces: `save*` return dicts carry `shape_crest_factor / shape_near_peak_count / shape_sample_count / shape_axis` (present only when the `.h5` had usable samples).
|
||||
|
||||
- [ ] **Step 1: Write the failing test** (drives the BW-import path, which the existing suite already exercises)
|
||||
|
||||
```python
|
||||
# tests/test_save_shape.py
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from tests.helpers_bw import sample_bw_bytes, sample_serial # reuse existing import-test fixtures
|
||||
|
||||
def test_save_imported_bw_attaches_shape(tmp_path):
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
ev, rec = store.save_imported_bw(sample_bw_bytes(), serial=sample_serial())
|
||||
# A real BW waveform → shape present with a geo axis.
|
||||
assert rec.get("shape_axis") in ("Tran", "Vert", "Long")
|
||||
assert rec["shape_crest_factor"] > 0
|
||||
assert rec["shape_sample_count"] > 200
|
||||
```
|
||||
|
||||
> Reuse whatever fixture `tests/test_save_imported_bw*.py` already uses for BW bytes; match its import. If the existing BW fixture produces a degenerate/short waveform, use the fixture from the test that asserts a full h5.
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_save_shape.py -q`
|
||||
Expected: FAIL — `rec` has no `shape_*` keys.
|
||||
|
||||
- [ ] **Step 3: Implementation**
|
||||
|
||||
Add a helper near the top of `WaveformStore` methods (module-level import `from sfm.shape_metrics import shape_from_h5`). In each of `save`, `save_imported_bw`, `save_imported_idf`, immediately before building/returning the `rec` dict — and only when the `.h5` was written (i.e. `hdf5_filename`/`hdf5_path` is set) — compute and merge:
|
||||
|
||||
```python
|
||||
shape = shape_from_h5(hdf5_path) if hdf5_filename else None
|
||||
# ... in the returned rec dict literal, add:
|
||||
# **(shape and {
|
||||
# "shape_crest_factor": shape["crest_factor"],
|
||||
# "shape_near_peak_count": shape["near_peak_count"],
|
||||
# "shape_sample_count": shape["sample_count"],
|
||||
# "shape_axis": shape["axis"],
|
||||
# } or {}),
|
||||
```
|
||||
|
||||
Concretely, after each method computes `hdf5_filename`, add before its `return {...}`:
|
||||
|
||||
```python
|
||||
_shape = shape_from_h5(hdf5_path) if hdf5_filename else None
|
||||
_shape_rec = {
|
||||
"shape_crest_factor": _shape["crest_factor"],
|
||||
"shape_near_peak_count": _shape["near_peak_count"],
|
||||
"shape_sample_count": _shape["sample_count"],
|
||||
"shape_axis": _shape["axis"],
|
||||
} if _shape else {}
|
||||
```
|
||||
|
||||
and spread `**_shape_rec` into the returned dict. (`save_imported_bw`/`save_imported_idf` use their own hdf5 path variable names — use whichever local holds the written `.h5` path in each method.)
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_save_shape.py -q`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add sfm/waveform_store.py tests/test_save_shape.py
|
||||
git commit -m "feat(ingest): compute shape from the written .h5 in all save paths"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Backfill script for existing events
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/backfill_event_shape.py` (mirror `scripts/backfill_event_zc_freq.py`, but read the `.h5` for samples instead of the sidecar).
|
||||
- Test: `tests/test_backfill_event_shape.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `backfill_shape(db, store, *, dry_run=False) -> dict` with counts `{"updated","skipped_no_h5","skipped_no_samples"}`; `main(argv)` CLI mirroring the zc-freq script's args (`--db-path`, `--store-root`, `--dry-run`).
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# tests/test_backfill_event_shape.py
|
||||
import numpy as np, h5py
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from scripts.backfill_event_shape import backfill_shape
|
||||
from tests.helpers_events import make_event # or inline as in test_zc_freq_columns
|
||||
|
||||
def _h5(path, long):
|
||||
with h5py.File(path, "w") as f:
|
||||
g = f.create_group("samples")
|
||||
for k in ("Tran", "Vert"): g.create_dataset(k, data=np.zeros(1024, "float32"))
|
||||
g.create_dataset("Long", data=np.asarray(long, "float32"))
|
||||
|
||||
def test_backfill_updates_shape_and_is_idempotent(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
ev = make_event(serial="BE1", key="0111abcd")
|
||||
db.insert_events([ev], serial="BE1",
|
||||
waveform_records={ev._waveform_key.hex():
|
||||
{"filename": "F.CE0W", "filesize": 10}})
|
||||
# place the .h5 where store.paths_for expects it
|
||||
long = np.zeros(1024); long[100] = 0.48
|
||||
_h5(store.hdf5_path_for("BE1", "F.CE0W"), long)
|
||||
|
||||
c1 = backfill_shape(db, store)
|
||||
assert c1["updated"] == 1
|
||||
row = db.query_events(serial="BE1")[0]
|
||||
assert row["shape_axis"] == "Long" and row["shape_near_peak_count"] <= 3
|
||||
c2 = backfill_shape(db, store) # idempotent: re-run overwrites same values
|
||||
assert db.query_events(serial="BE1")[0]["shape_crest_factor"] == row["shape_crest_factor"]
|
||||
```
|
||||
|
||||
> Match `make_event` / column names to whatever `tests/test_zc_freq_columns.py` uses. `store.hdf5_path_for(serial, filename)` is the existing helper that returns the `.h5` path.
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_backfill_event_shape.py -q`
|
||||
Expected: FAIL — `ModuleNotFoundError: scripts.backfill_event_shape`.
|
||||
|
||||
- [ ] **Step 3: Implementation** (mirror the zc-freq script structure)
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
"""Backfill events.shape_* from each event's .h5 waveform samples. Idempotent."""
|
||||
from __future__ import annotations
|
||||
import argparse, logging, 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
|
||||
from sfm.shape_metrics import shape_from_h5
|
||||
|
||||
log = logging.getLogger("backfill_event_shape")
|
||||
|
||||
def backfill_shape(db: SeismoDb, store: WaveformStore, *, dry_run: bool = False) -> dict:
|
||||
counts = {"updated": 0, "skipped_no_h5": 0, "skipped_no_samples": 0}
|
||||
for row in db.query_events(limit=1_000_000):
|
||||
serial, filename = row.get("serial"), row.get("blastware_filename")
|
||||
if not serial or not filename:
|
||||
counts["skipped_no_h5"] += 1; continue
|
||||
h5_path = store.hdf5_path_for(serial, filename)
|
||||
if not h5_path.exists():
|
||||
counts["skipped_no_h5"] += 1; continue
|
||||
shape = shape_from_h5(h5_path)
|
||||
if shape is None:
|
||||
counts["skipped_no_samples"] += 1; continue
|
||||
if not dry_run:
|
||||
with db._connect() as conn:
|
||||
conn.execute(
|
||||
"UPDATE events SET shape_crest_factor=?, shape_near_peak_count=?, "
|
||||
"shape_sample_count=?, shape_axis=? WHERE id=?",
|
||||
(shape["crest_factor"], shape["near_peak_count"],
|
||||
shape["sample_count"], shape["axis"], row["id"]))
|
||||
counts["updated"] += 1
|
||||
log.info("backfill_shape: %s", counts)
|
||||
return counts
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--db-path", required=True)
|
||||
ap.add_argument("--store-root", required=True)
|
||||
ap.add_argument("--dry-run", action="store_true")
|
||||
a = ap.parse_args(argv)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
counts = backfill_shape(SeismoDb(a.db_path), WaveformStore(a.store_root), dry_run=a.dry_run)
|
||||
print(counts)
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
```
|
||||
|
||||
> `store.hdf5_path_for` and `db._connect` are existing internals used the same way by other scripts. If `hdf5_path_for` isn't public, use `store.paths_for(...)` sibling `.h5` path exactly as `save()` derives `hdf5_path`.
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_backfill_event_shape.py -q`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Run the full suite + commit**
|
||||
|
||||
```bash
|
||||
/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest -q
|
||||
git add scripts/backfill_event_shape.py tests/test_backfill_event_shape.py
|
||||
git commit -m "feat(scripts): backfill events.shape_* from .h5 samples"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Confirm /db/events carries shape + version bump
|
||||
|
||||
**Files:**
|
||||
- Test: `tests/test_db_events_exposes_shape.py`
|
||||
- Modify: `pyproject.toml` version; `sfm/server.py` version string; `CHANGELOG.md`.
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: the running `/db/events` route (already returns `SELECT *`).
|
||||
|
||||
- [ ] **Step 1: Write the failing test** (guards that the feed dict includes the new keys)
|
||||
|
||||
```python
|
||||
# tests/test_db_events_exposes_shape.py
|
||||
from sfm.database import SeismoDb
|
||||
def test_query_events_row_includes_shape_keys(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
# query_events returns dict(row); a fresh insert has the keys (values may be None)
|
||||
from tests.helpers_events import make_event
|
||||
db.insert_events([make_event(serial="BE1", key="0111abcd")], serial="BE1")
|
||||
row = db.query_events(serial="BE1")[0]
|
||||
for k in ("shape_crest_factor","shape_near_peak_count","shape_sample_count","shape_axis"):
|
||||
assert k in row
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails / passes**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest tests/test_db_events_exposes_shape.py -q`
|
||||
Expected: PASS immediately if Task 3 landed (columns present in `SELECT *`). If it fails, the columns weren't added — fix Task 3. (This task is the guard, not new behavior.)
|
||||
|
||||
- [ ] **Step 3: Version bump**
|
||||
|
||||
Bump `pyproject.toml` `version` 0.23.0 → 0.24.0; set `sfm/server.py` `version="0.24.0"`; add a `## v0.24.0` CHANGELOG entry ("waveform-shape metrics on events: crest factor + points-near-peak, ingest + backfill").
|
||||
|
||||
- [ ] **Step 4: Full suite**
|
||||
|
||||
Run: `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest -q`
|
||||
Expected: PASS (no regressions).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/test_db_events_exposes_shape.py pyproject.toml sfm/server.py CHANGELOG.md
|
||||
git commit -m "chore(release): v0.24.0 — waveform-shape metrics on events"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
**Spec coverage:** SFM shape columns (Tasks 3–4) ✓; DSP crest + near-peak (Task 1) ✓; ingest population (Task 5) ✓; backfill (Task 6) ✓; `/db/events` exposure (Task 7) ✓; NULL for histogram/no-sample events (Tasks 1/5/6 return None → NULL) ✓; 94%-coverage / series-4 fallback handled by NULL-then-Terra-View-fallback (Phase B) ✓. Terra-View scoring, 3-state review, twin flagging, export Notes column → **Phase B plan** (separate, depends on this feed). Calibration → Phase C.
|
||||
|
||||
**Placeholder scan:** No TBD/TODO; every code step has real code. The two "reuse existing fixture" notes point at concrete existing tests (`test_zc_freq_columns.py`, `test_save_imported_bw*.py`) rather than leaving blanks.
|
||||
|
||||
**Type consistency:** `shape_from_h5`/`shape_from_samples`/`channel_shape` return the same dict keys (`crest_factor`, `near_peak_count`, `sample_count`, `axis`) throughout; the DB columns (`shape_crest_factor`, `shape_near_peak_count`, `shape_sample_count`, `shape_axis`) and rec keys match across Tasks 4–6.
|
||||
|
||||
## Deferred to Phase B (terra-view, separate plan)
|
||||
|
||||
Scoring service combining shape + cheap signals; suspicion column + reason chips; `reviewed_real` mirror + 3-state review; twin-aware flag propagation; Notes-column export + Maximums "(excludes N flagged)". Written once this feed is live so column names/values are real.
|
||||
@@ -0,0 +1,264 @@
|
||||
# Phase B2-A (seismo-relay) — reviewed_real + 3-state mirror + twin propagation
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Give SFM a persisted, queryable `reviewed_real` flag alongside `false_trigger` (mirrored from the sidecar review block, mutually exclusive), and propagate a review to an event's histogram/waveform twin so flagging one flags both.
|
||||
|
||||
**Architecture:** Mirror the existing `false_trigger` mechanism. New `events.reviewed_real` column (auto-migrate). `update_event_review` mirrors BOTH flags from the sidecar review block and enforces mutual exclusivity on the columns. A `find_twins` matcher (same serial + identical peak_vector_sum + timestamp within a window) drives `propagate_review_to_twins`, which the sidecar-PATCH endpoint calls after mirroring the primary. Terra-View reads `reviewed_real` from `/db/events` (SELECT *).
|
||||
|
||||
**Tech Stack:** Python 3.10, raw sqlite3, FastAPI, pytest. Runner: `/home/serversdown/seismo-relay/.venv/bin/python3`.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 3 review states are **mutually exclusive**: an event is `false_trigger=1` XOR `reviewed_real=1` XOR neither. Setting one true forces the other's column to 0.
|
||||
- The sidecar JSON stays the source of truth for full review state; the `false_trigger`/`reviewed_real` columns are derived indexes (like today). B2-A propagates twins at the **column** level (what the feed/peak/export read); twin sidecars are not rewritten (known limitation — noted).
|
||||
- Twin match = **same serial AND identical `peak_vector_sum` (exact equality) AND `timestamp` within ± window (default 300 s), excluding the event itself.** Identical PVS is the safety anchor.
|
||||
- Known pre-existing test failures (~16, missing gitignored fixtures under `tests/fixtures/`) are unrelated — confirm zero NEW failures, don't try to fix them.
|
||||
- Run tests with `/home/serversdown/seismo-relay/.venv/bin/python3 -m pytest`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: `reviewed_real` column on events
|
||||
|
||||
**Files:** Modify `sfm/database.py` (`_SCHEMA` CREATE TABLE `events` + the Migration-1 rebuild `CREATE TABLE` + the `_migrate` ADD COLUMN loop). Test: `tests/test_reviewed_real_column.py`.
|
||||
|
||||
**Interfaces:** Produces `events.reviewed_real INTEGER NOT NULL DEFAULT 0`.
|
||||
|
||||
- [ ] **Step 1: Failing test**
|
||||
```python
|
||||
# tests/test_reviewed_real_column.py
|
||||
import sqlite3
|
||||
from sfm.database import SeismoDb
|
||||
def _cols(db):
|
||||
with sqlite3.connect(db.db_path) as c:
|
||||
return {r[1] for r in c.execute("PRAGMA table_info(events)")}
|
||||
def test_fresh_db_has_reviewed_real(tmp_path):
|
||||
assert "reviewed_real" in _cols(SeismoDb(tmp_path/"s.db"))
|
||||
def test_existing_db_migrates_reviewed_real(tmp_path):
|
||||
p = tmp_path/"s.db"; db = SeismoDb(p)
|
||||
with sqlite3.connect(p) as c:
|
||||
c.execute("ALTER TABLE events DROP COLUMN reviewed_real")
|
||||
assert "reviewed_real" not in _cols(db) # dropped (read via existing handle/connection)
|
||||
SeismoDb(p) # re-open migrates
|
||||
assert "reviewed_real" in _cols(SeismoDb(p))
|
||||
```
|
||||
> If sqlite < 3.35 lacks DROP COLUMN, fall back to building a table without the column and asserting re-open adds it (same as the shape-columns test did).
|
||||
|
||||
- [ ] **Step 2: Run → FAIL** (`pytest tests/test_reviewed_real_column.py -q`).
|
||||
- [ ] **Step 3: Implement**
|
||||
- In `_SCHEMA` `events` CREATE TABLE, after the `false_trigger ... DEFAULT 0,` line add: ` reviewed_real INTEGER NOT NULL DEFAULT 0, -- 0=no, 1=operator-confirmed real (mutually exclusive with false_trigger)`
|
||||
- In the `_migrate` ADD COLUMN loop tuple add: `("reviewed_real", "INTEGER NOT NULL DEFAULT 0"),`
|
||||
- **Do NOT** add it to the Migration-1 rebuild `CREATE TABLE events (...)` block — that block uses a positional `INSERT ... SELECT * FROM events_old` and, by convention, contains only the columns that existed when Migration 1 was written; every later column is added by the ADD COLUMN loop only. Adding it there crashes `_migrate` on genuinely legacy (pre-Migration-1) DBs.
|
||||
- [ ] **Step 4: Run → PASS.**
|
||||
- [ ] **Step 5: Commit** `feat(db): reviewed_real column on events (+ auto-migrate)`
|
||||
|
||||
---
|
||||
|
||||
### Task 2: `update_event_review` mirrors both flags + mutual exclusivity
|
||||
|
||||
**Files:** Modify `sfm/database.py` `update_event_review`. Test: `tests/test_update_event_review_reviewed_real.py`.
|
||||
|
||||
**Interfaces:** Consumes a `review` dict that may carry `false_trigger` and/or `reviewed_real` (bools). Produces mutually-exclusive column state.
|
||||
|
||||
- [ ] **Step 1: Failing test**
|
||||
```python
|
||||
# tests/test_update_event_review_reviewed_real.py
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event
|
||||
def _ins(db, eid_key="01110000", serial="BE1"):
|
||||
ev = Event(index=0); ev._waveform_key = bytes.fromhex(eid_key)
|
||||
db.insert_events([ev], serial=serial)
|
||||
return db.query_events(serial=serial)[0]["id"]
|
||||
def test_confirm_real_sets_and_clears_ft(tmp_path):
|
||||
db = SeismoDb(tmp_path/"s.db"); eid = _ins(db)
|
||||
db.update_event_review(eid, {"false_trigger": True})
|
||||
assert db.get_event(eid)["false_trigger"] == 1
|
||||
db.update_event_review(eid, {"reviewed_real": True}) # confirming real clears FT
|
||||
row = db.get_event(eid)
|
||||
assert row["reviewed_real"] == 1 and row["false_trigger"] == 0
|
||||
def test_flag_ft_clears_reviewed_real(tmp_path):
|
||||
db = SeismoDb(tmp_path/"s.db"); eid = _ins(db)
|
||||
db.update_event_review(eid, {"reviewed_real": True})
|
||||
db.update_event_review(eid, {"false_trigger": True})
|
||||
row = db.get_event(eid)
|
||||
assert row["false_trigger"] == 1 and row["reviewed_real"] == 0
|
||||
```
|
||||
> Build the Event inline like `tests/test_zc_freq_columns.py` if the import differs.
|
||||
|
||||
- [ ] **Step 2: Run → FAIL.**
|
||||
- [ ] **Step 3: Implement** — replace the body of `update_event_review` so it handles both keys:
|
||||
```python
|
||||
if not isinstance(review, dict):
|
||||
return False
|
||||
has_ft = "false_trigger" in review
|
||||
has_real = "reviewed_real" in review
|
||||
if not has_ft and not has_real:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute("SELECT 1 FROM events WHERE id=?", (event_id,)).fetchone()
|
||||
return row is not None
|
||||
sets = {}
|
||||
if has_ft:
|
||||
sets["false_trigger"] = 1 if review.get("false_trigger") else 0
|
||||
if has_real:
|
||||
sets["reviewed_real"] = 1 if review.get("reviewed_real") else 0
|
||||
# mutual exclusivity: a true in one forces the other column to 0
|
||||
if sets.get("false_trigger") == 1:
|
||||
sets["reviewed_real"] = 0
|
||||
if sets.get("reviewed_real") == 1:
|
||||
sets["false_trigger"] = 0
|
||||
assign = ", ".join(f"{k}=?" for k in sets)
|
||||
params = list(sets.values()) + [event_id]
|
||||
with self._connect() as conn:
|
||||
cur = conn.execute(f"UPDATE events SET {assign} WHERE id=?", params)
|
||||
return cur.rowcount > 0
|
||||
```
|
||||
- [ ] **Step 4: Run → PASS** (+ run `tests/test_*false_trigger*`/existing review tests to confirm no regression).
|
||||
- [ ] **Step 5: Commit** `feat(db): update_event_review mirrors reviewed_real + enforces 3-state exclusivity`
|
||||
|
||||
---
|
||||
|
||||
### Task 3: `find_twins` matcher
|
||||
|
||||
**Files:** Modify `sfm/database.py` (add `find_twins`). Test: `tests/test_find_twins.py`.
|
||||
|
||||
**Interfaces:** Produces `find_twins(event_id, *, window_seconds=300) -> list[dict]` — same serial, identical peak_vector_sum, timestamp within ±window, excluding self.
|
||||
|
||||
- [ ] **Step 1: Failing test**
|
||||
```python
|
||||
# tests/test_find_twins.py
|
||||
import datetime
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event, Timestamp
|
||||
def _ins(db, key, serial, pvs, ts):
|
||||
ev = Event(index=0); ev._waveform_key = bytes.fromhex(key)
|
||||
ev.timestamp = ts
|
||||
# peak_vector_sum comes from peak_values; simplest: insert then UPDATE pvs directly
|
||||
db.insert_events([ev], serial=serial)
|
||||
row = [r for r in db.query_events(serial=serial) if r["waveform_key"] == key][0]
|
||||
import sqlite3
|
||||
with sqlite3.connect(db.db_path) as c:
|
||||
c.execute("UPDATE events SET peak_vector_sum=? WHERE id=?", (pvs, row["id"]))
|
||||
return row["id"]
|
||||
def test_find_twins_matches_same_serial_pvs_near_time(tmp_path):
|
||||
db = SeismoDb(tmp_path/"s.db")
|
||||
base = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=20, minute=19, second=5)
|
||||
twin = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=20, minute=19, second=45)
|
||||
far = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=21, minute=0, second=0)
|
||||
a = _ins(db, "01110001", "BE1", 0.4763, base)
|
||||
b = _ins(db, "01110002", "BE1", 0.4763, twin) # twin: same serial+pvs, 40s apart
|
||||
c = _ins(db, "01110003", "BE1", 0.4763, far) # same pvs but >window away
|
||||
d = _ins(db, "01110004", "BE1", 0.9999, twin) # near time but different pvs
|
||||
ids = {r["id"] for r in db.find_twins(a, window_seconds=300)}
|
||||
assert ids == {b}
|
||||
```
|
||||
> Adjust the Event/Timestamp construction to match how `tests/test_waveform_store.py::_make_synthetic_event` builds them if fields differ.
|
||||
|
||||
- [ ] **Step 2: Run → FAIL.**
|
||||
- [ ] **Step 3: Implement**
|
||||
```python
|
||||
def find_twins(self, event_id: str, *, window_seconds: int = 300) -> list[dict]:
|
||||
row = self.get_event(event_id)
|
||||
if not row:
|
||||
return []
|
||||
serial = row.get("serial"); pvs = row.get("peak_vector_sum"); ts = row.get("timestamp")
|
||||
if serial is None or pvs is None or not ts:
|
||||
return []
|
||||
try:
|
||||
t = datetime.datetime.fromisoformat(ts.replace(" ", "T"))
|
||||
except ValueError:
|
||||
return []
|
||||
lo = (t - datetime.timedelta(seconds=window_seconds)).isoformat()
|
||||
hi = (t + datetime.timedelta(seconds=window_seconds)).isoformat()
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM events WHERE serial=? AND id!=? AND peak_vector_sum=? "
|
||||
"AND timestamp BETWEEN ? AND ?",
|
||||
(serial, event_id, pvs, lo, hi),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
```
|
||||
- [ ] **Step 4: Run → PASS.**
|
||||
- [ ] **Step 5: Commit** `feat(db): find_twins (serial + identical PVS + time window)`
|
||||
|
||||
---
|
||||
|
||||
### Task 4: propagate a review to twins + wire into the sidecar-PATCH endpoint
|
||||
|
||||
**Files:** Modify `sfm/database.py` (add `propagate_review_to_twins`); `sfm/server.py` (`db_event_sidecar_patch`). Test: `tests/test_twin_propagation.py`.
|
||||
|
||||
**Interfaces:** `propagate_review_to_twins(event_id, *, window_seconds=300) -> list[str]` copies the event's `false_trigger`/`reviewed_real` columns onto each twin; returns twin ids.
|
||||
|
||||
- [ ] **Step 1: Failing test** (DB-level)
|
||||
```python
|
||||
# tests/test_twin_propagation.py — reuse the _ins helper pattern from test_find_twins
|
||||
def test_propagate_copies_flags_to_twins(tmp_path):
|
||||
db = SeismoDb(tmp_path/"s.db")
|
||||
# (build primary + twin via the _ins helper as in test_find_twins)
|
||||
# flag the primary FT, then propagate:
|
||||
db.update_event_review(primary_id, {"false_trigger": True})
|
||||
moved = db.propagate_review_to_twins(primary_id)
|
||||
assert twin_id in moved
|
||||
assert db.get_event(twin_id)["false_trigger"] == 1
|
||||
```
|
||||
- [ ] **Step 2: Run → FAIL.**
|
||||
- [ ] **Step 3: Implement**
|
||||
- `sfm/database.py`:
|
||||
```python
|
||||
def propagate_review_to_twins(self, event_id: str, *, window_seconds: int = 300) -> list[str]:
|
||||
row = self.get_event(event_id)
|
||||
if not row:
|
||||
return []
|
||||
ft = 1 if row.get("false_trigger") else 0
|
||||
real = 1 if row.get("reviewed_real") else 0
|
||||
twins = self.find_twins(event_id, window_seconds=window_seconds)
|
||||
moved = []
|
||||
with self._connect() as conn:
|
||||
for tw in twins:
|
||||
conn.execute("UPDATE events SET false_trigger=?, reviewed_real=? WHERE id=?",
|
||||
(ft, real, tw["id"]))
|
||||
moved.append(tw["id"])
|
||||
return moved
|
||||
```
|
||||
- `sfm/server.py` `db_event_sidecar_patch`: after the existing `_get_db().update_event_review(event_id, new_sidecar.get("review", {}))`, add:
|
||||
```python
|
||||
# Propagate the review to the event's histogram/waveform twin(s) so
|
||||
# flagging one flags both (column-level; twins share serial+PVS+near time).
|
||||
try:
|
||||
_get_db().propagate_review_to_twins(event_id)
|
||||
except Exception as exc:
|
||||
log.warning("twin review-propagation failed for %s: %s", event_id, exc)
|
||||
```
|
||||
(Guard the `if body.review is not None:` block so propagation only runs when review changed.)
|
||||
- [ ] **Step 4: Run → PASS.**
|
||||
- [ ] **Step 5: Commit** `feat(review): propagate false_trigger/reviewed_real to twins on sidecar PATCH`
|
||||
|
||||
---
|
||||
|
||||
### Task 5: expose in feed guard + version bump
|
||||
|
||||
**Files:** Test `tests/test_reviewed_real_in_feed.py`; `pyproject.toml`, `sfm/server.py` version, `CHANGELOG.md`.
|
||||
|
||||
- [ ] **Step 1: Guard test** — a `query_events` row dict includes `reviewed_real` (SELECT * returns it).
|
||||
```python
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event
|
||||
def test_query_events_includes_reviewed_real(tmp_path):
|
||||
db = SeismoDb(tmp_path/"s.db")
|
||||
ev = Event(index=0); ev._waveform_key = bytes.fromhex("01110000")
|
||||
db.insert_events([ev], serial="BE1")
|
||||
assert "reviewed_real" in db.query_events(serial="BE1")[0]
|
||||
```
|
||||
- [ ] **Step 2: Run → PASS** (columns already present from Task 1).
|
||||
- [ ] **Step 3: Bump** `pyproject.toml` 0.24.0 → 0.25.0; `sfm/server.py` version="0.25.0"; add `## v0.25.0` CHANGELOG entry ("reviewed_real 3-state review flag + histogram/waveform twin review-propagation").
|
||||
- [ ] **Step 4: Full suite** — confirm zero NEW failures beyond the ~16 pre-existing.
|
||||
- [ ] **Step 5: Commit** `chore(release): v0.25.0 — reviewed_real + twin review-propagation`
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
**Spec coverage:** reviewed_real column (T1) ✓; mirror + mutual exclusivity (T2) ✓; twin match serial+identical-PVS+window (T3) ✓; twin propagation wired into the review path (T4) ✓; feed exposure + version (T5) ✓. Twin **sidecar** rewrite intentionally deferred (column-level only — documented in Global Constraints); this is the SFM half — the 3-state UI + confirm-real PATCH is the separate **B2-B (terra-view)** plan.
|
||||
|
||||
**Placeholder scan:** none — every step has real code (the two "adjust Event construction to match test_waveform_store" notes point at a concrete existing helper).
|
||||
|
||||
**Type consistency:** `false_trigger`/`reviewed_real` INTEGER columns used identically across T1/T2/T4; `find_twins`→`propagate_review_to_twins` both key on the same match; server calls the DB methods by the exact names T2–T4 define.
|
||||
@@ -1,3 +1,22 @@
|
||||
> ## SUPERSEDED 2026-08-25 — the body is a RECORD CHAIN
|
||||
>
|
||||
> The tag-dispatch model described in this document — `40 NN` segment headers,
|
||||
> tagless headers, channel rotation — is **wrong**. It produced nearly-correct
|
||||
> output only because the block table happens to tile the data sections.
|
||||
>
|
||||
> The body is a chain of self-delimiting per-channel records: `off+2` is a
|
||||
> uint16 BE length, `next = off + 2 + len`, and the chain ends on a record whose
|
||||
> chan_id is `0x06`. A 3-valued mode enum at `off+8` selects delta / absolute /
|
||||
> raw-12-bit semantics. `40 NN` is an ordinary int16 BE data block.
|
||||
>
|
||||
> See the record-chain section of `docs/instantel_protocol_reference.md` §7.6.1
|
||||
> and the implementation in `minimateplus/waveform_codec.py`.
|
||||
>
|
||||
> Result: all four channels equal length in 1388/1388 files (was 156/1388);
|
||||
> ASCII sample-count exact 75/75, fully exact 73/75; device PPV 1306/1306.
|
||||
>
|
||||
> This document is retained as the reasoning trail.
|
||||
|
||||
# Waveform body codec — FULLY DECODED (2026-05-11)
|
||||
|
||||
This is the **clean working note** for the body-codec reverse-engineering
|
||||
@@ -102,12 +121,24 @@ correct.
|
||||
| | | nibble first; signed 0..7 / 8..F = -8..-1)|
|
||||
| `20 NN` | NN + 2 bytes | int8 signed deltas (1 per byte) |
|
||||
| `00 NN` | 2 bytes | RLE: append NN copies of current value |
|
||||
| `30 NN` | NN*2 in data section, | Unknown content. Only in loud-from- |
|
||||
| | NN*4 in trailer | start events. |
|
||||
| `40 02` | 20 bytes (fixed) | Segment header |
|
||||
| `30 NN` | NN*1.5 + 2 in data | 12-bit signed deltas (see below). |
|
||||
| | section, NN*4 trailer | |
|
||||
| `40 NN` | 2*NN + 16 bytes | Segment header (NN = prev-channel deltas)|
|
||||
|
||||
NN is always a multiple of 4.
|
||||
|
||||
**Wide-NN forms.** `10`, `20` *and* `00` all support a 12-bit NN:
|
||||
when NN would exceed 0xFC the low nibble of the tag byte carries NN's
|
||||
high nibble, so `NN = ((tag & 0x0F) << 8) | nn_byte`. Confirmed for
|
||||
`1X`/`2X` in 2026-05-11 and for `0X` (RLE) in 2026-08-25 — e.g.
|
||||
`01 0c` = a 268-sample zero-delta run.
|
||||
|
||||
**`40 NN` is variable width.** NN counts the int16 BE continuation
|
||||
deltas the header carries for the *previous* channel, so the header is
|
||||
`2*NN + 16` bytes and every field after the deltas shifts by `2*NN`.
|
||||
`40 01` (18 B) and `40 03` (22 B) both occur alongside the common
|
||||
`40 02` (20 B). Confirmed 2026-08-25.
|
||||
|
||||
Implementation: `walk_body()` in `minimateplus/waveform_codec.py`.
|
||||
|
||||
### 7-byte preamble
|
||||
@@ -207,6 +238,61 @@ TL;DR table above are now locked in by pytest regression tests.
|
||||
still bails out partway through. Lower priority since the other
|
||||
7 events walk cleanly.
|
||||
|
||||
4. **Variable-prefix segment descriptors** (found 2026-08-25).
|
||||
3 of 75 ground-truth production events still truncate. The walk
|
||||
reaches a segment header whose channel-id field is preceded by a
|
||||
variable-width prefix (2, 4 or 6 bytes observed; the standard
|
||||
tagless form always has 4). These also carry an `01 00` marker
|
||||
instead of `02 00`. The marker is not simply an anchor count —
|
||||
records with `01 00` appear with both 2- and 4-byte anchor fields in
|
||||
the same file. Examples: `BE12599/N599LPNB.JF0W` @1155,
|
||||
`BE12599/N599LPWJ.980W` @849, `BE9558/K558LOF2.820W` @1485.
|
||||
|
||||
## Segment header: channel id and tagless form — 2026-08-25
|
||||
|
||||
The 4-byte field previously read as a "monotonic uint32 LE counter" is
|
||||
`[channel_id][00][00][segment_index]`, with `0x46`=Tran `0x47`=Vert
|
||||
`0x48`=Long `0x49`=MicL. Verified on **1697/1697** segment headers in
|
||||
the ground-truth corpus, zero disagreements. `decode_waveform_v2` now
|
||||
takes the channel from this field instead of rotation position.
|
||||
|
||||
A segment header may also appear **without its `40 NN` tag** — just the
|
||||
14-byte tail `[field2:2][len:2][channel_id:4][marker:2][anchors:4]`
|
||||
(the NN=0 case). `is_tagless_segment_header()` detects it from the six
|
||||
bytes at `[4:10]`.
|
||||
|
||||
## Geo scale: full scale is 32000 counts — 2026-08-25
|
||||
|
||||
One decoder unit (16 ADC counts) is exactly 0.005 in/s, so Normal range
|
||||
(10.000 in/s) is `10.0 / (0.005/16)` = **32000** ADC counts. Consumers
|
||||
that divided by 32768 read every geophone sample 2.34% low. Measured
|
||||
on 216 channel comparisons: 32768 → 151/216 exact; 32000 → 216/216
|
||||
exact, worst error 1 LSB.
|
||||
|
||||
**Scope — not waveform-specific.** The scale is applied where ADC
|
||||
counts become physical units, which every event passes through
|
||||
regardless of source codec:
|
||||
|
||||
| source | median ratio ours/device, 32768 | with 32000 |
|
||||
|---|---|---|
|
||||
| series-3 waveform (vs ASCII sample table) | 0.9766 | **1.0000** |
|
||||
| series-3 histogram (vs ASCII PPV, n=1137) | 0.9766 | **1.0000** |
|
||||
| series-4 Thor IDF (vs device peak, n=1468) | 0.960 | **0.983** |
|
||||
|
||||
The four block-framing fixes are waveform-only — `histogram_codec` is
|
||||
untouched by them.
|
||||
|
||||
## Ground-truth corpus (2026-08-25)
|
||||
|
||||
Beyond the bundled fixtures, the production waveform store keeps each
|
||||
event's original Blastware ASCII export at
|
||||
`<store>/<serial>/<filename>_ASCII.TXT`. 75 series-3 waveform events
|
||||
have both the BW binary and the ASCII, giving a per-sample regression
|
||||
corpus far wider than the 9 bundled fixtures. Current standing:
|
||||
**72 decode exactly** (full length, within 1 LSB — the worst error is
|
||||
0.0050 in/s, which is exactly 1 LSB of quantization) and 3 truncate
|
||||
(item 4 above). Zero events have full-length value errors.
|
||||
|
||||
## `30 NN` block format — CRACKED 2026-05-11 late
|
||||
|
||||
The `30 NN` block carries `NN` 12-bit signed deltas, packed as `NN/4`
|
||||
|
||||
@@ -210,8 +210,7 @@ def parse_idf_report(text: Union[str, bytes]) -> Dict[str, Any]:
|
||||
"long_peak_acceleration",
|
||||
"tran_peak_displacement", "vert_peak_displacement",
|
||||
"long_peak_displacement",
|
||||
"tran_time_of_peak", "vert_time_of_peak", "long_time_of_peak",
|
||||
"mic_time_of_peak", "mic_zc_freq",
|
||||
"mic_zc_freq",
|
||||
)
|
||||
for key in float_fields:
|
||||
v = raw.get(key)
|
||||
@@ -223,6 +222,22 @@ def parse_idf_report(text: Union[str, bytes]) -> Dict[str, Any]:
|
||||
else:
|
||||
out.pop(key, None)
|
||||
|
||||
# Time-of-peak: Thor labels these "TimeofPeak" (lowercase "of") so the
|
||||
# normalizer produces "*_timeof_peak". Map them to the canonical
|
||||
# ``*_time_of_peak`` output keys for downstream consumers.
|
||||
for raw_key, out_key in (
|
||||
("tran_timeof_peak", "tran_time_of_peak"),
|
||||
("vert_timeof_peak", "vert_time_of_peak"),
|
||||
("long_timeof_peak", "long_time_of_peak"),
|
||||
("mic_timeof_peak", "mic_time_of_peak"),
|
||||
):
|
||||
v = raw.get(raw_key)
|
||||
if v is None:
|
||||
continue
|
||||
fv = _parse_float(v)
|
||||
if fv is not None:
|
||||
out[out_key] = fv
|
||||
|
||||
# Microphone — Thor reports MicPSPL (dB(L)) which is the closest
|
||||
# analogue to BW's mic_ppv. The raw "99.4 dB(L)" string stays in
|
||||
# `out` under the original `mic_pspl` key for display; the parsed
|
||||
|
||||
+526
-48
@@ -1,64 +1,542 @@
|
||||
"""
|
||||
micromate/idf_file.py — placeholder for the Thor IDF binary codec.
|
||||
micromate/idf_file.py — Thor IDF binary codec.
|
||||
|
||||
Thor's ``.IDFH`` (histogram) and ``.IDFW`` (waveform) event files are an
|
||||
Instantel proprietary binary format that has not yet been reverse-
|
||||
engineered. Today seismo-relay treats them as opaque blobs:
|
||||
``WaveformStore.save_imported_idf`` stores the bytes verbatim and reads
|
||||
all device-authoritative metadata from the paired ``.IDFW.txt`` /
|
||||
``.IDFH.txt`` ASCII sidecar (parsed by ``idf_ascii_report.py``).
|
||||
Decodes the Instantel Micromate Series IV ``.IDFW`` (waveform) and
|
||||
``.IDFH`` (histogram) binary on-disk format. Sister module to
|
||||
``minimateplus/event_file_io.py``.
|
||||
|
||||
When we crack the binary codec — same reverse-engineering playbook we
|
||||
used to byte-perfect-parse Series III BW files (see
|
||||
``docs/instantel_protocol_reference.md`` and ``minimateplus/event_file_io.py``)
|
||||
— this module will grow:
|
||||
Status (2026-05-28):
|
||||
|
||||
- ``read_idf_file(path) -> IdfEvent``
|
||||
Parse a ``.IDFW``/``.IDFH`` binary and return a fully populated
|
||||
``IdfEvent`` whose waveform-sample arrays come from the binary
|
||||
(the .txt sidecar's tabular sample block being a best-effort
|
||||
check). Lets us ingest Thor events even when the operator
|
||||
hasn't enabled the .txt exporter — closing the
|
||||
``had_report=False`` gap that the thor-watcher forwarder
|
||||
currently tolerates as a known limitation.
|
||||
- **Genuine Series IV / Thor binaries** are all signed
|
||||
``00 12 01 00 00 00 Instantel\\0`` (sig-A in earlier notes). Two
|
||||
Series III (Blastware) binaries appear in the example corpus
|
||||
(``BE9439_*``) — they share the ``.IDFW``/``.IDFH`` extension by
|
||||
filing convention but carry a BW STRT header (``10 00 01 80 00 00
|
||||
Instantel STRT...``) and are NOT Thor data. The reader detects
|
||||
them by signature and raises NotImplementedError pointing callers
|
||||
at ``minimateplus.event_file_io.read_blastware_file()``.
|
||||
- **IDFW waveform body** reuses the BW segment-rotated block codec
|
||||
verbatim. Body always starts at file offset ``0x0f1f``. Samples
|
||||
decoded via ``minimateplus.waveform_codec.decode_waveform_v2``
|
||||
with 87–99% byte-exact match against ``.IDFW.txt`` sidecar (quiet
|
||||
events). Loud events hit the BW codec's known walker-stops-early
|
||||
limit. Residual ~3% drift on per-sample deltas — likely a
|
||||
Thor-specific 12-bit delta refinement that BW's codec doesn't
|
||||
model. Geo LSB = 0.0003 in/s; mic factor ~2.14e-6 psi/count.
|
||||
- **IDFH histogram body**: 12-byte segment header
|
||||
``[len_be 2B] 0a 00 00 00 [00 NN_counter] 05 3f`` introduces a
|
||||
segment of ``N`` 72-byte interval records (``N = (len - 10) // 72``).
|
||||
Each record holds 4 × 16-byte per-channel min/max/halfp + 8-byte
|
||||
tail. Geo peaks via ``max(|min|, |max|) / 32768 × 10`` in/s
|
||||
(matches sidecar within ~1.8%), freq via ``512 / halfp`` Hz.
|
||||
**All 859 Thor IDFH files in the corpus decode (181,071 intervals).**
|
||||
- Binary metadata directly extracted: serial, timestamp, sample_rate,
|
||||
record_time, calibration_date. Other fields fall back to the paired
|
||||
``.IDFW.txt`` / ``.IDFH.txt`` sidecar (consumed by
|
||||
``WaveformStore.save_imported_idf``).
|
||||
|
||||
- ``write_idf_file(path, event)`` (eventually)
|
||||
Round-trip event reconstruction, used for verifying the codec
|
||||
against captured device files the way ``write_blastware_file``
|
||||
verifies the Series III codec.
|
||||
|
||||
- Helpers for decoding the binary's per-channel sample arrays into
|
||||
physical units, the per-event flash buffer's monitor-log records,
|
||||
etc.
|
||||
|
||||
The reverse-engineering path: pair every ``.IDFW`` binary in
|
||||
``thor-watcher/example-data/`` with its sibling ``.IDFW.txt``, treating
|
||||
the txt's "Waveform Data Channels" block as ground-truth, and align
|
||||
the binary's per-channel int16-or-similar arrays against it. Header
|
||||
fields (sample rate, channel count, record time, timestamps) sit before
|
||||
the sample block — same approach as the BW codec where ASCII strings
|
||||
inside the binary (``Project:``, ``Client:``, etc.) anchored field
|
||||
discovery.
|
||||
The full reverse-engineering writeup lives in
|
||||
``docs/idf_protocol_reference.md``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Union
|
||||
from typing import Optional, Union
|
||||
|
||||
from .models import IdfEvent
|
||||
# Thor IDFW bodies are pinned to the SUPERSEDED tag-dispatch decoder.
|
||||
#
|
||||
# _find_waveform_body_offset() trial-decodes every candidate offset and keeps
|
||||
# whichever yields the most samples. The series-3 record-chain decoder
|
||||
# correctly returns None where the legacy walker returned garbage, which
|
||||
# changes that heuristic's winner on 33 of 577 files. The net effect measured
|
||||
# 2026-08-25 was positive (all-channels-equal 8/577 -> 506/577, mean abs PPV
|
||||
# error 0.228 -> 0.173 in/s) but Thor has no ASCII ground truth in the corpus
|
||||
# and its geo scaling is separately suspect, so the switch is deferred until
|
||||
# the body-offset search is reworked to use the record chain directly.
|
||||
from minimateplus.waveform_codec import (
|
||||
decode_waveform_legacy as decode_waveform_v2,
|
||||
)
|
||||
|
||||
from .models import IdfEvent, IdfPeaks, IdfReport
|
||||
|
||||
|
||||
def read_idf_file(path: Union[str, Path]) -> "IdfEvent":
|
||||
"""Parse a Thor ``.IDFW``/``.IDFH`` binary into an ``IdfEvent``.
|
||||
# Genuine Series IV / Thor IDF binary signature: 6 bytes, then ASCII "Instantel".
|
||||
_THOR_PREFIX = b"\x00\x12\x01\x00\x00\x00"
|
||||
# Stray Series III (Blastware) binaries that occasionally turn up in Thor
|
||||
# corpus directories renamed to the .IDFW/.IDFH convention. Their header
|
||||
# (`10 00 01 80 00 00 Instantel STRT ...`) is byte-for-byte a BW SUB 5A
|
||||
# STRT record, not a Thor binary. Detected so we can refuse-and-route
|
||||
# rather than mis-parse.
|
||||
_BW_STRAY_PREFIX = b"\x10\x00\x01\x80\x00\x00"
|
||||
_INSTANTEL_TAG = b"Instantel"
|
||||
|
||||
Not yet implemented. When implemented, this will be the canonical
|
||||
entry point for reading Thor binaries — the ASCII sidecar parser
|
||||
becomes an optional fast-path metadata supplement rather than the
|
||||
sole source of device-authoritative data.
|
||||
# Most common body offset for sig-A IDFW files (~50% of prod events;
|
||||
# 151/154 in the original tests/fixtures/THORDATA_example corpus). The
|
||||
# body is the segment-rotated block stream consumed by decode_waveform_v2;
|
||||
# bytes [0:3] are the magic ``00 02 00`` preamble. Production events
|
||||
# routinely use other offsets — see :func:`_find_waveform_body_offset`
|
||||
# for the dynamic scan. This constant survives only as the priority hint.
|
||||
_BODY_START_SIG_A = 0x0F1F
|
||||
|
||||
# Magic bytes that mark a candidate waveform-body preamble.
|
||||
_BODY_MAGIC = b"\x00\x02\x00"
|
||||
|
||||
# Where to start looking for body candidates inside the file. Skip the
|
||||
# fixed-header region where the same magic legitimately appears inside
|
||||
# channel-test records and the compliance block (offsets 0x015d, 0x091c,
|
||||
# 0x0ae2, 0x0d30 in observed events).
|
||||
_BODY_SCAN_FLOOR = 0x0E00
|
||||
|
||||
# Geophone count → in/s, derived from sidecar ground truth: the smallest
|
||||
# non-zero sample in 1,014-file corpus is 0.0003 in/s.
|
||||
_GEO_LSB_IPS = 0.0003
|
||||
|
||||
# Microphone count → psi, derived from sidecar regression on 50 sample
|
||||
# pairs from UM11719_20231219162723.IDFW (mic-heavy event).
|
||||
_MIC_LSB_PSI = 2.14e-6
|
||||
|
||||
# IDFH histogram constants.
|
||||
_IDFH_INTERVAL_SIZE = 72 # bytes per per-interval record
|
||||
_IDFH_SEGMENT_HEADER = 10 # bytes: [len_be 2B][0a 00 00 00 4B][00 NN 2B][05 3f 2B]
|
||||
_IDFH_SEGMENT_TAIL = 2 # bytes after the interval data block, before next marker
|
||||
_IDFH_HALFP_FREQ_NUM = 512.0 # freq_hz = NUM / halfp; halfp ≤ 5 means ">100 Hz" sentinel
|
||||
_IDFH_GEO_FULL_SCALE = 10.0 # in/s — Normal range
|
||||
_IDFH_INT16_FS = 32768.0
|
||||
_IDFH_CHANNELS = ("Tran", "Vert", "Long", "MicL")
|
||||
|
||||
|
||||
# ─── Binary metadata extraction ─────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdfBinaryMetadata:
|
||||
"""Fields recoverable from the sig-A binary header (no .txt needed)."""
|
||||
serial: Optional[str] = None
|
||||
event_datetime: Optional[datetime.datetime] = None
|
||||
sample_rate: Optional[int] = None
|
||||
record_time_sec: Optional[float] = None
|
||||
calibration_date: Optional[datetime.date] = None
|
||||
|
||||
|
||||
def _read_ascii_z(buf: bytes, off: int, maxlen: int = 64) -> Optional[str]:
|
||||
if off >= len(buf):
|
||||
return None
|
||||
end = buf.find(b"\x00", off, off + maxlen)
|
||||
if end < 0:
|
||||
end = min(off + maxlen, len(buf))
|
||||
s = buf[off:end].decode("ascii", errors="replace").strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def _decode_8byte_timestamp(buf: bytes, off: int) -> Optional[datetime.datetime]:
|
||||
"""Layout: ``[day][month][year_hi][year_lo][unknown][hour][min][sec]``."""
|
||||
if off + 8 > len(buf):
|
||||
return None
|
||||
day, mon, yh, yl, _unk, hr, mn, sc = buf[off : off + 8]
|
||||
year = (yh << 8) | yl
|
||||
if not (2015 <= year <= 2050 and 1 <= mon <= 12 and 1 <= day <= 31
|
||||
and 0 <= hr < 24 and 0 <= mn < 60 and 0 <= sc < 60):
|
||||
return None
|
||||
try:
|
||||
return datetime.datetime(year, mon, day, hr, mn, sc)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def extract_binary_metadata(buf: bytes) -> IdfBinaryMetadata:
|
||||
"""Pull serial/timestamp/sample_rate/record_time/calibration from the
|
||||
sig-A binary header.
|
||||
|
||||
Field positions confirmed against UM11719_20231219162723.IDFW; stable
|
||||
across the 151-file sig-A corpus.
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"IDF binary codec not yet implemented; the .IDFW/.IDFH binary format "
|
||||
"is undecoded. Use parse_idf_report() on the paired .txt sidecar "
|
||||
"for device-authoritative metadata."
|
||||
md = IdfBinaryMetadata()
|
||||
|
||||
# Serial: null-terminated ASCII at 0x14E.
|
||||
md.serial = _read_ascii_z(buf, 0x14E, maxlen=16)
|
||||
|
||||
# Sample rate + record time live in a BW-compatible compliance block.
|
||||
# Locate the 6-byte anchor `be 80 00 00 00 00` and read offsets relative
|
||||
# to it: anchor-6 = sample_rate uint16 BE; anchor+6 = record_time float32 BE.
|
||||
anchor = buf.find(b"\xbe\x80\x00\x00\x00\x00", 0x800, 0xA00)
|
||||
if anchor > 0:
|
||||
sr_bytes = buf[anchor - 6 : anchor - 4]
|
||||
if len(sr_bytes) == 2:
|
||||
sr = int.from_bytes(sr_bytes, "big")
|
||||
if sr in (256, 512, 1024, 2048, 4096):
|
||||
md.sample_rate = sr
|
||||
rt_bytes = buf[anchor + 6 : anchor + 10]
|
||||
if len(rt_bytes) == 4:
|
||||
try:
|
||||
rt = struct.unpack(">f", rt_bytes)[0]
|
||||
if 0.1 <= rt <= 600.0:
|
||||
md.record_time_sec = float(rt)
|
||||
except struct.error:
|
||||
pass
|
||||
|
||||
# Event timestamp: 8 bytes. Position differs between IDFW (0x97A) and
|
||||
# IDFH (0x9F8); scan a small range and accept the first valid decode.
|
||||
for off in (0x97A, 0x9F8):
|
||||
ts = _decode_8byte_timestamp(buf, off)
|
||||
if ts is not None:
|
||||
md.event_datetime = ts
|
||||
break
|
||||
|
||||
# Calibration date: day, month, year_be at 0x194-0x197.
|
||||
if len(buf) > 0x197:
|
||||
day, mon = buf[0x194], buf[0x195]
|
||||
year = int.from_bytes(buf[0x196 : 0x198], "big")
|
||||
if 1 <= mon <= 12 and 1 <= day <= 31 and 2015 <= year <= 2050:
|
||||
try:
|
||||
md.calibration_date = datetime.date(year, mon, day)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return md
|
||||
|
||||
|
||||
# ─── Sample decoder + unit conversion ───────────────────────────────────────
|
||||
|
||||
|
||||
def _find_waveform_body_offset(buf: bytes) -> Optional[int]:
|
||||
"""Pick the file offset of the waveform body by trial-decoding every
|
||||
``00 02 00`` magic position past the fixed-header region.
|
||||
|
||||
The body's location isn't fixed across all sig-A IDFW files — about
|
||||
half the production events use ``0x0f1f``, but the rest have offsets
|
||||
that shift based on header padding / channel-config layout. We
|
||||
auto-detect by:
|
||||
|
||||
1. Find every ``00 02 00`` occurrence past ``_BODY_SCAN_FLOOR``.
|
||||
2. Try ``decode_waveform_v2()`` on each candidate.
|
||||
3. Pick the offset whose decoded sample count is largest.
|
||||
|
||||
Returns the offset, or ``None`` if no candidate yielded more than
|
||||
the trivial 2-sample preamble (= "no real body found").
|
||||
|
||||
Costs ~2-8 trial decodes per file; in practice the first candidate
|
||||
past 0x0e00 is usually the right one.
|
||||
"""
|
||||
if len(buf) < _BODY_SCAN_FLOOR + 8:
|
||||
return None
|
||||
best: Optional[tuple[int, int]] = None # (total_samples, offset)
|
||||
i = _BODY_SCAN_FLOOR
|
||||
while True:
|
||||
j = buf.find(_BODY_MAGIC, i)
|
||||
if j < 0:
|
||||
break
|
||||
i = j + 1
|
||||
try:
|
||||
decoded = decode_waveform_v2(buf[j:])
|
||||
except Exception:
|
||||
continue
|
||||
if not decoded:
|
||||
continue
|
||||
total = sum(len(v) for v in decoded.values())
|
||||
# A "real" body has more than just the 2-sample preamble.
|
||||
if total <= 2:
|
||||
continue
|
||||
if best is None or total > best[0]:
|
||||
best = (total, j)
|
||||
return best[1] if best else None
|
||||
|
||||
|
||||
def _decode_waveform_samples(buf: bytes) -> Optional[dict]:
|
||||
"""Decode samples from the sig-A waveform body.
|
||||
|
||||
Returns the raw decoder counts dict — geo LSB = 0.0003 in/s, mic in
|
||||
its own count unit (see :func:`mic_count_to_psi`). Returns None if
|
||||
no usable body is found.
|
||||
|
||||
Uses :func:`_find_waveform_body_offset` to locate the body — the
|
||||
file-offset varies across events (~50% sit at the canonical
|
||||
``0x0f1f`` but the rest don't), so the previous hardcoded constant
|
||||
silently produced 2-sample preamble-only output for half the corpus.
|
||||
"""
|
||||
off = _find_waveform_body_offset(buf)
|
||||
if off is None:
|
||||
return None
|
||||
return decode_waveform_v2(buf[off:])
|
||||
|
||||
|
||||
def geo_count_to_ips(count: int) -> float:
|
||||
"""Convert a Thor geo decoder count to in/s. LSB = 0.0003 in/s."""
|
||||
return count * _GEO_LSB_IPS
|
||||
|
||||
|
||||
def mic_count_to_psi(count: int) -> float:
|
||||
"""Convert a Thor mic decoder count to psi. Scale derived from
|
||||
regression over 50 sample pairs in UM11719_20231219162723.IDFW;
|
||||
consistent to ~5%. Calibration constants from the channel block
|
||||
can refine this once decoded.
|
||||
"""
|
||||
return count * _MIC_LSB_PSI
|
||||
|
||||
|
||||
# ─── IDFH histogram decoder ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdfhInterval:
|
||||
"""One decoded histogram interval (typically one minute of monitoring)."""
|
||||
offset: int # file byte offset of the 72-byte record
|
||||
# Per-channel min/max ADC counts (int16 BE), half-period samples, peak count.
|
||||
# Peak = max(|min|, |max|). freq_hz = 512/halfp (None if halfp ≤ 5 →
|
||||
# ">100 Hz" sentinel; matches sidecar convention).
|
||||
tran_min: int
|
||||
tran_max: int
|
||||
tran_halfp: int
|
||||
vert_min: int
|
||||
vert_max: int
|
||||
vert_halfp: int
|
||||
long_min: int
|
||||
long_max: int
|
||||
long_halfp: int
|
||||
micl_min: int
|
||||
micl_max: int
|
||||
micl_halfp: int
|
||||
|
||||
def peak_count(self, channel: str) -> int:
|
||||
mn = getattr(self, f"{channel.lower()}_min")
|
||||
mx = getattr(self, f"{channel.lower()}_max")
|
||||
return max(abs(mn), abs(mx))
|
||||
|
||||
def peak_ips(self, channel: str) -> float:
|
||||
"""Convert peak count to in/s (geo channels only)."""
|
||||
return self.peak_count(channel) / _IDFH_INT16_FS * _IDFH_GEO_FULL_SCALE
|
||||
|
||||
def freq_hz(self, channel: str) -> Optional[float]:
|
||||
halfp = getattr(self, f"{channel.lower()}_halfp")
|
||||
if halfp <= 5:
|
||||
return None
|
||||
return _IDFH_HALFP_FREQ_NUM / halfp
|
||||
|
||||
|
||||
def _decode_idfh_interval(buf72: bytes, offset: int) -> IdfhInterval:
|
||||
"""Decode one 72-byte interval record into per-channel min/max/halfp."""
|
||||
import struct
|
||||
fields = []
|
||||
for i in range(4):
|
||||
block = buf72[i * 16 : (i + 1) * 16]
|
||||
mn = struct.unpack_from(">h", block, 0)[0]
|
||||
mx = struct.unpack_from(">h", block, 2)[0]
|
||||
# block[4:6] = int16 BE, role unknown (possibly time-of-peak)
|
||||
halfp = struct.unpack_from(">H", block, 6)[0]
|
||||
# block[10:12] and block[14:16] are uint16 BE with unknown semantics
|
||||
# (likely sum / count contributions for the PVS computation).
|
||||
fields.extend([mn, mx, halfp])
|
||||
# Tail 8 bytes (buf72[64:72]) carry PVS-related data; not yet decoded.
|
||||
return IdfhInterval(
|
||||
offset=offset,
|
||||
tran_min=fields[0], tran_max=fields[1], tran_halfp=fields[2],
|
||||
vert_min=fields[3], vert_max=fields[4], vert_halfp=fields[5],
|
||||
long_min=fields[6], long_max=fields[7], long_halfp=fields[8],
|
||||
micl_min=fields[9], micl_max=fields[10], micl_halfp=fields[11],
|
||||
)
|
||||
|
||||
|
||||
def decode_idfh_body(buf: bytes) -> list:
|
||||
"""Walk an IDFH file and decode every interval record.
|
||||
|
||||
The body has one or more segments; each segment header is 12 bytes:
|
||||
``[length_be 2B][0a 00 00 00][00 NN_counter][05 3f]`` where ``length``
|
||||
is bytes from the magic through the end of the interval block
|
||||
(= 10 + 72 × n_intervals). Segments are separated by a 2-byte tail
|
||||
+ next-segment 2-byte prefix (the bytes before the next length field).
|
||||
Confirmed against the 859-file corpus (181,071 intervals decoded; 1
|
||||
failure is the sig-B BE9439 file).
|
||||
"""
|
||||
intervals: list = []
|
||||
i = 0
|
||||
while True:
|
||||
j = buf.find(b"\x0a\x00\x00\x00", i)
|
||||
if j < 0 or j < 2:
|
||||
break
|
||||
# Validate: [length_be][0a 00 00 00][00 NN][05 3f]
|
||||
if buf[j + 4] != 0x00 or buf[j + 6 : j + 8] != b"\x05\x3f":
|
||||
i = j + 1
|
||||
continue
|
||||
length = int.from_bytes(buf[j - 2 : j], "big")
|
||||
n = (length - _IDFH_SEGMENT_HEADER) // _IDFH_INTERVAL_SIZE
|
||||
if n <= 0:
|
||||
i = j + 1
|
||||
continue
|
||||
header_start = j - 2
|
||||
interval_start = header_start + _IDFH_SEGMENT_HEADER
|
||||
for k in range(n):
|
||||
off = interval_start + k * _IDFH_INTERVAL_SIZE
|
||||
if off + _IDFH_INTERVAL_SIZE > len(buf):
|
||||
break
|
||||
chunk = buf[off : off + _IDFH_INTERVAL_SIZE]
|
||||
intervals.append(_decode_idfh_interval(chunk, off))
|
||||
# Advance past this segment + the 2-byte tail.
|
||||
i = header_start + length + _IDFH_SEGMENT_TAIL
|
||||
return intervals
|
||||
|
||||
|
||||
# ─── Top-level reader ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdfReadResult:
|
||||
"""Return type for :func:`read_idf_file`.
|
||||
|
||||
For waveforms (``.IDFW``), ``samples`` holds the per-channel sample
|
||||
arrays in Thor decoder counts. For histograms (``.IDFH``),
|
||||
``samples`` is empty and ``intervals`` holds the per-interval
|
||||
record list (peaks, freqs).
|
||||
"""
|
||||
event: IdfEvent
|
||||
samples: dict # {"Tran": [...], ...} for IDFW; empty for IDFH
|
||||
binary_metadata: IdfBinaryMetadata
|
||||
signature: str # always "thor" for now (sig-A genuine Thor)
|
||||
intervals: Optional[list] = None # list[IdfhInterval] for IDFH; None for IDFW
|
||||
|
||||
|
||||
def read_idf_file(
|
||||
path: Union[str, Path],
|
||||
*,
|
||||
data: Optional[bytes] = None,
|
||||
) -> IdfReadResult:
|
||||
"""Parse a Thor ``.IDFW`` binary into an ``IdfEvent`` + decoded samples.
|
||||
|
||||
Currently implements signature-A waveforms only. Signature-B
|
||||
(old-firmware) and ``.IDFH`` histograms raise NotImplementedError;
|
||||
use the paired ``.IDFW.txt`` / ``.IDFH.txt`` sidecar for those via
|
||||
``parse_idf_report()``.
|
||||
|
||||
Returns an :class:`IdfReadResult`. The caller converts int sample
|
||||
counts to physical units via :func:`geo_count_to_ips` /
|
||||
:func:`mic_count_to_psi`.
|
||||
|
||||
``path`` is used for filename in error messages and ``.IDFH`` vs
|
||||
``.IDFW`` suffix detection. When ``data`` is supplied the disk
|
||||
read is skipped — useful for ingest paths that already have the
|
||||
bytes in memory and where the file may not exist on disk yet.
|
||||
"""
|
||||
p = Path(path)
|
||||
buf = data if data is not None else p.read_bytes()
|
||||
|
||||
if len(buf) < 16 or buf[6:16] != _INSTANTEL_TAG + b"\x00":
|
||||
raise ValueError(f"{p.name}: not an IDF file (missing Instantel magic)")
|
||||
|
||||
sig_prefix = buf[:6]
|
||||
if sig_prefix == _THOR_PREFIX:
|
||||
signature = "thor"
|
||||
elif sig_prefix == _BW_STRAY_PREFIX:
|
||||
raise NotImplementedError(
|
||||
f"{p.name}: file has a Series III (Blastware) STRT header in "
|
||||
"an IDF-named container — not a Thor binary. Route through "
|
||||
"minimateplus.event_file_io.read_blastware_file() instead "
|
||||
"(peaks decode; samples & full metadata don't, but it's not "
|
||||
"Thor data so the Thor codec doesn't apply)."
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"{p.name}: unknown IDF signature {sig_prefix.hex()}")
|
||||
|
||||
is_histogram = p.suffix.upper() == ".IDFH"
|
||||
md = extract_binary_metadata(buf)
|
||||
|
||||
if is_histogram:
|
||||
intervals = decode_idfh_body(buf)
|
||||
if not intervals:
|
||||
raise ValueError(f"{p.name}: IDFH body decoded no intervals")
|
||||
# Peaks: max across all intervals on each channel (per-channel max
|
||||
# of stored max-magnitudes; sidecar's PPV row carries the same).
|
||||
peak_tran = max((iv.peak_ips("Tran") for iv in intervals), default=0.0)
|
||||
peak_vert = max((iv.peak_ips("Vert") for iv in intervals), default=0.0)
|
||||
peak_long = max((iv.peak_ips("Long") for iv in intervals), default=0.0)
|
||||
# Mic peak in psi — Thor stores per-interval mic ADC counts in the
|
||||
# binary; convert the max count to psi via the per-count factor.
|
||||
mic_peak_count = max((iv.peak_count("MicL") for iv in intervals), default=0)
|
||||
mic_peak_psi = mic_count_to_psi(mic_peak_count) if mic_peak_count else None
|
||||
rep = IdfReport(
|
||||
serial_number=md.serial,
|
||||
event_type="Full Histogram",
|
||||
event_datetime=md.event_datetime,
|
||||
filename=p.name,
|
||||
sample_rate=md.sample_rate,
|
||||
record_time_sec=md.record_time_sec,
|
||||
)
|
||||
peaks = IdfPeaks(
|
||||
transverse_ips=peak_tran,
|
||||
vertical_ips=peak_vert,
|
||||
longitudinal_ips=peak_long,
|
||||
peak_vector_sum_ips=None,
|
||||
mic_pspl_dbl=None, # IDFH binary doesn't carry the dB(L) value
|
||||
mic_pspl_psi=mic_peak_psi,
|
||||
)
|
||||
event = IdfEvent(
|
||||
serial=md.serial or "UNKNOWN",
|
||||
timestamp=md.event_datetime or datetime.datetime(1970, 1, 1),
|
||||
kind="Histogram",
|
||||
filename=p.name,
|
||||
sample_rate=md.sample_rate,
|
||||
record_time_sec=md.record_time_sec,
|
||||
peaks=peaks,
|
||||
report=rep,
|
||||
)
|
||||
return IdfReadResult(
|
||||
event=event,
|
||||
samples={},
|
||||
binary_metadata=md,
|
||||
signature=signature,
|
||||
intervals=intervals,
|
||||
)
|
||||
|
||||
# Waveform path.
|
||||
decoded = _decode_waveform_samples(buf)
|
||||
if decoded is None:
|
||||
raise ValueError(f"{p.name}: waveform body codec failed")
|
||||
|
||||
rep = IdfReport(
|
||||
serial_number=md.serial,
|
||||
event_type="Full Waveform",
|
||||
event_datetime=md.event_datetime,
|
||||
filename=p.name,
|
||||
sample_rate=md.sample_rate,
|
||||
record_time_sec=md.record_time_sec,
|
||||
)
|
||||
|
||||
def _peak_ips(ch: str) -> float:
|
||||
arr = decoded.get(ch, [])
|
||||
return geo_count_to_ips(max((abs(v) for v in arr), default=0))
|
||||
|
||||
# Mic peak psi from binary: max absolute MicL ADC count × 2.14e-6 psi/count.
|
||||
mic_arr = decoded.get("MicL", [])
|
||||
mic_peak_count = max((abs(v) for v in mic_arr), default=0)
|
||||
mic_peak_psi = mic_count_to_psi(mic_peak_count) if mic_peak_count else None
|
||||
|
||||
peaks = IdfPeaks(
|
||||
transverse_ips=_peak_ips("Tran"),
|
||||
vertical_ips=_peak_ips("Vert"),
|
||||
longitudinal_ips=_peak_ips("Long"),
|
||||
# PVS requires aligned per-sample √(T²+V²+L²); leave None — the
|
||||
# sidecar carries it and the bridge picks it up if present.
|
||||
peak_vector_sum_ips=None,
|
||||
mic_pspl_dbl=None, # binary IDFW doesn't carry the dB(L) value;
|
||||
# sidecar .txt fills it via IdfReport.from_dict
|
||||
mic_pspl_psi=mic_peak_psi,
|
||||
)
|
||||
|
||||
event = IdfEvent(
|
||||
serial=md.serial or "UNKNOWN",
|
||||
timestamp=md.event_datetime or datetime.datetime(1970, 1, 1),
|
||||
kind="Waveform",
|
||||
filename=p.name,
|
||||
sample_rate=md.sample_rate,
|
||||
record_time_sec=md.record_time_sec,
|
||||
peaks=peaks,
|
||||
report=rep,
|
||||
)
|
||||
|
||||
return IdfReadResult(
|
||||
event=event,
|
||||
samples=decoded,
|
||||
binary_metadata=md,
|
||||
signature=signature,
|
||||
)
|
||||
@@ -0,0 +1,323 @@
|
||||
"""
|
||||
micromate/idf_to_bw_report.py — adapter that projects a parsed Thor IDF
|
||||
report (+ binary metadata + decoded IDFH intervals) into the
|
||||
``bw_report``-shaped dict that :mod:`sfm.report_pdf.gather_report_data`
|
||||
consumes.
|
||||
|
||||
Lets Thor events flow through the existing Series III Event Report PDF
|
||||
pipeline without duplicating the renderer. Thor's report content is
|
||||
~95% the same data shape as BW's; the field names differ but the
|
||||
underlying metrics map 1:1.
|
||||
|
||||
Caveats
|
||||
───────
|
||||
|
||||
- **Mic units** — Thor records ``MicPSPL`` natively in dB(L). This
|
||||
adapter sets ``bw_report.mic.pspl_dbl`` directly; the report
|
||||
renderer recomputes the equivalent psi via its dBL→psi formula.
|
||||
- **Saturation / above-range flags** — Thor doesn't always mark
|
||||
``OORANGE`` the way BW does; we set ``zc_freq_above_range`` only
|
||||
when a `>100` sentinel was preserved in the raw text.
|
||||
- **Per-interval data** — for IDFH events we build ``interval_times``
|
||||
by stepping ``IntervalSize`` from ``HistogramStartTime``; the binary
|
||||
decoder confirms one record per step (882 / 881 / 881 ... across
|
||||
the corpus).
|
||||
- **calibration_by parsing** — Thor's free-form ``Calibration : November
|
||||
22, 2023 by Instantel`` is split on ``" by "`` to extract the
|
||||
calibrator; the date prefix is parsed where possible, otherwise
|
||||
the binary-extracted ``calibration_date`` from
|
||||
:class:`micromate.idf_file.IdfBinaryMetadata` wins.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
# ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
_NUM_RE = re.compile(r"-?\d+(?:\.\d+)?")
|
||||
|
||||
|
||||
def _parse_first_number(s: Optional[str]) -> Optional[float]:
|
||||
"""Pull the first numeric token from a string like ``"0.1500 in/s"``."""
|
||||
if s is None:
|
||||
return None
|
||||
m = _NUM_RE.search(str(s))
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
return float(m.group(0))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_interval_size_s(s: Optional[str]) -> Optional[float]:
|
||||
"""``"60 sec"`` → 60.0, ``"5 min"`` → 300.0, ``"1 hour"`` → 3600."""
|
||||
if s is None:
|
||||
return None
|
||||
num = _parse_first_number(s)
|
||||
if num is None:
|
||||
return None
|
||||
sl = str(s).lower()
|
||||
if "hour" in sl or "hr" in sl:
|
||||
return num * 3600.0
|
||||
if "min" in sl:
|
||||
return num * 60.0
|
||||
return num # default to seconds
|
||||
|
||||
|
||||
def _parse_calibration(text: Optional[str]) -> tuple[Optional[str], Optional[str]]:
|
||||
"""Split ``"November 22, 2023 by Instantel"`` → (ISO date, calibrator).
|
||||
|
||||
Returns ``(None, None)`` if neither half parses.
|
||||
"""
|
||||
if not text:
|
||||
return None, None
|
||||
parts = str(text).split(" by ", 1)
|
||||
date_part = parts[0].strip() if parts else None
|
||||
by_part = parts[1].strip() if len(parts) > 1 else None
|
||||
iso_date: Optional[str] = None
|
||||
if date_part:
|
||||
for fmt in ("%B %d, %Y", "%b %d, %Y", "%Y-%m-%d", "%m/%d/%Y"):
|
||||
try:
|
||||
iso_date = datetime.datetime.strptime(date_part, fmt).date().isoformat()
|
||||
break
|
||||
except ValueError:
|
||||
continue
|
||||
return iso_date, by_part
|
||||
|
||||
|
||||
def _channel_peaks(idf: Dict[str, Any], ch_lc: str) -> Dict[str, Any]:
|
||||
"""Map ``tran_ppv`` / ``tran_zc_freq`` / ... → bw_report.peaks.tran shape."""
|
||||
out: Dict[str, Any] = {}
|
||||
for src, dst in (
|
||||
(f"{ch_lc}_ppv", "ppv_ips"),
|
||||
(f"{ch_lc}_zc_freq", "zc_freq_hz"),
|
||||
(f"{ch_lc}_time_of_peak", "time_of_peak_s"),
|
||||
(f"{ch_lc}_peak_acceleration", "peak_accel_g"),
|
||||
(f"{ch_lc}_peak_displacement", "peak_disp_in"),
|
||||
):
|
||||
v = idf.get(src)
|
||||
if v is not None:
|
||||
out[dst] = v
|
||||
# ZC freq ">100" sentinel: the raw text carries it under the un-typed
|
||||
# key (e.g. ``raw["tran_zc_freq"]`` would be ``">100"``), and our parser
|
||||
# dropped the typed entry. Detect that case and flag.
|
||||
raw_zc = idf.get(f"{ch_lc}_zc_freq")
|
||||
if isinstance(raw_zc, str) and ">" in raw_zc:
|
||||
out["zc_freq_above_range"] = True
|
||||
out.pop("zc_freq_hz", None)
|
||||
return out
|
||||
|
||||
|
||||
def _sensor_check(idf: Dict[str, Any], ch_lc: str) -> Dict[str, Any]:
|
||||
out: Dict[str, Any] = {}
|
||||
fr = idf.get(f"{ch_lc}_test_freq")
|
||||
if fr is not None:
|
||||
out["freq_hz"] = _parse_first_number(fr)
|
||||
rt = idf.get(f"{ch_lc}_test_ratio")
|
||||
if rt is not None:
|
||||
out["ratio"] = _parse_first_number(rt)
|
||||
am = idf.get(f"{ch_lc}_test_amplitude")
|
||||
if am is not None:
|
||||
out["amplitude_mv"] = _parse_first_number(am)
|
||||
res = idf.get(f"{ch_lc}_test_results")
|
||||
if res is not None:
|
||||
out["result"] = str(res).strip()
|
||||
return {k: v for k, v in out.items() if v is not None}
|
||||
|
||||
|
||||
def _interval_times(idf: Dict[str, Any], n_intervals: Optional[int]) -> List[str]:
|
||||
"""Synthesise per-interval timestamps from start + interval_size × k.
|
||||
|
||||
Returns ``[]`` when start time or interval size is unknown.
|
||||
"""
|
||||
if not n_intervals:
|
||||
return []
|
||||
start_date = idf.get("histogram_start_date") or idf.get("event_date")
|
||||
start_time = idf.get("histogram_start_time") or idf.get("event_time")
|
||||
iv_str = idf.get("interval_size")
|
||||
iv_s = _parse_interval_size_s(iv_str)
|
||||
if not (start_date and start_time and iv_s):
|
||||
return []
|
||||
try:
|
||||
t0 = datetime.datetime.strptime(f"{start_date} {start_time}", "%Y-%m-%d %H:%M:%S")
|
||||
except ValueError:
|
||||
return []
|
||||
out = []
|
||||
for k in range(int(n_intervals)):
|
||||
t = t0 + datetime.timedelta(seconds=iv_s * (k + 1))
|
||||
out.append(t.isoformat())
|
||||
return out
|
||||
|
||||
|
||||
# ─── Top-level adapter ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def build_bw_report_from_idf(
|
||||
idf_report: Dict[str, Any],
|
||||
*,
|
||||
binary_md=None,
|
||||
intervals: Optional[list] = None,
|
||||
is_histogram: Optional[bool] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Project a parsed IDF report dict (and optional binary metadata +
|
||||
decoded IDFH intervals) into the BW report sidecar shape.
|
||||
|
||||
The returned dict is structurally identical to what
|
||||
``minimateplus.event_file_io._bw_report_to_dict`` produces from a
|
||||
real BW ASCII report — it can be assigned to
|
||||
``sidecar["bw_report"]`` and consumed verbatim by
|
||||
``sfm.report_pdf.gather_report_data``.
|
||||
|
||||
``intervals`` is the list of :class:`micromate.idf_file.IdfhInterval`
|
||||
objects from :func:`micromate.idf_file.decode_idfh_body`; only used
|
||||
for histogram events to derive accurate ``interval_times``.
|
||||
"""
|
||||
if is_histogram is None:
|
||||
et = str(idf_report.get("event_type", ""))
|
||||
is_histogram = et.lower().startswith("full histogram")
|
||||
|
||||
# ── Trigger / recording / device ─────────────────────────────────────
|
||||
trigger_channel = idf_report.get("trigger")
|
||||
trigger_level = _parse_first_number(idf_report.get("geo_trigger_level"))
|
||||
geo_range_ips = _parse_first_number(idf_report.get("geo_range"))
|
||||
|
||||
cal_iso, cal_by = _parse_calibration(idf_report.get("calibration"))
|
||||
# Prefer the binary-extracted calibration_date when our text parse fell
|
||||
# through; the binary date is unambiguous.
|
||||
if cal_iso is None and binary_md is not None and binary_md.calibration_date:
|
||||
cal_iso = binary_md.calibration_date.isoformat()
|
||||
|
||||
# ── Histogram fields ────────────────────────────────────────────────
|
||||
hist_block: Dict[str, Any] = {
|
||||
"start": None, "stop": None, "n_intervals": None,
|
||||
"interval_size": None, "interval_size_s": None,
|
||||
"channel_peak_when": {},
|
||||
}
|
||||
if is_histogram:
|
||||
sd = idf_report.get("histogram_start_date")
|
||||
st = idf_report.get("histogram_start_time")
|
||||
if sd and st:
|
||||
try:
|
||||
hist_block["start"] = datetime.datetime.strptime(
|
||||
f"{sd} {st}", "%Y-%m-%d %H:%M:%S"
|
||||
).isoformat()
|
||||
except ValueError:
|
||||
pass
|
||||
ed = idf_report.get("histogram_stop_date")
|
||||
et_ = idf_report.get("histogram_stop_time")
|
||||
if ed and et_:
|
||||
try:
|
||||
hist_block["stop"] = datetime.datetime.strptime(
|
||||
f"{ed} {et_}", "%Y-%m-%d %H:%M:%S"
|
||||
).isoformat()
|
||||
except ValueError:
|
||||
pass
|
||||
n_raw = idf_report.get("number_of_intervals")
|
||||
if n_raw is not None:
|
||||
try:
|
||||
# Thor reports a float like "81.04"; round to int (the BW
|
||||
# report uses an int for the column).
|
||||
hist_block["n_intervals"] = int(float(str(n_raw)))
|
||||
except ValueError:
|
||||
pass
|
||||
# When the binary decoder gave us the actual interval count, prefer it.
|
||||
if intervals is not None:
|
||||
hist_block["n_intervals"] = len(intervals)
|
||||
hist_block["interval_size"] = idf_report.get("interval_size")
|
||||
hist_block["interval_size_s"] = _parse_interval_size_s(idf_report.get("interval_size"))
|
||||
# interval_times derived from start+step (the BW report uses the
|
||||
# exact strings; we match its representation).
|
||||
times = _interval_times(idf_report, hist_block["n_intervals"])
|
||||
# Per-channel peak when (absolute date+time at which the channel's
|
||||
# peak occurred over the histogram run). Thor splits this into
|
||||
# ``TranPeakDate`` / ``TranPeakTime`` etc.
|
||||
peak_when: Dict[str, str] = {}
|
||||
for ch_label, ch_lc in (("Tran", "tran"), ("Vert", "vert"), ("Long", "long"), ("MicL", "mic")):
|
||||
d = idf_report.get(f"{ch_lc}_peak_date")
|
||||
t = idf_report.get(f"{ch_lc}_peak_time")
|
||||
if d and t:
|
||||
try:
|
||||
peak_when[ch_label] = datetime.datetime.strptime(
|
||||
f"{d} {t}", "%Y-%m-%d %H:%M:%S"
|
||||
).isoformat()
|
||||
except ValueError:
|
||||
continue
|
||||
if peak_when:
|
||||
hist_block["channel_peak_when"] = peak_when
|
||||
|
||||
# ── Mic block ────────────────────────────────────────────────────────
|
||||
mic_block = {
|
||||
"weighting": "L", # Thor mic is ISEE Linear
|
||||
"pspl_dbl": idf_report.get("mic_ppv"), # the dB(L) float
|
||||
"pspl_saturated": False,
|
||||
"zc_freq_hz": idf_report.get("mic_zc_freq"),
|
||||
"zc_freq_above_range": isinstance(idf_report.get("mic_zc_freq"), str)
|
||||
and ">" in str(idf_report.get("mic_zc_freq")),
|
||||
"time_of_peak_s": idf_report.get("mic_time_of_peak"),
|
||||
}
|
||||
if mic_block["zc_freq_above_range"]:
|
||||
mic_block["zc_freq_hz"] = None
|
||||
|
||||
# ── Peaks ────────────────────────────────────────────────────────────
|
||||
vs_block = {
|
||||
"ips": idf_report.get("peak_vector_sum"),
|
||||
"time_s": _parse_first_number(idf_report.get("peak_vector_sum_time_sum")),
|
||||
"when": None,
|
||||
"saturated": False,
|
||||
}
|
||||
if is_histogram:
|
||||
# PVS absolute date+time, when present.
|
||||
vs_d = idf_report.get("peak_vector_sum_date")
|
||||
vs_t = idf_report.get("peak_vector_sum_time")
|
||||
if vs_d and vs_t:
|
||||
try:
|
||||
vs_block["when"] = datetime.datetime.strptime(
|
||||
f"{vs_d} {vs_t}", "%Y-%m-%d %H:%M:%S"
|
||||
).isoformat()
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"event_type": idf_report.get("event_type"),
|
||||
"version": idf_report.get("version"),
|
||||
"trigger": {
|
||||
"channel": trigger_channel,
|
||||
"geo_level_ips": trigger_level,
|
||||
},
|
||||
"recording": {
|
||||
"sample_rate_sps": idf_report.get("sample_rate"),
|
||||
"record_time_s": idf_report.get("record_time_sec"),
|
||||
"pretrig_s": idf_report.get("pre_trigger_sec"),
|
||||
"stop_mode": idf_report.get("record_stop_mode"),
|
||||
"geo_range_ips": geo_range_ips,
|
||||
"units": idf_report.get("units"),
|
||||
},
|
||||
"device": {
|
||||
"battery_volts": idf_report.get("battery_volts"),
|
||||
"calibration_date": cal_iso,
|
||||
"calibration_by": cal_by,
|
||||
},
|
||||
"peaks": {
|
||||
"tran": _channel_peaks(idf_report, "tran"),
|
||||
"vert": _channel_peaks(idf_report, "vert"),
|
||||
"long": _channel_peaks(idf_report, "long"),
|
||||
"vector_sum": vs_block,
|
||||
},
|
||||
"mic": mic_block,
|
||||
"sensor_check": {
|
||||
"tran": _sensor_check(idf_report, "tran"),
|
||||
"vert": _sensor_check(idf_report, "vert"),
|
||||
"long": _sensor_check(idf_report, "long"),
|
||||
"mic": _sensor_check(idf_report, "mic"),
|
||||
},
|
||||
"histogram": hist_block,
|
||||
"monitor_log": [],
|
||||
"pc_sw_version": None,
|
||||
}
|
||||
+27
-6
@@ -159,12 +159,23 @@ class IdfReport:
|
||||
|
||||
@dataclass
|
||||
class IdfPeaks:
|
||||
"""Geophone + mic peak values for one Thor event. Native Thor units."""
|
||||
"""Geophone + mic peak values for one Thor event. Native Thor units.
|
||||
|
||||
Thor stores the mic peak in two parallel forms — ``mic_pspl_dbl`` is
|
||||
what the sidecar's top-level ``MicPSPL`` header field carries (dB(L)),
|
||||
used in the report header. ``mic_pspl_psi`` is the psi value derived
|
||||
either from the IDFW sample table / IDFH interval column 9, or from
|
||||
the binary mic counts (~2.14e-6 psi/count). Needed because the
|
||||
BW-shaped ``PeakValues.micl`` consumed by ``event_hdf5.write_event_hdf5``
|
||||
expects psi — feeding it dB(L) makes the h5 mic-chart scale factor
|
||||
blow up.
|
||||
"""
|
||||
transverse_ips: Optional[float] = None # in/s
|
||||
vertical_ips: Optional[float] = None # in/s
|
||||
longitudinal_ips: Optional[float] = None # in/s
|
||||
peak_vector_sum_ips: Optional[float] = None # in/s
|
||||
mic_pspl_dbl: Optional[float] = None # dB(L)
|
||||
mic_pspl_psi: Optional[float] = None # psi
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -324,10 +335,14 @@ class IdfEvent:
|
||||
machinery without those code paths needing to know about Thor.
|
||||
|
||||
Caveats of the bridge:
|
||||
- ``mic_ppv`` on the produced Event carries Thor's dB(L) value
|
||||
verbatim — the UI distinguishes via the ``device_family``
|
||||
column (Phase 1). Don't run the BW psi→dBL converter on
|
||||
Series IV rows.
|
||||
- ``PeakValues.micl`` carries the mic peak in **psi** (matching
|
||||
BW's convention) — set from :attr:`IdfPeaks.mic_pspl_psi`,
|
||||
with a dB(L)→psi fallback when only the dB(L) value is
|
||||
available. This is what the h5 writer's mic-scale-factor
|
||||
logic needs. The dB(L) value still flows through
|
||||
``bw_report.mic.pspl_dbl`` (set by the
|
||||
``idf_to_bw_report`` adapter) and the renderer reads it
|
||||
from there for the report header.
|
||||
- Many Thor-specific fields (Peak Acceleration / Displacement,
|
||||
sensor self-check, calibration) don't have a slot in
|
||||
``Event``. The full IdfReport is preserved on the
|
||||
@@ -349,11 +364,17 @@ class IdfEvent:
|
||||
minute=self.timestamp.minute,
|
||||
second=self.timestamp.second,
|
||||
)
|
||||
# Resolve mic peak as psi. Priority: binary-derived mic_pspl_psi
|
||||
# (set by read_idf_file) > dB(L)→psi fallback via standard formula
|
||||
# (psi = 2.9e-9 × 10^(dBL/20)) > None.
|
||||
mic_psi = self.peaks.mic_pspl_psi
|
||||
if mic_psi is None and self.peaks.mic_pspl_dbl is not None:
|
||||
mic_psi = 2.9e-9 * (10.0 ** (self.peaks.mic_pspl_dbl / 20.0))
|
||||
pv = PeakValues(
|
||||
tran=self.peaks.transverse_ips,
|
||||
vert=self.peaks.vertical_ips,
|
||||
long=self.peaks.longitudinal_ips,
|
||||
micl=self.peaks.mic_pspl_dbl, # dB(L) — see caveat above
|
||||
micl=mic_psi, # psi, matching BW's convention (h5 scaling depends on this)
|
||||
peak_vector_sum=self.peaks.peak_vector_sum_ips,
|
||||
)
|
||||
pi = ProjectInfo(
|
||||
|
||||
+227
-11
@@ -60,6 +60,18 @@ class ChannelStats:
|
||||
time_of_peak_s: Optional[float] = None # seconds (relative to trigger; can be negative)
|
||||
peak_accel_g: Optional[float] = None # g (geo channels only)
|
||||
peak_disp_in: Optional[float] = None # in (geo channels only)
|
||||
# When BW writes "OORANGE" (Out Of Range — truncated) for a PPV
|
||||
# value, the true peak exceeded the channel's full-scale range.
|
||||
# We substitute the range max (e.g. 10.000 in/s for Normal range)
|
||||
# as a lower bound, and flag here so downstream UI / alerts know
|
||||
# to render "> 10 in/s" or "saturated" instead of trusting the
|
||||
# value as an exact measurement.
|
||||
ppv_saturated: bool = False
|
||||
# Set when BW writes ">100 Hz" for ZC Freq — the zero-crossing
|
||||
# algorithm's peak frequency exceeded the device's reporting
|
||||
# ceiling (typically 100 Hz on V10.72). zc_freq_hz gets the
|
||||
# threshold (100.0) as a lower bound; downstream UI renders ">100".
|
||||
zc_freq_above_range: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -69,6 +81,14 @@ class MicStats:
|
||||
pspl_dbl: Optional[float] = None # dB(L)
|
||||
zc_freq_hz: Optional[float] = None
|
||||
time_of_peak_s: Optional[float] = None
|
||||
# Set when BW writes "OORANGE" for PSPL — mic exceeded its
|
||||
# measurement range. pspl_dbl gets the conservative upper bound
|
||||
# 140 dBL (typical NL-43 max; some units cap at 148). Consumers
|
||||
# should render "> 140 dB(L)" or similar when this flag is set.
|
||||
pspl_saturated: bool = False
|
||||
# Same semantics as ChannelStats.zc_freq_above_range — mic ZC
|
||||
# peak exceeded device reporting ceiling.
|
||||
zc_freq_above_range: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -92,6 +112,35 @@ class MonitorLogEntry:
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
# BW saturation marker — appears in PPV / Peak Vector Sum / similar
|
||||
# numeric fields when the underlying measurement exceeded the
|
||||
# channel's full-scale range (e.g., a geophone reading > 10 in/s at
|
||||
# Normal range, or a mic exceeding its sensitivity ceiling). Treated
|
||||
# as "≥ range_max" + a saturated flag rather than discarded.
|
||||
# Appears as: ``"Tran PPV : OORANGE in/s"``
|
||||
_OORANGE_MARKERS = ("OORANGE", "OUT OF RANGE")
|
||||
|
||||
|
||||
def _is_oorange(value: str) -> bool:
|
||||
"""True when a BW numeric field is an Out-Of-Range saturation marker."""
|
||||
s = value.strip().upper()
|
||||
return any(m in s for m in _OORANGE_MARKERS)
|
||||
|
||||
|
||||
def _parse_above_range(value: str) -> Optional[float]:
|
||||
"""For BW "above-range" markers like ">100 Hz", return the threshold.
|
||||
|
||||
BW writes ZC Freq as ">100 Hz" when the zero-crossing algorithm sees
|
||||
a peak too fast to count (device cuts off at 100 Hz). Returns the
|
||||
numeric portion after the '>' (e.g. 100.0), or None if `value` is
|
||||
not an above-range marker.
|
||||
"""
|
||||
s = value.strip()
|
||||
if not s.startswith(">"):
|
||||
return None
|
||||
return _parse_number(s[1:])
|
||||
|
||||
|
||||
@dataclass
|
||||
class BwAsciiReport:
|
||||
"""Structured representation of one BW per-event ASCII export."""
|
||||
@@ -144,6 +193,29 @@ class BwAsciiReport:
|
||||
# ── Vector sum ──────────────────────────────────────────────────────────
|
||||
peak_vector_sum_ips: Optional[float] = None
|
||||
peak_vector_sum_time_s: Optional[float] = None
|
||||
# Saturation flag — set when BW writes "OORANGE" for the PVS. We
|
||||
# then substitute sqrt(3) * geo_range_ips as a conservative upper
|
||||
# bound (the theoretical maximum PVS when all 3 geo channels are
|
||||
# simultaneously at full-scale). Consumers should display this as
|
||||
# ">{value} in/s" or similar.
|
||||
peak_vector_sum_saturated: bool = False
|
||||
# Histograms additionally have an absolute date+time for the PVS
|
||||
# (it occurred at a specific interval). Waveform reports show
|
||||
# only the relative-time value above.
|
||||
peak_vector_sum_when: Optional[datetime.datetime] = None
|
||||
|
||||
# ── Histogram-specific fields (populated only when Event Type starts
|
||||
# with 'Histogram' / 'Full Histogram' / 'Histogram + Continuous') ──
|
||||
histogram_start: Optional[datetime.datetime] = None
|
||||
histogram_stop: Optional[datetime.datetime] = None
|
||||
histogram_n_intervals: Optional[int] = None # e.g. 4, 1436
|
||||
histogram_interval_size_str: Optional[str] = None # "1 minute" / "5 minutes" / "15 seconds"
|
||||
histogram_interval_size_s: Optional[float] = None # parsed to seconds
|
||||
# Per-channel absolute peak time+date (histogram-specific). For
|
||||
# waveform events these are None — those reports use the channel's
|
||||
# time_of_peak_s (relative to trigger) instead. Keyed by channel
|
||||
# name ("Tran", "Vert", "Long", "MicL").
|
||||
channel_peak_when: Dict[str, datetime.datetime] = field(default_factory=dict)
|
||||
|
||||
# ── Sensor self-check (per channel) ─────────────────────────────────────
|
||||
sensor_check: Dict[str, SensorCheck] = field(default_factory=dict)
|
||||
@@ -223,6 +295,46 @@ def _parse_event_date(s: str) -> Optional[datetime.date]:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_iso_date(s: str) -> Optional[datetime.date]:
|
||||
"""Parse "2026-05-16" → date. Histograms use ISO format for their
|
||||
Start Date / Stop Date / Peak Date fields; waveforms use the
|
||||
"May 8, 2026" long form which `_parse_event_date` handles."""
|
||||
s = s.strip()
|
||||
try:
|
||||
return datetime.date.fromisoformat(s)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
_INTERVAL_UNIT_SECONDS = {
|
||||
"second": 1, "seconds": 1, "sec": 1, "secs": 1,
|
||||
"minute": 60, "minutes": 60, "min": 60, "mins": 60,
|
||||
"hour": 3600, "hours": 3600, "hr": 3600, "hrs": 3600,
|
||||
}
|
||||
|
||||
|
||||
def _parse_interval_size(s: str) -> Optional[float]:
|
||||
"""Parse "1 minute" / "5 minutes" / "15 seconds" / "2 seconds" → seconds.
|
||||
|
||||
Handles the BW Compliance Setup → Histogram Interval values verbatim
|
||||
("2 seconds", "5 seconds", "15 seconds", "1 minute", "5 minutes",
|
||||
"15 minutes") plus a few defensive variants.
|
||||
"""
|
||||
if not s:
|
||||
return None
|
||||
parts = s.strip().split()
|
||||
if len(parts) < 2:
|
||||
return None
|
||||
try:
|
||||
n = float(parts[0])
|
||||
except ValueError:
|
||||
return None
|
||||
unit_per_s = _INTERVAL_UNIT_SECONDS.get(parts[1].lower())
|
||||
if unit_per_s is None:
|
||||
return None
|
||||
return n * unit_per_s
|
||||
|
||||
|
||||
def _parse_event_time(s: str) -> Optional[datetime.time]:
|
||||
"""Parse "15:56:35" → time."""
|
||||
s = s.strip()
|
||||
@@ -336,6 +448,15 @@ def parse_report(text: Union[str, bytes], *, parse_samples: bool = False) -> BwA
|
||||
in_user_notes_block = False
|
||||
user_note_position = 0
|
||||
|
||||
# Histogram-field staging — BW writes <Channel> Peak Time and
|
||||
# <Channel> Peak Date on separate lines (and similarly Histogram
|
||||
# Start Time / Date). We stash the partial value when the time
|
||||
# line arrives and combine it when the matching date line arrives.
|
||||
_hist_start_time: Optional[datetime.time] = None
|
||||
_hist_stop_time: Optional[datetime.time] = None
|
||||
_pending_peak_time: Dict[str, Optional[datetime.time]] = {}
|
||||
_pvs_time_raw: Optional[str] = None # last Peak Vector Sum Time value, raw
|
||||
|
||||
while i < n:
|
||||
raw_line = lines[i]
|
||||
i += 1
|
||||
@@ -420,24 +541,113 @@ def parse_report(text: Union[str, bytes], *, parse_samples: bool = False) -> BwA
|
||||
):
|
||||
ch_name, stat = key.split(" ", 1)
|
||||
cs = report.channels.setdefault(ch_name, ChannelStats())
|
||||
num = _parse_number(value)
|
||||
if stat == "PPV": cs.ppv_ips = num
|
||||
elif stat == "ZC Freq": cs.zc_freq_hz = num
|
||||
elif stat == "Time of Peak": cs.time_of_peak_s = num
|
||||
elif stat == "Peak Acceleration": cs.peak_accel_g = num
|
||||
elif stat == "Peak Displacement": cs.peak_disp_in = num
|
||||
if stat == "PPV":
|
||||
if _is_oorange(value):
|
||||
# Channel saturated — substitute range max as lower
|
||||
# bound; flag so downstream UI can render "> 10 in/s".
|
||||
cs.ppv_ips = report.geo_range_ips
|
||||
cs.ppv_saturated = True
|
||||
else:
|
||||
cs.ppv_ips = _parse_number(value)
|
||||
elif stat == "ZC Freq":
|
||||
# ">100 Hz" → store threshold + flag; numeric → parse normally
|
||||
threshold = _parse_above_range(value)
|
||||
if threshold is not None:
|
||||
cs.zc_freq_hz = threshold
|
||||
cs.zc_freq_above_range = True
|
||||
else:
|
||||
cs.zc_freq_hz = _parse_number(value)
|
||||
else:
|
||||
num = _parse_number(value)
|
||||
if stat == "Time of Peak": cs.time_of_peak_s = num
|
||||
elif stat == "Peak Acceleration": cs.peak_accel_g = num
|
||||
elif stat == "Peak Displacement": cs.peak_disp_in = num
|
||||
|
||||
# ── Histogram-specific fields ────────────────────────────────────────
|
||||
# Histograms have Start/Stop time+date pairs + an interval count
|
||||
# and size, plus per-channel absolute Peak Time/Date instead of
|
||||
# the waveform's relative Time of Peak.
|
||||
elif key == "Histogram Start Time":
|
||||
_hist_start_time = _parse_event_time(value)
|
||||
elif key == "Histogram Start Date":
|
||||
_d = _parse_iso_date(value)
|
||||
if _d and _hist_start_time:
|
||||
report.histogram_start = datetime.datetime.combine(_d, _hist_start_time)
|
||||
elif key == "Histogram Stop Time":
|
||||
_hist_stop_time = _parse_event_time(value)
|
||||
elif key == "Histogram Stop Date":
|
||||
_d = _parse_iso_date(value)
|
||||
if _d and _hist_stop_time:
|
||||
report.histogram_stop = datetime.datetime.combine(_d, _hist_stop_time)
|
||||
elif key == "Number of Intervals":
|
||||
try:
|
||||
report.histogram_n_intervals = int(float(value.strip()))
|
||||
except ValueError:
|
||||
pass
|
||||
elif key == "Interval Size":
|
||||
report.histogram_interval_size_str = value.strip()
|
||||
report.histogram_interval_size_s = _parse_interval_size(value)
|
||||
|
||||
# ── Per-channel histogram Peak Date / Peak Time ──
|
||||
# Lines like "Tran Peak Time : 22:31:38" + "Tran Peak Date : 2026-05-16"
|
||||
elif key in ("Tran Peak Time", "Vert Peak Time", "Long Peak Time", "MicL Time"):
|
||||
ch_name = "MicL" if key == "MicL Time" else key.split(" ", 1)[0]
|
||||
_pending_peak_time[ch_name] = _parse_event_time(value)
|
||||
elif key in ("Tran Peak Date", "Vert Peak Date", "Long Peak Date", "MicL Date"):
|
||||
ch_name = "MicL" if key == "MicL Date" else key.split(" ", 1)[0]
|
||||
_d = _parse_iso_date(value)
|
||||
_t = _pending_peak_time.get(ch_name)
|
||||
if _d and _t:
|
||||
report.channel_peak_when[ch_name] = datetime.datetime.combine(_d, _t)
|
||||
|
||||
# ── Vector Sum ───────────────────────────────────────────────────────
|
||||
elif key == "Peak Vector Sum":
|
||||
report.peak_vector_sum_ips = _parse_number(value)
|
||||
elif key == "Peak Vector Sum Time":
|
||||
if _is_oorange(value):
|
||||
# PVS saturated — conservative upper bound is
|
||||
# sqrt(3) * geo_range_ips (all 3 channels at full-scale).
|
||||
# Real PVS could be lower (channels rarely peak
|
||||
# simultaneously) but never higher within the range.
|
||||
if report.geo_range_ips is not None:
|
||||
import math as _math
|
||||
report.peak_vector_sum_ips = _math.sqrt(3) * report.geo_range_ips
|
||||
report.peak_vector_sum_saturated = True
|
||||
else:
|
||||
report.peak_vector_sum_ips = _parse_number(value)
|
||||
# BW writes the PVS-time label with a typo: "Peak Vector Sum TimeSum"
|
||||
# (looks like Sum got appended twice). Accept both forms. Confirmed
|
||||
# against actual BW output on 2026-05-27 — every PVS-time line in
|
||||
# the field examples (T190, T438, K557) uses the typo'd label.
|
||||
elif key in ("Peak Vector Sum Time", "Peak Vector Sum TimeSum"):
|
||||
report.peak_vector_sum_time_s = _parse_number(value)
|
||||
_pvs_time_raw = value
|
||||
elif key == "Peak Vector Sum Date":
|
||||
# Histogram-mode PVS gets paired with a date. We may have
|
||||
# captured 'Peak Vector Sum Time' as either a relative
|
||||
# seconds float (waveform) or an HH:MM:SS string we
|
||||
# interpreted as a number. For histograms, BW writes
|
||||
# "Peak Vector Sum Time : 22:33:52" which _parse_number
|
||||
# parses as 22.0 (loses information). When Peak Vector Sum
|
||||
# Date arrives, re-parse the previous PVS time line as a
|
||||
# clock time and combine into an absolute datetime.
|
||||
_d = _parse_iso_date(value)
|
||||
if _d and _pvs_time_raw is not None:
|
||||
_t = _parse_event_time(_pvs_time_raw)
|
||||
if _t:
|
||||
report.peak_vector_sum_when = datetime.datetime.combine(_d, _t)
|
||||
# The earlier seconds parse was bogus for histograms;
|
||||
# clear it so consumers don't think it's a real offset.
|
||||
report.peak_vector_sum_time_s = None
|
||||
|
||||
# ── Microphone block ────────────────────────────────────────────────
|
||||
elif key == "Microphone":
|
||||
report.mic.weighting = value
|
||||
elif key == "MicL PSPL":
|
||||
report.mic.pspl_dbl = _parse_number(value)
|
||||
if _is_oorange(value):
|
||||
# Mic saturated — substitute conservative upper bound 140 dBL.
|
||||
report.mic.pspl_dbl = 140.0
|
||||
report.mic.pspl_saturated = True
|
||||
else:
|
||||
report.mic.pspl_dbl = _parse_number(value)
|
||||
# Mirror onto the "MicL" entry in channels so callers querying
|
||||
# `channels["MicL"].ppv_ips` see something — but it's dB(L), not
|
||||
# in/s, so we store as-is in the MicStats and mark the channel.
|
||||
@@ -446,9 +656,15 @@ def parse_report(text: Union[str, bytes], *, parse_samples: bool = False) -> BwA
|
||||
cs = report.channels.setdefault("MicL", ChannelStats())
|
||||
cs.time_of_peak_s = report.mic.time_of_peak_s
|
||||
elif key == "MicL ZC Freq":
|
||||
report.mic.zc_freq_hz = _parse_number(value)
|
||||
threshold = _parse_above_range(value)
|
||||
if threshold is not None:
|
||||
report.mic.zc_freq_hz = threshold
|
||||
report.mic.zc_freq_above_range = True
|
||||
else:
|
||||
report.mic.zc_freq_hz = _parse_number(value)
|
||||
cs = report.channels.setdefault("MicL", ChannelStats())
|
||||
cs.zc_freq_hz = report.mic.zc_freq_hz
|
||||
cs.zc_freq_hz = report.mic.zc_freq_hz
|
||||
cs.zc_freq_above_range = report.mic.zc_freq_above_range
|
||||
|
||||
# ── Sensor self-check ────────────────────────────────────────────────
|
||||
elif key in (
|
||||
|
||||
+197
-19
@@ -27,6 +27,9 @@ from typing import Optional, Union
|
||||
from .models import Event, PeakValues, ProjectInfo, Timestamp
|
||||
from . import blastware_file as _bw # avoid circular reference at module load
|
||||
from .bw_ascii_report import BwAsciiReport
|
||||
from . import waveform_codec as _wc
|
||||
from .waveform_codec import decode_waveform_v2, decoded_to_adc_counts
|
||||
from .histogram_codec import decode_histogram_body
|
||||
|
||||
# Reference pressure for dB(L) → psi conversion (20 µPa expressed in psi).
|
||||
# Same constant as sfm/sfm_webapp.html so server-side and browser-side
|
||||
@@ -47,7 +50,7 @@ SIDECAR_KIND = "sfm.event"
|
||||
# bumped without a `pip install` re-run — leading to confusing stale
|
||||
# version stamps in sidecars. Bump this constant and CHANGELOG.md
|
||||
# together at release time.
|
||||
TOOL_VERSION = "0.16.1"
|
||||
TOOL_VERSION = "0.26.0"
|
||||
|
||||
try:
|
||||
# Best-effort: prefer the installed metadata when it's NEWER than the
|
||||
@@ -118,7 +121,16 @@ def _bw_report_to_dict(report: BwAsciiReport) -> dict:
|
||||
"peak_disp_in": cs.peak_disp_in,
|
||||
}
|
||||
# Drop all-None entries — keeps the JSON tidy for partial reports.
|
||||
return {k: v for k, v in out.items() if v is not None}
|
||||
out = {k: v for k, v in out.items() if v is not None}
|
||||
# Saturation flag (only present when True) — signals that ppv_ips
|
||||
# is the channel range max (a lower bound), not an exact reading.
|
||||
if getattr(cs, "ppv_saturated", False):
|
||||
out["ppv_saturated"] = True
|
||||
# ZC Freq above device reporting ceiling (BW ">100 Hz") — value
|
||||
# in zc_freq_hz is the threshold, not an exact measurement.
|
||||
if getattr(cs, "zc_freq_above_range", False):
|
||||
out["zc_freq_above_range"] = True
|
||||
return out
|
||||
|
||||
def _sc(ch_name: str) -> dict:
|
||||
sc = report.sensor_check.get(ch_name)
|
||||
@@ -167,15 +179,25 @@ def _bw_report_to_dict(report: BwAsciiReport) -> dict:
|
||||
"vert": _ch("Vert"),
|
||||
"long": _ch("Long"),
|
||||
"vector_sum": {
|
||||
"ips": report.peak_vector_sum_ips,
|
||||
"time_s": report.peak_vector_sum_time_s,
|
||||
"ips": report.peak_vector_sum_ips,
|
||||
"time_s": report.peak_vector_sum_time_s,
|
||||
# Histogram events have an absolute date+time for the PVS
|
||||
# (the interval at which it occurred); waveform events
|
||||
# only have the time_s offset.
|
||||
"when": report.peak_vector_sum_when.isoformat() if report.peak_vector_sum_when else None,
|
||||
# Set when BW reported the PVS as OORANGE — value is the
|
||||
# conservative upper bound sqrt(3) * geo_range_ips, not
|
||||
# an exact peak.
|
||||
"saturated": bool(getattr(report, "peak_vector_sum_saturated", False)),
|
||||
},
|
||||
},
|
||||
"mic": {
|
||||
"weighting": report.mic.weighting,
|
||||
"pspl_dbl": report.mic.pspl_dbl,
|
||||
"zc_freq_hz": report.mic.zc_freq_hz,
|
||||
"time_of_peak_s": report.mic.time_of_peak_s,
|
||||
"weighting": report.mic.weighting,
|
||||
"pspl_dbl": report.mic.pspl_dbl,
|
||||
"pspl_saturated": bool(getattr(report.mic, "pspl_saturated", False)),
|
||||
"zc_freq_hz": report.mic.zc_freq_hz,
|
||||
"zc_freq_above_range": bool(getattr(report.mic, "zc_freq_above_range", False)),
|
||||
"time_of_peak_s": report.mic.time_of_peak_s,
|
||||
},
|
||||
"sensor_check": {
|
||||
"tran": _sc("Tran"),
|
||||
@@ -183,6 +205,17 @@ def _bw_report_to_dict(report: BwAsciiReport) -> dict:
|
||||
"long": _sc("Long"),
|
||||
"mic": _sc("MicL"),
|
||||
},
|
||||
# Histogram-specific fields (None on waveform-mode events).
|
||||
# Per-channel absolute peak time/date for histograms — for
|
||||
# waveforms see channels[ch]["time_of_peak_s"] instead.
|
||||
"histogram": {
|
||||
"start": report.histogram_start.isoformat() if report.histogram_start else None,
|
||||
"stop": report.histogram_stop.isoformat() if report.histogram_stop else None,
|
||||
"n_intervals": report.histogram_n_intervals,
|
||||
"interval_size": report.histogram_interval_size_str,
|
||||
"interval_size_s": report.histogram_interval_size_s,
|
||||
"channel_peak_when": {ch: dt.isoformat() for ch, dt in report.channel_peak_when.items()},
|
||||
},
|
||||
"monitor_log": monitor_log,
|
||||
"pc_sw_version": report.pc_sw_version,
|
||||
}
|
||||
@@ -238,6 +271,19 @@ def apply_report_to_event(event: Event, report: BwAsciiReport) -> None:
|
||||
if report.mic.pspl_dbl is not None and report.mic.pspl_dbl > 0:
|
||||
pv.micl = _dbl_to_psi(report.mic.pspl_dbl)
|
||||
|
||||
if (t := ch.get("Tran")):
|
||||
pv.tran_zc_freq = t.zc_freq_hz
|
||||
pv.tran_zc_above_range = bool(getattr(t, "zc_freq_above_range", False))
|
||||
if (v := ch.get("Vert")):
|
||||
pv.vert_zc_freq = v.zc_freq_hz
|
||||
pv.vert_zc_above_range = bool(getattr(v, "zc_freq_above_range", False))
|
||||
if (l := ch.get("Long")):
|
||||
pv.long_zc_freq = l.zc_freq_hz
|
||||
pv.long_zc_above_range = bool(getattr(l, "zc_freq_above_range", False))
|
||||
if report.mic is not None:
|
||||
pv.mic_zc_freq = report.mic.zc_freq_hz
|
||||
pv.mic_zc_above_range = bool(getattr(report.mic, "zc_freq_above_range", False))
|
||||
|
||||
if event.project_info is None:
|
||||
event.project_info = ProjectInfo()
|
||||
pi = event.project_info
|
||||
@@ -252,6 +298,71 @@ def apply_report_to_event(event: Event, report: BwAsciiReport) -> None:
|
||||
event.rectime_seconds = report.record_time_s
|
||||
|
||||
|
||||
def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
|
||||
"""Mirror of ``apply_report_to_event`` for the projected sidecar
|
||||
dict shape (as produced by ``_bw_report_to_dict``).
|
||||
|
||||
Why this exists
|
||||
───────────────
|
||||
The ingest path holds a live ``BwAsciiReport`` parsed straight from
|
||||
the ``_ASCII.TXT`` and uses ``apply_report_to_event`` to overlay
|
||||
device-authoritative peaks onto the codec output before insert.
|
||||
|
||||
The backfill path doesn't have the original ``.TXT`` (it's not
|
||||
retained in the waveform store), but it does have the preserved
|
||||
``bw_report`` block from the sidecar — which contains the same
|
||||
projected fields. Re-overlaying those during a backfill keeps the
|
||||
DB peak columns aligned with what BW reports rather than letting
|
||||
the codec output (which may be incomplete for unhandled formats or
|
||||
walker edge cases) win by default.
|
||||
|
||||
No-ops cleanly when ``bw_report`` is ``None``, empty, or missing
|
||||
any particular sub-field — only fields with a concrete value get
|
||||
written. Mirrors ``apply_report_to_event``'s "report wins where
|
||||
present" semantics.
|
||||
"""
|
||||
if not bw_report:
|
||||
return
|
||||
if event.peak_values is None:
|
||||
event.peak_values = PeakValues()
|
||||
pv = event.peak_values
|
||||
|
||||
peaks = bw_report.get("peaks") or {}
|
||||
tran = (peaks.get("tran") or {}).get("ppv_ips")
|
||||
vert = (peaks.get("vert") or {}).get("ppv_ips")
|
||||
long = (peaks.get("long") or {}).get("ppv_ips")
|
||||
if tran is not None: pv.tran = tran
|
||||
if vert is not None: pv.vert = vert
|
||||
if long is not None: pv.long = long
|
||||
vs_ips = (peaks.get("vector_sum") or {}).get("ips")
|
||||
if vs_ips is not None:
|
||||
pv.peak_vector_sum = vs_ips
|
||||
|
||||
mic = bw_report.get("mic") or {}
|
||||
pspl = mic.get("pspl_dbl")
|
||||
if pspl is not None and pspl > 0:
|
||||
pv.micl = _dbl_to_psi(pspl)
|
||||
|
||||
for axis, freq_attr, above_attr in (
|
||||
("tran", "tran_zc_freq", "tran_zc_above_range"),
|
||||
("vert", "vert_zc_freq", "vert_zc_above_range"),
|
||||
("long", "long_zc_freq", "long_zc_above_range"),
|
||||
):
|
||||
chd = peaks.get(axis) or {}
|
||||
setattr(pv, freq_attr, chd.get("zc_freq_hz"))
|
||||
setattr(pv, above_attr, bool(chd.get("zc_freq_above_range", False)))
|
||||
pv.mic_zc_freq = mic.get("zc_freq_hz")
|
||||
pv.mic_zc_above_range = bool(mic.get("zc_freq_above_range", False))
|
||||
|
||||
rec = bw_report.get("recording") or {}
|
||||
sr = rec.get("sample_rate_sps")
|
||||
if sr:
|
||||
event.sample_rate = sr
|
||||
rt = rec.get("record_time_s")
|
||||
if rt is not None:
|
||||
event.rectime_seconds = rt
|
||||
|
||||
|
||||
def _project_info_to_dict(pi: Optional[ProjectInfo]) -> dict:
|
||||
if pi is None:
|
||||
return {
|
||||
@@ -276,6 +387,7 @@ def event_to_sidecar_dict(
|
||||
blastware_filesize: int,
|
||||
blastware_sha256: str,
|
||||
source_kind: str = "sfm-live",
|
||||
txt_filename: Optional[str] = None,
|
||||
a5_pickle_filename: Optional[str] = None,
|
||||
tool_version: str = _TOOL_VERSION_DEFAULT,
|
||||
captured_at: Optional[datetime.datetime] = None,
|
||||
@@ -392,6 +504,7 @@ def event_to_sidecar_dict(
|
||||
"captured_at": captured_at.isoformat() + "Z" if captured_at.tzinfo is None else captured_at.isoformat(),
|
||||
"tool_version": tool_version,
|
||||
"a5_pickle_filename": a5_pickle_filename,
|
||||
"txt_filename": txt_filename,
|
||||
},
|
||||
|
||||
"review": review or {
|
||||
@@ -547,6 +660,11 @@ def file_sha256(path: Union[str, Path], chunk_size: int = 65536) -> str:
|
||||
_GEO_NORMAL_FS_INS = 10.0
|
||||
_GEO_SENSITIVE_FS_INS = 1.250
|
||||
_INT16_FS = 32768.0
|
||||
# Geophone full-scale count — 32000, not 32768. One decoder unit (16 ADC
|
||||
# counts) is exactly 0.005 in/s, so 10.000 in/s = 32000 counts. Must match
|
||||
# sfm.event_hdf5._GEO_INT16_FS or sidecar peaks disagree with the plotted
|
||||
# waveform by 2.3%. Confirmed 2026-08-25 against the BW ASCII corpus.
|
||||
_GEO_INT16_FS = 32000.0
|
||||
|
||||
# Microphone scale factor, psi per ADC count. Approximate — exact factor
|
||||
# depends on the geophone-vs-mic ADC scaling and the firmware reference.
|
||||
@@ -616,7 +734,7 @@ def _peaks_from_samples(samples: dict[str, list[int]]) -> PeakValues:
|
||||
if not ch:
|
||||
return 0.0
|
||||
m = max(abs(int(v)) for v in ch)
|
||||
return m / _INT16_FS * _GEO_NORMAL_FS_INS
|
||||
return m / _GEO_INT16_FS * _GEO_NORMAL_FS_INS
|
||||
|
||||
tran = _peak_ins(samples.get("Tran", []))
|
||||
vert = _peak_ins(samples.get("Vert", []))
|
||||
@@ -630,7 +748,7 @@ def _peaks_from_samples(samples: dict[str, list[int]]) -> PeakValues:
|
||||
pvs = 0.0
|
||||
n = min(len(samples.get("Tran", [])), len(samples.get("Vert", [])), len(samples.get("Long", [])))
|
||||
if n:
|
||||
scale = _GEO_NORMAL_FS_INS / _INT16_FS
|
||||
scale = _GEO_NORMAL_FS_INS / _GEO_INT16_FS
|
||||
T = samples["Tran"]; V = samples["Vert"]; L = samples["Long"]
|
||||
for i in range(n):
|
||||
t = T[i] * scale
|
||||
@@ -726,7 +844,13 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
|
||||
|
||||
# Footer: locate the 0e 08 marker, validating the year is in a sane range.
|
||||
body_start = _bw._WAVEFORM_HEADER_SIZE + 21
|
||||
footer_pos = -1
|
||||
# The 0e 08 + plausible-year footer signature can occur inside the sample
|
||||
# stream. Collect every candidate and prefer the first whose body yields a
|
||||
# waveform record chain terminating on the 0x06 marker; fall back to the
|
||||
# first candidate otherwise. Blast radius measured 2026-08-25: changes the
|
||||
# chosen footer on exactly 1 of 1,388 series-3 waveform files
|
||||
# (BE17353/S353L4O5.OX0W, false positive at 3800, real footer at 8576).
|
||||
footer_candidates = []
|
||||
pos = body_start
|
||||
while True:
|
||||
pos = raw.find(b"\x0e\x08", pos)
|
||||
@@ -734,10 +858,24 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
|
||||
break
|
||||
yr = (raw[pos + 4] << 8) | raw[pos + 5]
|
||||
if 2015 <= yr <= 2050:
|
||||
footer_pos = pos
|
||||
break
|
||||
footer_candidates.append(pos)
|
||||
pos += 1
|
||||
|
||||
footer_pos = -1
|
||||
for cand in footer_candidates:
|
||||
cand_body = raw[body_start:cand]
|
||||
try:
|
||||
recs = _wc.walk_records(cand_body)
|
||||
except Exception:
|
||||
recs = []
|
||||
if recs:
|
||||
tail = recs[-1]["end"]
|
||||
if tail + 5 <= len(cand_body) and cand_body[tail + 4] == _wc.STREAM_END_ID:
|
||||
footer_pos = cand
|
||||
break
|
||||
if footer_pos < 0 and footer_candidates:
|
||||
footer_pos = footer_candidates[0]
|
||||
|
||||
if footer_pos < 0 and len(raw) >= 26:
|
||||
footer_pos = len(raw) - 26
|
||||
if footer_pos < body_start:
|
||||
@@ -755,11 +893,40 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
|
||||
ts1 = _bw._decode_ts_be(footer[2:10])
|
||||
ts2 = _bw._decode_ts_be(footer[10:18])
|
||||
|
||||
# Body: first 6 bytes are the preamble (00 00 ff ff ff ff). Strip
|
||||
# them before decoding samples. Any trailing tail past the last
|
||||
# full sample-set is silently truncated by _decode_samples_4ch.
|
||||
sample_bytes = body[6:] if body[:6].hex() in ("0000ffffffff", "0000FFFFFFFF") else body
|
||||
samples = _decode_samples_4ch_int16_le(sample_bytes)
|
||||
# Body: decode via the verified body codecs. Two formats coexist:
|
||||
#
|
||||
# 1. Waveform-mode (.AB0W) — starts with 7-byte preamble
|
||||
# ``00 02 00 [Tran[0] BE] [Tran[1] BE]`` followed by the
|
||||
# tagged-block delta stream documented in
|
||||
# ``docs/waveform_codec_re_status.md`` and §7.6.1 of the
|
||||
# protocol reference. Decoded by ``waveform_codec.decode_waveform_v2``.
|
||||
#
|
||||
# 2. Histogram-mode (.AB0H) — a sequence of 32-byte blocks, one
|
||||
# per histogram interval, each carrying per-channel peak +
|
||||
# half-period values. Decoded by
|
||||
# ``histogram_codec.decode_histogram_body``. Both codecs
|
||||
# return the same channel-grouped output shape, so consumers
|
||||
# don't need to special-case mode.
|
||||
#
|
||||
# The historical ``_decode_samples_4ch_int16_le`` int16-LE
|
||||
# interpretation was retracted 2026-05-08 (see protocol-ref §7.6.1
|
||||
# retraction box) — it produced ±32K noise on every event.
|
||||
#
|
||||
# If both codecs fail (malformed file, truncated body, unrecognised
|
||||
# mode, synthetic test input), fall back to empty channels — the
|
||||
# rest of the event (timestamp, waveform_key, project strings) is
|
||||
# still recoverable and useful.
|
||||
decoded = decode_waveform_v2(body)
|
||||
if decoded is None:
|
||||
decoded = decode_histogram_body(body)
|
||||
if decoded is None:
|
||||
log.warning(
|
||||
"%s: body codec failed to decode (body starts %s) — "
|
||||
"raw_samples will be empty", path, body[:8].hex(" "),
|
||||
)
|
||||
samples = {"Tran": [], "Vert": [], "Long": [], "MicL": []}
|
||||
else:
|
||||
samples = decoded_to_adc_counts(decoded)
|
||||
|
||||
# Metadata strings (label-anchored search across the body).
|
||||
project = _find_first_string(body, b"Project:")
|
||||
@@ -793,7 +960,18 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
|
||||
project=project, client=client, operator=user, sensor_location=seisloc,
|
||||
)
|
||||
ev.raw_samples = samples
|
||||
ev.peak_values = _peaks_from_samples(samples)
|
||||
# Only compute peaks from samples when we actually have samples.
|
||||
# For events the codec couldn't decode (histogram-mode bodies, until
|
||||
# the §7.6.2 histogram codec is wired in), samples is an empty dict
|
||||
# and ``_peaks_from_samples`` would return PeakValues(0, 0, 0, 0, 0).
|
||||
# That would then OVERWRITE existing good DB peak values (e.g. from
|
||||
# paired BW ASCII reports) during the backfill UPSERT path.
|
||||
# Leaving peak_values=None signals "we don't know" to downstream
|
||||
# consumers; the backfill script seeds from the DB row when it sees
|
||||
# None, and ``apply_report_to_event`` overlays from a paired ASCII
|
||||
# report when one is supplied.
|
||||
has_samples = any(samples.get(ch) for ch in ("Tran", "Vert", "Long", "MicL"))
|
||||
ev.peak_values = _peaks_from_samples(samples) if has_samples else None
|
||||
ev._a5_frames = None # not recoverable from BW file
|
||||
|
||||
return ev
|
||||
@@ -0,0 +1,479 @@
|
||||
"""
|
||||
histogram_codec.py — decoder for MiniMate Plus histogram-mode event bodies.
|
||||
|
||||
FULLY DECODED 2026-05-20. Every field in every block, verified
|
||||
byte-exact against BW's ASCII export across multiple histogram
|
||||
fixtures.
|
||||
|
||||
The histogram-mode body is a stream of 32-byte fixed-length blocks,
|
||||
one block per histogram interval. Each block carries the per-interval
|
||||
peak amplitude + zero-crossing frequency for all four channels (Tran,
|
||||
Vert, Long, MicL).
|
||||
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
Body layout (CONFIRMED 2026-05-20)
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
[stream of 32-byte blocks]
|
||||
|
||||
Body length is approximately ``n_intervals * 32`` bytes plus a small
|
||||
trailing remnant (1-9 bytes typically) at the very end. Walker should
|
||||
iterate 32-stride and stop before the tail.
|
||||
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
32-byte block layout
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
[0] 0x00 always-zero tag
|
||||
[1] segment_id (uint8) 0x00..0x03 - 256 blocks per segment
|
||||
[2:4] block_ctr (uint16 LE) resets each segment (0x0100, 0x0101, ...)
|
||||
[4] 0x0a (uint8) constant marker (= 10)
|
||||
[5:7] T_peak_count uint16 BE Tran peak (count x 0.005 -> in/s)
|
||||
[7:9] T_halfperiod uint16 BE Tran half-period in samples (freq = 512 / halfp)
|
||||
[9:11] V_peak_count uint16 BE
|
||||
[11:13] V_halfperiod uint16 BE
|
||||
[13:15] L_peak_count uint16 BE
|
||||
[15:17] L_halfperiod uint16 BE
|
||||
[17:19] M_peak_count uint16 BE MicL peak (count -> dB via mic_count_to_db)
|
||||
[19:21] M_halfperiod uint16 BE MicL half-period in samples
|
||||
[21:23] 0x00 0x00 constant on standard blocks
|
||||
[24:28] 4-byte variable purpose unknown (possibly CRC or timestamp delta)
|
||||
[28:32] block-end signature see "Two block tails" below
|
||||
|
||||
**Every per-channel field is uint16 BIG-endian** (confirmed 2026-08-25).
|
||||
Only ``block_ctr`` at [2:4] is little-endian.
|
||||
|
||||
HISTORY - two earlier readings of this block were wrong in ways that
|
||||
cancelled out on quiet data:
|
||||
|
||||
1. *peak as uint16 LE at [6:8]* - produced 268 in/s peaks on any
|
||||
interval whose next byte was non-zero.
|
||||
2. *peak as uint8 at [6] with an "annotation" byte at [7]* - correct
|
||||
for every peak below 256 counts (1.275 in/s), but it silently
|
||||
**clipped larger peaks**: the final interval of
|
||||
BE18193/T193LQ9K.OE0H reads 8.270 in/s in BW's export
|
||||
(1654 counts = 0x0676) and decoded as 0x76 = 118 = 0.590 in/s.
|
||||
The "annotation" byte was never an annotation - it is the high
|
||||
byte of the big-endian half-period, which is why it was non-zero
|
||||
exactly on the sub-Hz intervals BW renders as "<1.0".
|
||||
|
||||
Both readings also forced ``block[5] == 0`` via a bogus ``uint16 LE``
|
||||
marker check at [4:6], which is what capped the peak at one byte.
|
||||
The marker is ``block[4]`` alone.
|
||||
|
||||
Verified 2026-08-25 against 1211 production histograms paired with
|
||||
their Blastware ASCII exports: **1211/1211 decode exactly** (interval
|
||||
count plus every per-interval peak), and 842,442 per-interval
|
||||
frequency comparisons match with **zero** mismatches.
|
||||
|
||||
Two block tails
|
||||
---------------
|
||||
Standard blocks end with ``1e 0a 00 00``. The **final block of the
|
||||
stream** ends with ``9c 06 00 42`` instead, and carries arbitrary bytes
|
||||
at [21:23]. Rejecting it dropped the last interval of nearly every
|
||||
histogram - and the last interval is frequently the one holding the
|
||||
event peak, so the file's reported PPV came out low. Observed in 1206
|
||||
of 1211 production histograms, always positioned after every
|
||||
standard-tail block.
|
||||
|
||||
Block-identification anchor: ``block[0] == 0x00`` AND
|
||||
``block[4] == 0x0A`` AND the tail is one of the two signatures above;
|
||||
standard-tail blocks additionally require ``block[22] == 0x00``.
|
||||
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
Per-channel encoding
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Geophone channels (Tran, Vert, Long):
|
||||
- peak_count × 0.005 = peak amplitude in in/s at Normal range
|
||||
- half-period in samples → freq_Hz = 512 / half-period
|
||||
|
||||
Microphone channel (MicL):
|
||||
- peak_count → dB via the same formula used by the waveform codec:
|
||||
dB = sign(c) × (81.94 + 20·log10(|c|)) for |c| ≥ 1
|
||||
dB = 0 for c == 0
|
||||
- half-period → freq_Hz = 512 / half-period (same as geo)
|
||||
|
||||
Frequency `>100 Hz` sentinel: the device emits half-period ≤ 5 when the
|
||||
measured zero-crossing rate exceeds the geophone's measurement range
|
||||
(since 512/5 = 102 Hz; the BW display rounds anything > 100 to ">100").
|
||||
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
Output shape
|
||||
────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
``decode_histogram_body`` returns a per-channel dict matching the
|
||||
waveform codec's shape so the rest of the pipeline (.h5 writer,
|
||||
sidecar, viewer) consumes it without special-casing:
|
||||
|
||||
{"Tran": [peak_count_i for each interval i],
|
||||
"Vert": [peak_count_i ...],
|
||||
"Long": [peak_count_i ...],
|
||||
"MicL": [peak_count_i ...]}
|
||||
|
||||
Values are in **16-count units for geo** (LSB = 0.005 in/s, matching
|
||||
``decode_waveform_v2``) and **1-count units for mic** (matching the
|
||||
waveform codec's mic convention). Run through
|
||||
``waveform_codec.decoded_to_adc_counts`` to scale geo to 1-count ADC.
|
||||
|
||||
Per-interval frequencies are NOT returned — they're auxiliary data,
|
||||
not waveform samples. Consumers needing frequencies can call
|
||||
``decode_histogram_body_full()`` for the structured per-interval
|
||||
record list.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
# Block-end signature: constant `1e 0a 00 00` in bytes [28:32] of every
|
||||
# real data block. More distinctive than the byte-22 `00 00` (which
|
||||
# matches many false positives), so we anchor on this.
|
||||
_BLOCK_TAIL = b"\x1e\x0a\x00\x00"
|
||||
|
||||
# The final block of a histogram stream ends with this instead. It is a
|
||||
# real data block - same layout - and holds the last interval. See the
|
||||
# module docstring, "Two block tails".
|
||||
_BLOCK_TAIL_TERMINAL = b"\x9c\x06\x00\x42"
|
||||
|
||||
_BLOCK_SIZE = 32
|
||||
|
||||
# Marker byte at block[4:6] of every histogram data block. Used as
|
||||
# additional validation that we're looking at a real block.
|
||||
_BLOCK_MARKER = 10
|
||||
|
||||
# Geo peak scaling: stored as "count × 0.005 in/s" where 1 count = one
|
||||
# 0.005 in/s display quantum. Equivalent to the waveform codec's
|
||||
# 16-count-unit output (1 unit = 0.005 in/s = 16 ADC counts).
|
||||
_GEO_LSB_INS = 0.005
|
||||
|
||||
# Frequency formula: freq_Hz = _FREQ_NUMERATOR / half_period_samples.
|
||||
# Empirically determined to be 512 (= sample_rate / 2, where sample rate
|
||||
# is 1024 sps for the standard MiniMate Plus configuration).
|
||||
_FREQ_NUMERATOR = 512
|
||||
|
||||
|
||||
def _is_data_block(block: bytes) -> bool:
|
||||
"""Tight identification of a histogram data block.
|
||||
|
||||
Accepts both tail signatures. ``block[4]`` alone is the marker -
|
||||
``block[5]`` is the high byte of the Tran peak and is non-zero on any
|
||||
interval above 1.275 in/s, so it must not be part of the marker test.
|
||||
The ``block[22] == 0`` constraint is what keeps trailer content out,
|
||||
but it applies only to standard-tail blocks: terminal blocks carry
|
||||
arbitrary bytes there.
|
||||
"""
|
||||
if len(block) < _BLOCK_SIZE:
|
||||
return False
|
||||
if block[0] != 0x00:
|
||||
return False
|
||||
if block[4] != _BLOCK_MARKER:
|
||||
return False
|
||||
# The 4-byte tail plus block[0]==0 and block[4]==0x0A is already six bytes
|
||||
# of constraint — enough to keep trailer content out. There is NO extra
|
||||
# test on block[22]: it was documented as a constant 0x00 but carries data
|
||||
# on loud blocks, and rejecting those threw away the interval holding the
|
||||
# event peak. BE18350/T350L7HR.NL0H is the proof: its block 92 has
|
||||
# block[22]=0x26 and a Tran peak of 0x0563 = 1379 counts = 6.895 in/s,
|
||||
# exactly the device-reported PPV, while the file decoded to 0.015 in/s.
|
||||
return block[28:32] in (_BLOCK_TAIL, _BLOCK_TAIL_TERMINAL)
|
||||
|
||||
|
||||
def _decode_block(block: bytes) -> Optional[dict]:
|
||||
"""Decode one 32-byte histogram block. Caller must have validated
|
||||
with ``_is_data_block`` first.
|
||||
|
||||
Returns a record with per-channel peak counts (uint8) and
|
||||
half-periods (uint16 LE).
|
||||
"""
|
||||
# Every per-channel field is uint16 BIG-endian; only block_ctr is LE.
|
||||
# See the module docstring for the two superseded readings and why
|
||||
# each looked correct on quiet data.
|
||||
def _be16(i: int) -> int:
|
||||
return (block[i] << 8) | block[i + 1]
|
||||
|
||||
t_peak = _be16(5)
|
||||
t_halfp = _be16(7)
|
||||
v_peak = _be16(9)
|
||||
v_halfp = _be16(11)
|
||||
l_peak = _be16(13)
|
||||
l_halfp = _be16(15)
|
||||
m_peak = _be16(17)
|
||||
m_halfp = _be16(19)
|
||||
segment_id = block[1]
|
||||
block_ctr = block[2] | (block[3] << 8)
|
||||
var_meta = bytes(block[24:28])
|
||||
return {
|
||||
"segment_id": segment_id,
|
||||
"block_ctr": block_ctr,
|
||||
"t_peak": t_peak,
|
||||
"t_halfp": t_halfp,
|
||||
"v_peak": v_peak,
|
||||
"v_halfp": v_halfp,
|
||||
"l_peak": l_peak,
|
||||
"l_halfp": l_halfp,
|
||||
"m_peak": m_peak,
|
||||
"m_halfp": m_halfp,
|
||||
"meta_var": var_meta,
|
||||
"is_terminal": block[28:32] == _BLOCK_TAIL_TERMINAL,
|
||||
}
|
||||
|
||||
|
||||
def walk_body(body: bytes) -> List[dict]:
|
||||
"""Walk the body and return one dict per histogram interval.
|
||||
|
||||
Iterates 32-byte strides from offset 0. Yields a decoded record
|
||||
for every block that passes ``_is_data_block`` validation. Stops
|
||||
when the remaining bytes are too short to form a complete block.
|
||||
|
||||
In Histogram+Continuous mode the body interleaves data blocks with
|
||||
other 32-byte content (likely continuous-mode waveform blocks) that
|
||||
fail the data-block validation; the walker naturally skips them
|
||||
without losing 32-byte alignment. Use ``block_ctr`` from each
|
||||
returned record to map back to the original interval index — the
|
||||
record list is sparse when other block types are interleaved.
|
||||
"""
|
||||
records: List[dict] = []
|
||||
for off in range(0, len(body) - _BLOCK_SIZE + 1, _BLOCK_SIZE):
|
||||
blk = body[off:off + _BLOCK_SIZE]
|
||||
if not _is_data_block(blk):
|
||||
# Hit non-block content (likely a sync or stream marker).
|
||||
# Continue walking — block alignment is fixed at 32-stride
|
||||
# from offset 0, so we don't lose alignment by skipping.
|
||||
continue
|
||||
decoded = _decode_block(blk)
|
||||
if decoded is None:
|
||||
# Block validated as a histogram block but had peak fields
|
||||
# outside the plausible range — undocumented extension.
|
||||
# Skip rather than propagating bogus PVS contributions.
|
||||
continue
|
||||
records.append(decoded)
|
||||
return records
|
||||
|
||||
|
||||
def _walk_auto(body: bytes) -> List[dict]:
|
||||
"""Pick the block model by signature strength, not by which returns first.
|
||||
|
||||
The multi-interval variant announces itself with consecutive block headers
|
||||
at an exact ``12 + 20*n`` stride — far stronger evidence than a handful of
|
||||
scattered standard-tail blocks, which a multi-interval body will also yield
|
||||
by coincidence. Dispatching on "whichever decoder returns something"
|
||||
handed 193 BE18193 files to the standard walker and produced peaks of
|
||||
149 in/s against a 10 in/s full scale.
|
||||
"""
|
||||
if detect_multi_interval_stride(body):
|
||||
recs = walk_multi_interval_blocks(body)
|
||||
if recs:
|
||||
return recs
|
||||
return walk_body(body)
|
||||
|
||||
|
||||
def decode_histogram_body(body: bytes) -> Optional[dict]:
|
||||
"""Decode a histogram-mode body into per-channel peak-sample arrays.
|
||||
|
||||
Returns ``{"Tran": [...], "Vert": [...], "Long": [...], "MicL": [...]}``
|
||||
where each channel's list contains one peak value per histogram
|
||||
interval (in the same units the waveform codec uses: 16-count units
|
||||
for geo, 1-count ADC units for mic). Returns ``None`` if the body
|
||||
doesn't contain any valid histogram blocks.
|
||||
|
||||
To convert to physical units:
|
||||
- Geo channels: ``count * 0.005`` = peak in in/s at Normal range
|
||||
(or run through ``waveform_codec.decoded_to_adc_counts`` first
|
||||
to get 1-count ADC values, then ``count / 32767 * 10.0`` for in/s)
|
||||
- Mic channel: use ``waveform_codec.mic_count_to_db(count)``
|
||||
"""
|
||||
records = _walk_auto(body)
|
||||
if not records:
|
||||
return None
|
||||
return {
|
||||
"Tran": [r["t_peak"] for r in records],
|
||||
"Vert": [r["v_peak"] for r in records],
|
||||
"Long": [r["l_peak"] for r in records],
|
||||
"MicL": [r["m_peak"] for r in records],
|
||||
}
|
||||
|
||||
|
||||
def decode_histogram_body_full(body: bytes) -> Optional[List[dict]]:
|
||||
"""Decode a histogram-mode body into the full per-interval record list.
|
||||
|
||||
Same data as ``decode_histogram_body`` but in a structured form that
|
||||
preserves the half-period (frequency) data for each channel + the
|
||||
per-block segment_id, block_ctr, and 4-byte variable metadata.
|
||||
Useful for diagnostic tools, sidecar enrichment, and future-codec
|
||||
work.
|
||||
|
||||
Returns ``None`` if the body has no valid blocks.
|
||||
"""
|
||||
records = _walk_auto(body)
|
||||
return records if records else None
|
||||
|
||||
|
||||
def half_period_to_hz(halfp: int) -> Optional[float]:
|
||||
"""Convert a half-period in samples to frequency in Hz.
|
||||
|
||||
Returns ``None`` for half-period ≤ 5 — the device emits values in
|
||||
that range when the measured zero-crossing rate exceeds 100 Hz
|
||||
(the BW display reports `>100 Hz` for such cases). Callers can
|
||||
treat ``None`` as the `>100 Hz` sentinel.
|
||||
"""
|
||||
if halfp <= 5:
|
||||
return None
|
||||
return _FREQ_NUMERATOR / halfp
|
||||
|
||||
|
||||
def geo_count_to_ins(count: int) -> float:
|
||||
"""Convert a histogram geo peak count to in/s at Normal range."""
|
||||
return count * _GEO_LSB_INS
|
||||
|
||||
|
||||
# ── Multi-interval block variant (CONFIRMED 2026-08-26) ─────────────────────
|
||||
#
|
||||
# When the histogram interval is SHORTER than one minute, the device packs
|
||||
# several intervals into a single block so that every block still covers
|
||||
# exactly one minute of data:
|
||||
#
|
||||
# interval size intervals/block stride
|
||||
# 1 minute 1 32 <- the standard block above
|
||||
# 15 seconds 4 92
|
||||
# 2 seconds 30 612
|
||||
#
|
||||
# stride = 12 + n_intervals * 20
|
||||
#
|
||||
# Block layout:
|
||||
# [0] 0x00
|
||||
# [1] segment_id (256 blocks per segment, same as the standard block)
|
||||
# [2:4] block_ctr uint16 LE (0x0100.., resets each segment)
|
||||
# [4] 0x0a marker
|
||||
# [5] 0x00
|
||||
# [6 ...] n x 20-byte interval records, each carrying 8 x uint16
|
||||
# LITTLE-endian values:
|
||||
# T_peak, T_halfperiod, V_peak, V_halfperiod,
|
||||
# L_peak, L_halfperiod, M_peak, M_halfperiod
|
||||
# then 2 more words; the first is 0x0000 on every real interval.
|
||||
# [-6:] 6-byte block trailer
|
||||
#
|
||||
# ⚠ ENDIANNESS: the standard 32-byte block is BIG-endian. This variant is
|
||||
# LITTLE-endian. Do not share the accessor.
|
||||
#
|
||||
# These files previously decoded to nothing at all — 415 of them in the
|
||||
# production snapshot, 216 on BE18193 (2 s intervals) and 199 on BE9440
|
||||
# (15 s). Before that they were being accepted by the WAVEFORM codec, which
|
||||
# returned garbage peaking up to 400x the device-reported PPV.
|
||||
#
|
||||
# Ground truth: BE9440/K440L3AQ.T70H (15 s intervals, 5,710 of them) decodes
|
||||
# against its Blastware ASCII export with 17,130/17,130 geo peak counts,
|
||||
# 22,840/22,840 frequencies and 5,710/5,710 mic dB(L) values matching exactly.
|
||||
|
||||
_MULTI_HEADER_LEN = 6
|
||||
_MULTI_RECORD_LEN = 20
|
||||
_MULTI_TRAILER_LEN = 6
|
||||
# At least 2 records: a 1-record block would have stride 12 + 20 = 32, which
|
||||
# collides with the standard big-endian block and mis-decodes it.
|
||||
_MULTI_MIN_RECORDS = 2
|
||||
_MULTI_MAX_RECORDS = 64
|
||||
|
||||
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. A peak above
|
||||
# this is physically impossible and marks buffer garbage in a partial block.
|
||||
_GEO_MAX_COUNTS = 2000
|
||||
|
||||
|
||||
def _is_multi_header(body: bytes, off: int) -> bool:
|
||||
return (off + _MULTI_HEADER_LEN <= len(body)
|
||||
and body[off] == 0x00
|
||||
and body[off + 4] == 0x0A
|
||||
and body[off + 5] == 0x00)
|
||||
|
||||
|
||||
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
|
||||
"""Block stride of a multi-interval histogram body, or None.
|
||||
|
||||
Found by locating the second block header; validated against
|
||||
``stride = 12 + n * 20`` and confirmed on a third block where present.
|
||||
"""
|
||||
if not _is_multi_header(body, 0):
|
||||
return None
|
||||
lo = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MIN_RECORDS
|
||||
hi = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MAX_RECORDS
|
||||
for stride in range(lo, min(hi, len(body)) + 1, 2):
|
||||
if (stride - 12) % _MULTI_RECORD_LEN:
|
||||
continue
|
||||
if not _is_multi_header(body, stride):
|
||||
continue
|
||||
# DECISIVE CHECK: consecutive blocks differ by exactly 1 in block_ctr.
|
||||
# Without it this false-positives on ordinary standard-block bodies:
|
||||
# those carry a header every 32 bytes, and 192 = 12 + 20*9 and
|
||||
# 512 = 12 + 20*25 are both multiples of 32, so a stride "fits" while
|
||||
# actually skipping 6 or 16 real blocks. Sampling a standard body at
|
||||
# stride 192 handed 9,082 files to the wrong decoder and produced peaks
|
||||
# of 149 in/s against a 10 in/s full scale.
|
||||
def _ctr(o: int) -> int:
|
||||
return body[o + 2] | (body[o + 3] << 8)
|
||||
|
||||
if (_ctr(stride) - _ctr(0)) & 0xFFFF != 1:
|
||||
continue
|
||||
# confirm on a third block when the body is long enough
|
||||
if 2 * stride + _MULTI_HEADER_LEN <= len(body):
|
||||
if not _is_multi_header(body, 2 * stride):
|
||||
continue
|
||||
if (_ctr(2 * stride) - _ctr(stride)) & 0xFFFF != 1:
|
||||
continue
|
||||
return stride
|
||||
return None
|
||||
|
||||
|
||||
def walk_multi_interval_blocks(body: bytes,
|
||||
stride: Optional[int] = None) -> List[dict]:
|
||||
"""Decode a multi-interval histogram body into per-interval records."""
|
||||
if stride is None:
|
||||
stride = detect_multi_interval_stride(body)
|
||||
if not stride:
|
||||
return []
|
||||
n_per_block = (stride - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN) // _MULTI_RECORD_LEN
|
||||
if n_per_block < 1:
|
||||
return []
|
||||
|
||||
def u16le(p: int) -> int:
|
||||
return body[p] | (body[p + 1] << 8)
|
||||
|
||||
out: List[dict] = []
|
||||
for off in range(0, len(body) - stride + 1, stride):
|
||||
if not _is_multi_header(body, off):
|
||||
break # end of the block run; trailer follows
|
||||
for k in range(n_per_block):
|
||||
q = off + _MULTI_HEADER_LEN + _MULTI_RECORD_LEN * k
|
||||
out.append({
|
||||
"_tail0": u16le(q + 16),
|
||||
"segment_id": body[off + 1],
|
||||
"block_ctr": u16le(off + 2),
|
||||
"t_peak": u16le(q), "t_halfp": u16le(q + 2),
|
||||
"v_peak": u16le(q + 4), "v_halfp": u16le(q + 6),
|
||||
"l_peak": u16le(q + 8), "l_halfp": u16le(q + 10),
|
||||
"m_peak": u16le(q + 12), "m_halfp": u16le(q + 14),
|
||||
"meta_var": bytes(body[q + 16:q + 20]),
|
||||
"is_terminal": False,
|
||||
})
|
||||
# A session ending mid-block leaves the remaining slots of the FINAL block
|
||||
# filled with whatever was in the buffer. Those decoded as peaks thousands
|
||||
# of times the device-reported PPV, so they have to go — but only from the
|
||||
# final block: a non-zero tail word occurs mid-file on real intervals, and
|
||||
# trimming on that alone truncated four BE9440 files by up to 2,800
|
||||
# intervals, while trimming purely from the end left garbage stranded
|
||||
# behind one slot that happened to have a zero tail word.
|
||||
#
|
||||
# Within the final block, stop at the first slot that is not plausibly
|
||||
# real: a non-zero tail word, or a geo peak above full scale. 16-count
|
||||
# units put Normal-range full scale (10.000 in/s) at 2000 counts, so
|
||||
# anything beyond that is physically impossible.
|
||||
if out:
|
||||
last_block_start = ((len(out) - 1) // n_per_block) * n_per_block
|
||||
for i in range(last_block_start, len(out)):
|
||||
r = out[i]
|
||||
if (r["_tail0"] != 0
|
||||
or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS):
|
||||
del out[i:]
|
||||
break
|
||||
for r in out:
|
||||
r.pop("_tail0", None)
|
||||
return out
|
||||
@@ -352,6 +352,14 @@ class PeakValues:
|
||||
long: Optional[float] = None # Longitudinal PPV (in/s) ✅
|
||||
micl: Optional[float] = None # Air overpressure (psi) 🔶 (units uncertain)
|
||||
peak_vector_sum: Optional[float] = None # Scalar geo PVS (in/s) ✅
|
||||
tran_zc_freq: Optional[float] = None
|
||||
vert_zc_freq: Optional[float] = None
|
||||
long_zc_freq: Optional[float] = None
|
||||
mic_zc_freq: Optional[float] = None
|
||||
tran_zc_above_range: bool = False
|
||||
vert_zc_above_range: bool = False
|
||||
long_zc_above_range: bool = False
|
||||
mic_zc_above_range: bool = False
|
||||
|
||||
|
||||
# ── Project / operator metadata ───────────────────────────────────────────────
|
||||
|
||||
+371
-38
@@ -166,8 +166,14 @@ def find_data_start(body: bytes) -> int:
|
||||
# Try fixed offset 7 first (canonical preamble length).
|
||||
if len(body) >= 9:
|
||||
b, nn = body[7], body[8]
|
||||
if (b in (0x00, 0x10, 0x20, 0x30) and nn % 4 == 0 and 0 < nn <= 0xFC) \
|
||||
or (b == 0x40 and nn == 0x02):
|
||||
# Accept the same tag vocabulary ``walk_body`` accepts, including the
|
||||
# wide-NN forms (``0X``/``1X``/``2X``) and the variable-width ``40 NN``
|
||||
# segment header.
|
||||
if ((b & 0xF0) in (0x00, 0x10, 0x20) and nn % 4 == 0
|
||||
and ((b & 0x0F) != 0 or 0 < nn <= 0xFC)) \
|
||||
or (b == 0x30 and nn % 4 == 0 and 0 < nn <= 0xFC) \
|
||||
or (b == 0x40 and 0 < nn <= 0x08) \
|
||||
or is_tagless_segment_header(body, 7):
|
||||
return 7
|
||||
# Fall back to scanning the first 20 bytes.
|
||||
for i in range(min(20, len(body) - 1)):
|
||||
@@ -178,6 +184,31 @@ def find_data_start(body: bytes) -> int:
|
||||
return -1
|
||||
|
||||
|
||||
# Channel-id byte carried in every segment header. Previously mis-read as a
|
||||
# "monotonic uint32 LE counter"; it is really ``[channel][00][00][segment]``.
|
||||
# Verified 2026-08-25 on 1697/1697 segment headers across the ground-truth
|
||||
# corpus with zero disagreements against the decoded channel rotation.
|
||||
SEGMENT_CHANNEL_IDS = {0x46: "Tran", 0x47: "Vert", 0x48: "Long", 0x49: "MicL"}
|
||||
|
||||
# A tagless segment header: the 14-byte tail of a ``40 NN`` header with no tag
|
||||
# and no previous-channel continuation deltas (the NN=0 case).
|
||||
_TAGLESS_HEADER_LEN = 14
|
||||
|
||||
|
||||
def is_tagless_segment_header(body: bytes, i: int) -> bool:
|
||||
"""True if a bare 14-byte segment header starts at *i*.
|
||||
|
||||
Layout ``[field2:2][len_to_next:2][channel_id:4][marker:2][anchors:4]``.
|
||||
The discriminator is the 6 bytes at ``[4:10]``: a known channel id, two
|
||||
zero bytes, a small segment index, and the ``01 00`` / ``02 00`` marker.
|
||||
"""
|
||||
if i + _TAGLESS_HEADER_LEN > len(body):
|
||||
return False
|
||||
return (body[i + 4] in SEGMENT_CHANNEL_IDS
|
||||
and body[i + 5] == 0x00 and body[i + 6] == 0x00
|
||||
and body[i + 8] in (0x01, 0x02) and body[i + 9] == 0x00)
|
||||
|
||||
|
||||
def walk_body(body: bytes, start: Optional[int] = None) -> List[WaveformBlock]:
|
||||
"""Walk the tagged-block sequence starting at *start* (auto-detected by default).
|
||||
|
||||
@@ -210,9 +241,15 @@ def walk_body(body: bytes, start: Optional[int] = None) -> List[WaveformBlock]:
|
||||
# Wide-NN int8 block: ``2X NN`` extends NN to 12 bits the same way.
|
||||
wide_nn = ((t0 & 0x0F) << 8) | t1
|
||||
length = wide_nn + 2
|
||||
elif t0 == 0x00 and t1 % 4 == 0:
|
||||
elif (t0 & 0xF0) == 0x00 and t1 % 4 == 0:
|
||||
# ``00 NN`` RLE zero-delta run, plus its wide form ``0X NN``
|
||||
# (X != 0) which extends NN to 12 bits exactly like ``1X``/``2X``:
|
||||
# NN = ((t0 & 0x0F) << 8) | t1. A narrow run maxes out at
|
||||
# NN=0xFC, so quiet stretches longer than 252 samples must use
|
||||
# the wide form. Confirmed 2026-08-25 against six production
|
||||
# events (e.g. ``01 0c`` = 268 repeats in K558LKOF.460W).
|
||||
length = 2
|
||||
elif t0 == 0x30 and t1 % 4 == 0 and 0 < t1 <= 0x10:
|
||||
elif t0 == 0x30 and t1 % 4 == 0 and 0 < t1 <= 0xFC:
|
||||
# Data-section ``30 NN`` blocks carry NN 12-bit signed deltas packed
|
||||
# as NN/4 groups of (2-byte high-nibble field + 4 × int8 low byte).
|
||||
# Length = NN/4 × 6 + 2 = NN × 1.5 + 2 (= 8 for NN=4, 14 for NN=8,
|
||||
@@ -229,8 +266,28 @@ def walk_body(body: bytes, start: Optional[int] = None) -> List[WaveformBlock]:
|
||||
length = cand_data
|
||||
else:
|
||||
length = cand_trailer
|
||||
elif t0 == 0x40 and t1 == 0x02:
|
||||
length = 20
|
||||
elif t0 == 0x40 and 0 < t1 <= 0x08:
|
||||
# ``40 NN`` segment header. NN is the number of int16 BE
|
||||
# continuation deltas the header carries for the PREVIOUS
|
||||
# channel, so the header grows with NN:
|
||||
# length = 2 (tag) + 2*NN (deltas) + 14 (fixed tail)
|
||||
# ``40 02`` (20 bytes) dominates, but ``40 01`` (18) and
|
||||
# ``40 03`` (22) both occur in production files. Confirmed
|
||||
# 2026-08-25; the constant ``02 00`` marker moves with NN too
|
||||
# (see :func:`parse_segment_header`).
|
||||
length = 2 * t1 + 16
|
||||
elif is_tagless_segment_header(body, i):
|
||||
# Segment header with no ``40 NN`` tag (NN=0 — the previous channel
|
||||
# needed no continuation deltas). Emit it as a synthetic ``40 00``
|
||||
# block whose ``data`` is the whole 14-byte record, so the nd=0
|
||||
# offsets in :func:`decode_waveform_v2` line up unchanged.
|
||||
blocks.append(WaveformBlock(
|
||||
offset=i, tag_hi=0x40, tag_lo=0x00,
|
||||
data=bytes(body[i : i + _TAGLESS_HEADER_LEN]),
|
||||
length=_TAGLESS_HEADER_LEN,
|
||||
))
|
||||
i += _TAGLESS_HEADER_LEN
|
||||
continue
|
||||
else:
|
||||
# Unknown tag; stop. Caller can inspect ``i`` to see where.
|
||||
break
|
||||
@@ -256,7 +313,7 @@ def split_segments(blocks: List[WaveformBlock]) -> List[List[WaveformBlock]]:
|
||||
segments: List[List[WaveformBlock]] = []
|
||||
current: List[WaveformBlock] = []
|
||||
for b in blocks:
|
||||
if b.tag_hi == 0x40 and b.tag_lo == 0x02:
|
||||
if b.tag_hi == 0x40:
|
||||
if current:
|
||||
segments.append(current)
|
||||
current = [b]
|
||||
@@ -268,23 +325,40 @@ def split_segments(blocks: List[WaveformBlock]) -> List[List[WaveformBlock]]:
|
||||
|
||||
|
||||
def parse_segment_header(block: WaveformBlock) -> Optional[dict]:
|
||||
"""Decode the 18-byte payload of a ``40 02`` segment header.
|
||||
"""Decode the payload of a ``40 NN`` segment header.
|
||||
|
||||
Returns a dict with the labelled fields, or None if *block* is not
|
||||
a ``40 02`` header.
|
||||
NN (the tag's low byte) is the number of int16 BE continuation deltas
|
||||
the header carries for the PREVIOUS channel, so every field after
|
||||
those deltas shifts by ``2 * NN``. The payload is ``2 * NN + 14``
|
||||
bytes. ``40 02`` is the common case; ``40 01`` and ``40 03`` also
|
||||
occur in production files (confirmed 2026-08-25).
|
||||
|
||||
Returns a dict with the labelled fields, or None if *block* is not a
|
||||
segment header or is too short.
|
||||
"""
|
||||
if not (block.tag_hi == 0x40 and block.tag_lo == 0x02):
|
||||
if block.tag_hi != 0x40 or block.tag_lo > 0x08:
|
||||
return None
|
||||
if len(block.data) < 18:
|
||||
nd = block.tag_lo
|
||||
if len(block.data) < 2 * nd + 14:
|
||||
return None
|
||||
p = block.data
|
||||
counter = int.from_bytes(p[8:12], "little", signed=False)
|
||||
counter = int.from_bytes(p[2 * nd + 4 : 2 * nd + 8], "little", signed=False)
|
||||
return {
|
||||
"anchor_bytes": p[0:4], # 4-byte field, role unconfirmed
|
||||
"field2": p[4:8], # 4-byte field, role unconfirmed
|
||||
"counter": counter, # uint32 LE — increments by 1 per segment
|
||||
"fixed_pattern": p[12:16], # always b"\x02\x00\x00\x01"
|
||||
"tail": p[16:18], # last 2 bytes
|
||||
"n_prev_deltas": nd,
|
||||
# ``nd`` int16 BE deltas extending the previous channel.
|
||||
"prev_deltas": [
|
||||
int.from_bytes(p[2 * k : 2 * k + 2], "big", signed=True)
|
||||
for k in range(nd)
|
||||
],
|
||||
"field2": p[2 * nd : 2 * nd + 4], # 4-byte field, role unconfirmed
|
||||
"counter": counter, # legacy: raw uint32 LE of the id field
|
||||
"channel": SEGMENT_CHANNEL_IDS.get(p[2 * nd + 4]),
|
||||
"segment_index": p[2 * nd + 7],
|
||||
"marker": p[2 * nd + 8 : 2 * nd + 10], # always b"\x02\x00"
|
||||
"anchors": [
|
||||
int.from_bytes(p[2 * nd + 10 : 2 * nd + 12], "big", signed=True),
|
||||
int.from_bytes(p[2 * nd + 12 : 2 * nd + 14], "big", signed=True),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -367,8 +441,16 @@ def decode_tran_initial(body: bytes) -> Optional[List[int]]:
|
||||
return out
|
||||
|
||||
|
||||
def decode_waveform_v2(body: bytes) -> Optional[dict]:
|
||||
def decode_waveform_legacy(body: bytes) -> Optional[dict]:
|
||||
"""
|
||||
SUPERSEDED 2026-08-25 — the tag-dispatch / segment-header model.
|
||||
|
||||
Retained because ``micromate/idf_file.py`` trial-decodes Thor IDFW bodies
|
||||
at many candidate offsets and keeps whichever yields the most samples;
|
||||
the record-chain decoder returns None where this one returned garbage,
|
||||
which shifts that heuristic's winner. Thor is pinned here until its own
|
||||
body-offset search is reworked. Do not use for series-3.
|
||||
|
||||
Decode the body into per-channel sample arrays.
|
||||
|
||||
Status (2026-05-11 evening — channel-rotation hypothesis CONFIRMED):
|
||||
@@ -420,8 +502,11 @@ def decode_waveform_v2(body: bytes) -> Optional[dict]:
|
||||
for byte in blk.data:
|
||||
cur += _i8(byte)
|
||||
out[channel].append(cur)
|
||||
elif blk.tag_hi == 0x00:
|
||||
for _ in range(blk.tag_lo):
|
||||
elif (blk.tag_hi & 0xF0) == 0x00:
|
||||
# RLE zero-delta run. Wide form ``0X NN`` carries the high
|
||||
# nibble of a 12-bit NN in the tag byte, same as ``1X``/``2X``.
|
||||
run = ((blk.tag_hi & 0x0F) << 8) | blk.tag_lo
|
||||
for _ in range(run):
|
||||
out[channel].append(cur)
|
||||
elif blk.tag_hi == 0x30:
|
||||
# 12-bit signed deltas, packed as NN/4 groups of 6 bytes each:
|
||||
@@ -461,34 +546,54 @@ def decode_waveform_v2(body: bytes) -> Optional[dict]:
|
||||
# previous-channel extension deltas at every segment boundary.
|
||||
last_value = {"Tran": last_tran_value, "Vert": None, "Long": None, "MicL": None}
|
||||
|
||||
prev_channel = "Tran"
|
||||
for k, hi in enumerate(seg_idx):
|
||||
channel = rotation[k % 4]
|
||||
prev_channel = "Tran" if k == 0 else rotation[(k - 1) % 4]
|
||||
header = blocks[hi]
|
||||
if len(header.data) < 18:
|
||||
# Channel comes from the header's own id byte, which is authoritative.
|
||||
# The old rotation-by-position fallback is kept for headers whose id
|
||||
# byte isn't one of the four known values — but a single missed or
|
||||
# extra header would desync rotation and corrupt every later channel,
|
||||
# which is exactly what tagless headers used to cause.
|
||||
_nd = header.tag_lo
|
||||
channel = None
|
||||
if len(header.data) >= 2 * _nd + 8:
|
||||
channel = SEGMENT_CHANNEL_IDS.get(header.data[2 * _nd + 4])
|
||||
if channel is None:
|
||||
channel = rotation[k % 4]
|
||||
# ``40 NN``: NN int16 BE continuation deltas for the previous channel
|
||||
# come first, so every later field shifts by 2*NN. NN is usually 2
|
||||
# but 1 and 3 both occur (confirmed 2026-08-25).
|
||||
nd = header.tag_lo
|
||||
if len(header.data) < 2 * nd + 14:
|
||||
continue
|
||||
# Validate: real segment headers have bytes [12:14] = `02 00`.
|
||||
# Trailer/footer "40 02" markers contain ASCII serial bytes or other
|
||||
# non-header data there and would otherwise be mis-interpreted as
|
||||
# segment headers, adding spurious samples at the tail.
|
||||
if header.data[12:14] != b"\x02\x00":
|
||||
# Validate: real segment headers have the constant `02 00` marker
|
||||
# right after the counter. Trailer/footer "40 NN" markers contain
|
||||
# ASCII serial bytes or other non-header data there and would
|
||||
# otherwise be mis-read as segment headers, adding spurious tail
|
||||
# samples.
|
||||
if header.data[2 * nd + 8 : 2 * nd + 10] != b"\x02\x00":
|
||||
break
|
||||
# Extend the PREVIOUS channel by 2 more samples (deltas in bytes [0:4]).
|
||||
prev_d0 = int.from_bytes(header.data[0:2], "big", signed=True)
|
||||
prev_d1 = int.from_bytes(header.data[2:4], "big", signed=True)
|
||||
# Extend the PREVIOUS channel by NN more samples.
|
||||
if last_value[prev_channel] is not None:
|
||||
v = last_value[prev_channel] + prev_d0
|
||||
out[prev_channel].append(v)
|
||||
v += prev_d1
|
||||
out[prev_channel].append(v)
|
||||
v = last_value[prev_channel]
|
||||
for d in range(nd): # NB: not `k` — that's the segment index
|
||||
v += int.from_bytes(
|
||||
header.data[2 * d : 2 * d + 2], "big", signed=True
|
||||
)
|
||||
out[prev_channel].append(v)
|
||||
last_value[prev_channel] = v
|
||||
# Anchor pair for THIS segment's channel.
|
||||
c0 = int.from_bytes(header.data[14:16], "big", signed=True)
|
||||
c1 = int.from_bytes(header.data[16:18], "big", signed=True)
|
||||
c0 = int.from_bytes(
|
||||
header.data[2 * nd + 10 : 2 * nd + 12], "big", signed=True
|
||||
)
|
||||
c1 = int.from_bytes(
|
||||
header.data[2 * nd + 12 : 2 * nd + 14], "big", signed=True
|
||||
)
|
||||
out[channel].extend([c0, c1])
|
||||
# Apply delta blocks for this segment.
|
||||
next_hi = seg_idx[k + 1] if k + 1 < len(seg_idx) else len(blocks)
|
||||
last_value[channel] = apply_blocks(channel, c1, hi + 1, next_hi)
|
||||
prev_channel = channel
|
||||
|
||||
return out
|
||||
|
||||
@@ -576,3 +681,231 @@ def decode_a5_frames(a5_frames) -> Optional[dict]:
|
||||
if decoded is None:
|
||||
return None
|
||||
return decoded_to_adc_counts(decoded)
|
||||
|
||||
|
||||
# ── Record-chain body model (CONFIRMED 2026-08-25) ──────────────────────────
|
||||
#
|
||||
# The body is NOT a flat tag-dispatch stream with ``40 NN`` segment headers.
|
||||
# It is a chain of self-delimiting per-channel RECORDS:
|
||||
#
|
||||
# off+0 field2 uint16 purpose unknown (not a length, not a checksum)
|
||||
# off+2 len uint16 BE next_record = off + 2 + len <- authoritative
|
||||
# off+4 chan_id 0x46 Tran / 0x47 Vert / 0x48 Long / 0x49 MicL
|
||||
# 0x06 = end of waveform stream
|
||||
# off+5 0x00
|
||||
# off+6 0x00
|
||||
# off+7 segment index
|
||||
# off+8 mode 2 bytes, a 3-valued enum (see below)
|
||||
# off+10 anchors 2 x int16 BE, ABSOLUTE — present only when mode is 02 00
|
||||
#
|
||||
# Mode semantics, all ground-truth verified:
|
||||
# 02 00 14-byte header; emit the 2 anchors, then blocks are CUMULATIVE deltas
|
||||
# 01 00 10-byte header; no anchors; blocks carry ABSOLUTE sample values
|
||||
# 00 03 10-byte header; NO TAGS AT ALL — the data section is raw 12-bit
|
||||
# packed ABSOLUTE samples (6 bytes -> 4 samples)
|
||||
#
|
||||
# ``40 NN`` is an ordinary int16 BE DATA block (length 2*NN + 2), never a header.
|
||||
# The previous model read it as a variable-width segment header of length
|
||||
# 2*NN + 16, which is why walks drifted and channels came out unequal.
|
||||
#
|
||||
# Verified over the 1,388 series-3 waveform binaries in the production
|
||||
# snapshot: the length chain terminates on a 0x06 record in 1,387 of them (the
|
||||
# exception has an ambiguous footer, handled by the caller), and all four
|
||||
# channels come out at identical length in 1,388/1,388 — against 156/1,388
|
||||
# under the superseded model. Against the 75 events with a preserved
|
||||
# Blastware ASCII export: sample-count exact 72/75 -> 75/75, fully exact
|
||||
# 70/75 -> 73/75.
|
||||
|
||||
CHANNEL_IDS = {0x46: "Tran", 0x47: "Vert", 0x48: "Long", 0x49: "MicL"}
|
||||
STREAM_END_ID = 0x06
|
||||
|
||||
MODE_DELTA = (0x02, 0x00)
|
||||
MODE_ABSOLUTE = (0x01, 0x00)
|
||||
MODE_RAW12 = (0x00, 0x03)
|
||||
_MODES = (MODE_DELTA, MODE_ABSOLUTE, MODE_RAW12)
|
||||
|
||||
|
||||
def _u16(b: bytes, p: int) -> int:
|
||||
return (b[p] << 8) | b[p + 1]
|
||||
|
||||
|
||||
def _i16(b: bytes, p: int) -> int:
|
||||
v = _u16(b, p)
|
||||
return v - 0x10000 if v >= 0x8000 else v
|
||||
|
||||
|
||||
def data_block_len(body: bytes, p: int) -> Tuple[Optional[int], Optional[int]]:
|
||||
"""``(byte_length, n_samples)`` of the data block at *p*, or ``(None, None)``.
|
||||
|
||||
Data-section blocks only — there is no segment-header tag in this model.
|
||||
``30 NN`` has no trailer-length fallback here; that fallback corrupted
|
||||
records whose ``30 NN`` sat near a record boundary.
|
||||
"""
|
||||
if p + 2 > len(body):
|
||||
return None, None
|
||||
t0, t1 = body[p], body[p + 1]
|
||||
hi = t0 & 0xF0
|
||||
nn = ((t0 & 0x0F) << 8) | t1
|
||||
if hi == 0x40: # int16 BE data block
|
||||
return (None, None) if (nn == 0 or nn > 0x08) else (2 * nn + 2, nn)
|
||||
if nn == 0 or nn % 4:
|
||||
return None, None
|
||||
if hi == 0x00:
|
||||
return 2, nn # RLE hold
|
||||
if hi == 0x10:
|
||||
return nn // 2 + 2, nn # 4-bit nibble
|
||||
if hi == 0x20:
|
||||
return nn + 2, nn # int8
|
||||
if hi == 0x30:
|
||||
return nn * 3 // 2 + 2, nn # 12-bit packed
|
||||
return None, None
|
||||
|
||||
|
||||
def unpack12(data: bytes) -> List[int]:
|
||||
"""Raw 12-bit packed samples: 6 bytes -> 4 signed values."""
|
||||
out: List[int] = []
|
||||
for g in range(len(data) // 6):
|
||||
hi = (data[6 * g] << 8) | data[6 * g + 1]
|
||||
for k in range(4):
|
||||
x = (((hi >> (12 - 4 * k)) & 0xF) << 8) | data[6 * g + 2 + k]
|
||||
out.append(x - 0x1000 if x >= 0x800 else x)
|
||||
return out
|
||||
|
||||
|
||||
def is_record(body: bytes, p: int) -> bool:
|
||||
"""True if a per-channel record header starts at *p*."""
|
||||
return (p + 10 <= len(body)
|
||||
and body[p + 4] in CHANNEL_IDS
|
||||
and body[p + 5] == 0x00 and body[p + 6] == 0x00
|
||||
and 8 <= _u16(body, p + 2) <= len(body) - p
|
||||
and (body[p + 8], body[p + 9]) in _MODES)
|
||||
|
||||
|
||||
def find_first_record(body: bytes) -> Optional[int]:
|
||||
"""Offset of the first record, or None.
|
||||
|
||||
Under the normal ``00 02 00`` preamble the leading bytes are segment-0's
|
||||
Tran blocks, so walk them. Under the ``00 00 03`` preamble that data is
|
||||
raw 12-bit with no tags at all and cannot be block-walked — scan instead.
|
||||
"""
|
||||
if len(body) >= 3 and (body[1], body[2]) == MODE_RAW12:
|
||||
scan_from = 3
|
||||
else:
|
||||
i = 7
|
||||
while i < len(body):
|
||||
if is_record(body, i):
|
||||
nxt = i + 2 + _u16(body, i + 2)
|
||||
if nxt + 5 <= len(body) and (is_record(body, nxt)
|
||||
or body[nxt + 4] == STREAM_END_ID):
|
||||
return i
|
||||
length, _ = data_block_len(body, i)
|
||||
if length is None:
|
||||
return None
|
||||
i += length
|
||||
return None
|
||||
for i in range(scan_from, max(scan_from, len(body) - 10)):
|
||||
if is_record(body, i):
|
||||
nxt = i + 2 + _u16(body, i + 2)
|
||||
if nxt + 5 <= len(body) and (is_record(body, nxt)
|
||||
or body[nxt + 4] == STREAM_END_ID):
|
||||
return i
|
||||
return None
|
||||
|
||||
|
||||
def walk_records(body: bytes, first: Optional[int] = None) -> List[dict]:
|
||||
"""Follow the length chain from *first* to the ``0x06`` terminator."""
|
||||
if first is None:
|
||||
first = find_first_record(body)
|
||||
out: List[dict] = []
|
||||
if first is None:
|
||||
return out
|
||||
p, seen = first, set()
|
||||
while p is not None and p + 10 <= len(body):
|
||||
if p in seen:
|
||||
break
|
||||
seen.add(p)
|
||||
cid = body[p + 4]
|
||||
if cid == STREAM_END_ID or cid not in CHANNEL_IDS:
|
||||
break
|
||||
length = _u16(body, p + 2)
|
||||
if length < 8 or p + 2 + length > len(body):
|
||||
break
|
||||
out.append({"offset": p, "channel": CHANNEL_IDS[cid],
|
||||
"segment_index": body[p + 7],
|
||||
"mode": (body[p + 8], body[p + 9]),
|
||||
"end": p + 2 + length})
|
||||
p += 2 + length
|
||||
return out
|
||||
|
||||
|
||||
def decode_waveform_v2(body: bytes) -> Optional[dict]:
|
||||
"""Decode a Blastware waveform body into per-channel sample arrays.
|
||||
|
||||
Returns ``{"Tran": [...], "Vert": [...], "Long": [...], "MicL": [...]}``
|
||||
in 16-count units (LSB = 0.005 in/s at Normal range), or None if *body*
|
||||
is not a decodable waveform body.
|
||||
|
||||
Implements the record-chain model documented above.
|
||||
"""
|
||||
if len(body) < 8 or body[0] != 0x00:
|
||||
return None
|
||||
preamble = (body[1], body[2])
|
||||
if preamble not in (MODE_DELTA, MODE_RAW12):
|
||||
return None
|
||||
first = find_first_record(body)
|
||||
if first is None:
|
||||
return None
|
||||
|
||||
out: dict = {c: [] for c in ("Tran", "Vert", "Long", "MicL")}
|
||||
|
||||
def run(channel: str, start: int, end: int, absolute: bool) -> None:
|
||||
cur = out[channel][-1] if out[channel] else 0
|
||||
i = start
|
||||
while i < end:
|
||||
length, nn = data_block_len(body, i)
|
||||
if length is None or i + length > end:
|
||||
return # stop this record; the chain resyncs at end
|
||||
hi = body[i] & 0xF0
|
||||
if hi == 0x00:
|
||||
vals = [None] * nn
|
||||
elif hi == 0x10:
|
||||
vals = []
|
||||
for k in range(nn):
|
||||
byte = body[i + 2 + k // 2]
|
||||
v = (byte >> 4) if k % 2 == 0 else (byte & 0xF)
|
||||
vals.append(v - 16 if v >= 8 else v)
|
||||
elif hi == 0x20:
|
||||
vals = [v - 256 if v >= 128 else v
|
||||
for v in body[i + 2:i + 2 + nn]]
|
||||
elif hi == 0x30:
|
||||
vals = unpack12(body[i + 2:i + length])
|
||||
else:
|
||||
vals = [_i16(body, i + 2 + 2 * k) for k in range(nn)]
|
||||
for v in vals:
|
||||
if v is None:
|
||||
pass # RLE hold, in delta AND absolute modes
|
||||
elif absolute:
|
||||
cur = v
|
||||
else:
|
||||
cur += v
|
||||
out[channel].append(cur)
|
||||
i += length
|
||||
|
||||
# Segment 0 is an implicit Tran record carried in the preamble.
|
||||
if preamble == MODE_DELTA:
|
||||
out["Tran"].extend([_i16(body, 3), _i16(body, 5)])
|
||||
run("Tran", 7, first, absolute=False)
|
||||
else:
|
||||
out["Tran"].extend(unpack12(body[3:first]))
|
||||
|
||||
for rec in walk_records(body, first):
|
||||
ch, off, mode, end = (rec["channel"], rec["offset"],
|
||||
rec["mode"], rec["end"])
|
||||
if mode == MODE_DELTA:
|
||||
out[ch].extend([_i16(body, off + 10), _i16(body, off + 12)])
|
||||
run(ch, off + 14, end, absolute=False)
|
||||
elif mode == MODE_ABSOLUTE:
|
||||
run(ch, off + 10, end, absolute=True)
|
||||
elif mode == MODE_RAW12:
|
||||
out[ch].extend(unpack12(body[off + 10:end]))
|
||||
return out
|
||||
+2
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "seismo-relay"
|
||||
version = "0.19.0"
|
||||
version = "0.26.0"
|
||||
description = "Python client and REST server for MiniMate Plus seismographs"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
@@ -15,6 +15,7 @@ dependencies = [
|
||||
"python-multipart>=0.0.7",
|
||||
"h5py>=3.10",
|
||||
"numpy>=1.24",
|
||||
"matplotlib>=3.8",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
|
||||
@@ -5,3 +5,4 @@ pyserial
|
||||
python-multipart
|
||||
h5py
|
||||
numpy
|
||||
matplotlib
|
||||
@@ -0,0 +1,275 @@
|
||||
event_id,serial,timestamp,filename,channel,offset_ips,peak_ips,mean_over_peak,trigger_level_ips,already_flagged_ft
|
||||
1e7a7808-034c-423b-80e9-d6788da80993,BE18438,2025-11-15T08:57:40,T438LBX4.W40W,Vert,0.2722,0.2930,0.929,0.2,0
|
||||
346e383f-c5a1-41d1-b972-3d652e599d39,BE18438,2025-11-15T09:13:15,T438LBX5.M30W,Vert,0.2747,0.2930,0.938,0.2,0
|
||||
45ef3023-22c5-44a8-a606-a0900bc17861,BE18438,2025-11-15T09:16:13,T438LBX5.R10W,Vert,0.2929,0.3027,0.967,0.2,0
|
||||
1cbcd2aa-ec55-4e2f-af42-7178f26cc6a1,BE18438,2025-11-15T09:19:29,T438LBX5.WH0W,Vert,0.2816,0.2979,0.945,0.2,0
|
||||
caf43634-4528-4fd5-9674-5f4f563661c0,BE18438,2025-11-15T09:22:32,T438LBX6.1K0W,Vert,0.2883,0.2930,0.984,0.2,0
|
||||
456ae646-c834-4e5c-82f1-7df18b3440a1,BE18438,2025-11-15T09:25:31,T438LBX6.6J0W,Vert,0.3189,0.3223,0.989,0.2,0
|
||||
afb91ba2-351b-42a0-b33f-acebd5f1829d,BE18438,2025-11-15T09:28:29,T438LBX6.BH0W,Vert,0.3057,0.3076,0.994,0.2,0
|
||||
39847146-3537-4300-943d-01c0c771e9cd,BE18438,2025-11-15T09:31:26,T438LBX6.GE0W,Vert,0.3225,0.3271,0.986,0.2,0
|
||||
e47335c1-fc3f-4c90-88c6-8edd0f296ce4,BE18438,2025-11-15T09:34:24,T438LBX6.LC0W,Vert,0.3275,0.3320,0.986,0.2,0
|
||||
25b6eda6-ba98-422f-8834-94b6cbe34971,BE18438,2025-11-15T09:37:22,T438LBX6.QA0W,Vert,0.3398,0.3418,0.994,0.2,0
|
||||
7af99377-e47f-4914-8e91-ac7f7f50b8c6,BE18438,2025-11-15T09:40:20,T438LBX6.V80W,Vert,0.3515,0.3564,0.986,0.2,0
|
||||
c4330605-c257-49ef-aede-20deb641e7d7,BE18438,2025-11-15T10:09:48,T438LBX8.8C0W,Vert,0.3605,0.3955,0.912,0.2,0
|
||||
b665caf9-64ee-4352-a391-60c1ddeebc1e,BE18438,2026-02-25T10:58:04,T438LH66.GS0W,Vert,0.1803,0.1953,0.923,0.2,0
|
||||
3b0c32c3-fd16-4b83-9917-942a56dea168,BE18438,2026-02-25T18:12:04,T438LH6Q.K40W,Vert,0.1869,0.1953,0.957,0.2,0
|
||||
ca66e601-d10f-4424-9c26-08a688e7b08c,BE18438,2026-02-25T18:17:16,T438LH6Q.SS0W,Vert,0.1870,0.1953,0.958,0.2,0
|
||||
31aa30ba-eb0a-49a9-98ca-c77d2cc31275,BE18438,2026-02-25T18:21:11,T438LH6Q.ZB0W,Vert,0.1868,0.1953,0.956,0.2,0
|
||||
fdb55a93-fc91-4fdf-a7f4-fdd1a6b48f59,BE18438,2026-02-25T18:26:27,T438LH6R.830W,Vert,0.1893,0.1953,0.969,0.2,0
|
||||
cbd718d7-2378-4d74-8656-842f229d19a8,BE18438,2026-02-25T18:33:25,T438LH6R.JP0W,Vert,0.1887,0.1953,0.966,0.2,0
|
||||
bfaf58ec-6163-47eb-9d2a-70da880bd948,BE18438,2026-02-25T18:37:48,T438LH6R.R00W,Vert,0.1872,0.1953,0.959,0.2,0
|
||||
ddaa530b-886e-4415-b93a-f4ebf4c4a882,BE18438,2026-02-25T18:59:54,T438LH6S.RU0W,Vert,0.1874,0.1953,0.959,0.2,0
|
||||
57f15284-ab69-48fc-9660-8c347c80c681,BE18438,2026-02-25T19:15:58,T438LH6T.IM0W,Vert,0.1873,0.1953,0.959,0.2,0
|
||||
03715718-7aa8-4e1d-9b0b-c2ab75fc1975,BE18438,2026-02-25T19:19:58,T438LH6T.PA0W,Vert,0.1891,0.1953,0.968,0.2,0
|
||||
9f921cd5-1bf9-4713-aef6-41e7f780eff1,BE18438,2026-02-25T19:24:02,T438LH6T.W20W,Vert,0.1871,0.1953,0.958,0.2,0
|
||||
44994949-58d4-44fa-bd78-ed75b8acc667,BE18438,2026-02-25T19:44:57,T438LH6U.UX0W,Vert,0.1877,0.1953,0.961,0.2,0
|
||||
c4be01c3-1001-4e17-aecd-d6d26dbb09f3,BE18438,2026-02-25T19:49:19,T438LH6V.270W,Vert,0.1884,0.1953,0.964,0.2,0
|
||||
3db004e6-ee34-43c5-ae8e-f22894ead5d0,BE18438,2026-02-25T20:08:22,T438LH6V.XY0W,Vert,0.1878,0.1953,0.962,0.2,0
|
||||
d276ae48-0434-41e5-af43-e0fb366acf11,BE18438,2026-02-25T20:11:33,T438LH6W.390W,Vert,0.1880,0.1953,0.963,0.2,0
|
||||
c027dc12-88fd-4a45-872b-a6a945f2008e,BE18438,2026-02-25T20:14:35,T438LH6W.8B0W,Vert,0.1874,0.1953,0.959,0.2,0
|
||||
9665bc3a-3d08-4852-b008-37ef8bfd0023,BE18438,2026-02-25T20:18:51,T438LH6W.FF0W,Vert,0.1884,0.1953,0.965,0.2,0
|
||||
5fb5a05e-d7e2-4268-9b85-cfe8d82aa6c9,BE18438,2026-02-25T20:29:50,T438LH6W.XQ0W,Vert,0.1890,0.1953,0.968,0.2,0
|
||||
57ec0b10-9324-4459-a07e-0c8532b8928f,BE18438,2026-02-25T20:35:39,T438LH6X.7F0W,Vert,0.1889,0.1953,0.967,0.2,0
|
||||
ac86f73f-1174-4fae-a206-ecdcb73e1ffc,BE18438,2026-02-25T20:39:12,T438LH6X.DC0W,Vert,0.1887,0.1953,0.966,0.2,0
|
||||
dcf25ddd-9cf0-41c1-b109-f3ef2e490ce5,BE18438,2026-02-25T20:43:41,T438LH6X.KT0W,Vert,0.1871,0.1953,0.958,0.2,0
|
||||
aa79bbdd-2392-4ef6-8a5c-873a9f72746d,BE18438,2026-02-25T20:46:51,T438LH6X.Q30W,Vert,0.1877,0.1953,0.961,0.2,0
|
||||
ad46d1ce-b417-4c8c-b029-bb3b008ba809,BE18438,2026-02-25T20:53:33,T438LH6Y.190W,Vert,0.1882,0.1953,0.964,0.2,0
|
||||
3d3a8f34-86a7-4d70-a7e8-fa768a723325,BE18438,2026-02-26T07:03:39,T438LH7Q.A30W,Vert,0.1809,0.1953,0.926,0.2,0
|
||||
7817525f-dc3d-4f5e-b2cb-5af9ca12ede8,BE18438,2026-02-26T07:09:42,T438LH7Q.K60W,Vert,0.1814,0.1953,0.929,0.2,0
|
||||
a2091302-0b34-46c1-ab83-174be2b59bcf,BE18438,2026-02-26T13:12:35,T438LH87.CZ0W,Vert,0.1896,0.1953,0.971,0.2,0
|
||||
e1c0c9de-a900-479f-9572-9675b13296a9,BE18438,2026-02-26T13:24:46,T438LH87.XA0W,Vert,0.2237,0.2588,0.864,0.2,0
|
||||
76a6dc6b-88e1-434b-a137-f5e9b63f248e,BE18438,2026-02-26T13:27:43,T438LH88.270W,Vert,0.3185,0.3223,0.988,0.2,0
|
||||
281b508b-7982-4668-86af-9b0b28be608a,BE18438,2026-02-26T13:30:36,T438LH88.700W,Vert,0.3263,0.3320,0.983,0.2,0
|
||||
68bbaf77-bb23-40fd-94f9-f928728d90dc,BE18438,2026-02-26T13:33:28,T438LH88.BS0W,Vert,0.3207,0.3271,0.980,0.2,0
|
||||
5c975640-6ff1-441a-aa11-41642f6a6b31,BE18438,2026-02-26T13:36:21,T438LH88.GL0W,Vert,0.3261,0.3320,0.982,0.2,0
|
||||
dea248ac-1124-4bba-b054-953f86c852b2,BE18438,2026-02-26T13:40:34,T438LH88.NM0W,Vert,0.3271,0.3320,0.985,0.2,0
|
||||
4e463201-f008-41ad-9c52-11fcc3d93095,BE18438,2026-02-26T13:43:29,T438LH88.SH0W,Vert,0.3357,0.3418,0.982,0.2,0
|
||||
507262c5-d58f-4a05-a6a3-a6cbb5b4de20,BE18438,2026-02-26T13:46:24,T438LH88.XC0W,Vert,0.3372,0.3418,0.987,0.2,0
|
||||
4c2d8ee8-842f-4e44-9e03-ff34d26e4fdb,BE18438,2026-02-26T13:49:17,T438LH89.250W,Vert,0.3253,0.3320,0.980,0.2,0
|
||||
b184b112-603f-44f4-ae97-087493fbd8ce,BE18438,2026-02-26T13:52:10,T438LH89.6Y0W,Vert,0.3321,0.3369,0.986,0.2,0
|
||||
2ff1a552-5a2e-4396-9083-b9c8d334eed7,BE18438,2026-02-26T13:55:04,T438LH89.BS0W,Vert,0.3378,0.3418,0.988,0.2,0
|
||||
928e21a7-1990-4792-803e-58014d8140ce,BE18438,2026-02-26T13:57:57,T438LH89.GL0W,Vert,0.3341,0.3369,0.992,0.2,0
|
||||
f521b5db-6100-41e6-954e-0abdbf9660c1,BE18438,2026-02-26T14:00:51,T438LH89.LF0W,Vert,0.3421,0.3467,0.987,0.2,0
|
||||
efba962f-e511-41ef-9fc5-313f202a9d96,BE18438,2026-02-26T14:03:46,T438LH89.QA0W,Vert,0.3506,0.3564,0.984,0.2,0
|
||||
0b51e273-8d10-4494-bda6-8c75eaeec66f,BE18438,2026-02-26T14:06:41,T438LH89.V50W,Vert,0.3448,0.3516,0.981,0.2,0
|
||||
6d46e4ee-1647-4169-b6b2-33da32240eb9,BE18438,2026-02-26T14:09:35,T438LH89.ZZ0W,Vert,0.3463,0.3516,0.985,0.2,0
|
||||
1ca294cd-4dc2-41fb-9374-e277d4550761,BE18438,2026-02-26T14:12:28,T438LH8A.4S0W,Vert,0.3442,0.3467,0.993,0.2,0
|
||||
7b683dcf-1aed-4d9b-be1e-b10f92374398,BE18438,2026-02-26T14:15:23,T438LH8A.9N0W,Vert,0.3486,0.3516,0.992,0.2,0
|
||||
2b5cb8e7-c947-4914-bcb5-504f74603547,BE18438,2026-02-26T14:18:21,T438LH8A.EL0W,Vert,0.3519,0.3613,0.974,0.2,0
|
||||
5ea3a6bf-10de-4911-aedc-66daecf86b76,BE18438,2026-02-26T14:21:16,T438LH8A.JG0W,Vert,0.3460,0.3564,0.971,0.2,0
|
||||
d93be7f5-39ec-45fd-9949-fa531f2f9d34,BE18438,2026-02-26T14:24:13,T438LH8A.OD0W,Vert,0.3457,0.3516,0.983,0.2,0
|
||||
cfa113f2-8cee-4a1d-b1e7-0e936fa771e2,BE18438,2026-02-26T14:28:21,T438LH8A.V90W,Vert,0.3485,0.3564,0.978,0.2,0
|
||||
46d322ac-38cb-4c99-a4c2-9e9d7ad06171,BE18438,2026-02-26T14:31:17,T438LH8B.050W,Vert,0.3367,0.3467,0.971,0.2,0
|
||||
42500a83-bd67-4deb-8bb2-963ee2b8a7ce,BE18438,2026-02-26T14:34:11,T438LH8B.4Z0W,Vert,0.3365,0.3516,0.957,0.2,0
|
||||
3ccf6bda-2e88-473c-951d-9ea86d0d9363,BE18438,2026-02-26T14:37:05,T438LH8B.9T0W,Vert,0.3472,0.3564,0.974,0.2,0
|
||||
9050487d-d238-4631-b8e1-5a693a026542,BE18438,2026-02-26T14:39:58,T438LH8B.EM0W,Vert,0.3420,0.3564,0.959,0.2,0
|
||||
e62989e4-a326-4bae-8d47-a8becee96462,BE18438,2026-02-26T14:42:52,T438LH8B.JG0W,Vert,0.3430,0.3564,0.962,0.2,0
|
||||
f0e30fab-dc57-4189-8439-48df17007a2c,BE18438,2026-02-26T14:45:46,T438LH8B.OA0W,Vert,0.3389,0.3516,0.964,0.2,0
|
||||
03e1ca09-78df-4c6f-9915-0b6e4f2141d2,BE18438,2026-02-26T14:48:43,T438LH8B.T70W,Vert,0.3449,0.3564,0.968,0.2,0
|
||||
945d39f7-1b98-4a1f-80a8-6a18fd9df25f,BE18438,2026-02-26T14:51:37,T438LH8B.Y10W,Vert,0.3522,0.3613,0.975,0.2,0
|
||||
d27eb2e3-e313-4125-98f4-f9d6d3737d28,BE18438,2026-02-26T14:54:32,T438LH8C.2W0W,Vert,0.3502,0.3613,0.969,0.2,0
|
||||
916901cb-ebea-441e-a2a1-40f4e49f32f4,BE18438,2026-02-26T14:57:25,T438LH8C.7P0W,Vert,0.3524,0.3662,0.962,0.2,0
|
||||
5d8d7e29-fdbb-4fa3-bd25-506c9352a354,BE18438,2026-02-26T15:01:35,T438LH8C.EN0W,Vert,0.3530,0.3613,0.977,0.2,0
|
||||
c6c7a3af-b03b-43dc-97de-024f8e09b62f,BE18438,2026-02-26T15:04:27,T438LH8C.JF0W,Vert,0.3514,0.3613,0.973,0.2,0
|
||||
b6856898-3d10-4967-9577-7f17902f77ea,BE18438,2026-02-26T15:11:34,T438LH8C.VA0W,Vert,0.3566,0.3613,0.987,0.2,0
|
||||
7a4802f6-621e-4230-8d8c-d7f0c9a65bf2,BE18438,2026-02-26T15:14:24,T438LH8D.000W,Vert,0.3594,0.3711,0.968,0.2,0
|
||||
79f38b7e-ec56-417e-943a-8c944252c2b8,BE18438,2026-02-26T15:18:32,T438LH8D.6W0W,Vert,0.3550,0.3613,0.983,0.2,0
|
||||
1b4190c4-0d54-48ba-8ff5-8ddb0eb91e50,BE18438,2026-02-26T15:22:22,T438LH8D.DA0W,Vert,0.3571,0.3613,0.988,0.2,0
|
||||
de57b5ae-a3a1-4ede-9d2b-3e87bfb3fd19,BE9558,2026-04-14T11:16:32,K558LJN3.BK0W,Tran,0.3448,0.3662,0.942,0.2,0
|
||||
43afeaf5-02ec-41f6-9e23-0c9772821ed4,BE9558,2026-04-14T11:27:15,K558LJN3.TF0W,Tran,0.3094,0.3223,0.960,0.2,0
|
||||
8123c0ef-84c9-4f6c-8d82-9dc32e2e470d,BE9558,2026-04-14T14:45:30,K558LJNC.ZU0W,Tran,0.2721,0.3564,0.763,0.2,0
|
||||
8c787af3-596e-411b-9e10-29485fa5114f,BE9558,2026-04-29T16:18:47,K558LKF9.BB0W,Tran,0.2943,0.3027,0.972,0.2,0
|
||||
431928ff-b4c4-4caa-b933-acc917f3717c,BE9558,2026-05-04T15:02:30,K558LKOF.460W,Tran,0.4364,0.5225,0.835,0.2,0
|
||||
6c3c07f8-c36a-4493-acce-7441c9d22cec,BE9558,2026-05-15T08:50:06,K558LL8B.7I0W,Long,0.2892,0.2930,0.987,0.2,0
|
||||
13c268df-b652-422e-a642-6453f6a314aa,BE9558,2026-05-15T10:18:34,K558LL8F.AY0W,Long,0.2907,0.2979,0.976,0.2,0
|
||||
9b0d0871-8810-467d-806a-5bbfa4e667fe,BE9558,2026-05-15T15:52:00,K558LL8U.QO0W,Long,0.2659,0.2979,0.893,0.2,0
|
||||
092640f9-a944-48b7-b872-364d75c2c5e7,BE9558,2026-05-15T16:13:12,K558LL8V.Q00W,Long,0.2428,0.2979,0.815,0.2,0
|
||||
0573741a-96ab-4b36-af7a-b5bc11a79009,BE9558,2026-05-16T03:23:26,K558LL9Q.R20W,Long,0.2861,0.2930,0.976,0.2,0
|
||||
321f03ea-6696-47de-ad46-2be43d4d6cae,BE9558,2026-05-16T03:30:49,K558LL9R.3D0W,Long,0.2886,0.2930,0.985,0.2,0
|
||||
cc423a6a-3e3c-466a-b39c-6146ca7f34c8,BE9558,2026-05-16T03:33:55,K558LL9R.8J0W,Long,0.2880,0.2881,1.000,0.2,0
|
||||
efa52a14-cc68-4bea-aab4-4ee3a3cbff3a,BE9558,2026-05-16T03:36:55,K558LL9R.DJ0W,Long,0.2890,0.2930,0.986,0.2,0
|
||||
92895bfe-122f-4cdc-bd3d-40609633d278,BE9558,2026-05-16T03:43:41,K558LL9R.OT0W,Long,0.2880,0.2881,1.000,0.2,0
|
||||
2a4c81db-2307-44e5-9b27-d5154d98e38d,BE9558,2026-05-16T03:46:36,K558LL9R.TO0W,Long,0.2921,0.2979,0.981,0.2,0
|
||||
656b0fdc-e275-4c9c-8936-9eee267ea04e,BE9558,2026-05-16T03:49:28,K558LL9R.YG0W,Long,0.2966,0.2979,0.996,0.2,0
|
||||
3b9989ae-e0f2-4652-9724-c145603543d2,BE9558,2026-05-16T03:52:29,K558LL9S.3H0W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
837d0d84-d609-4f4a-b542-b7e2b064ea22,BE9558,2026-05-16T03:56:32,K558LL9S.A80W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
affcb008-ab99-4bc5-8f35-83dbe620499d,BE9558,2026-05-16T04:02:50,K558LL9S.KQ0W,Long,0.2896,0.2930,0.989,0.2,0
|
||||
e1f1c6d2-545c-451f-9018-714d52e20a05,BE9558,2026-05-16T04:05:47,K558LL9S.PN0W,Long,0.3024,0.3076,0.983,0.2,0
|
||||
93ef80f1-7e83-4703-a0f9-89bbfeeae6c3,BE9558,2026-05-16T04:08:41,K558LL9S.UH0W,Long,0.2976,0.2979,0.999,0.2,0
|
||||
5c118ca9-fc37-4080-876d-b3f57ce0b121,BE9558,2026-05-16T04:11:42,K558LL9S.ZI0W,Long,0.2881,0.2930,0.983,0.2,0
|
||||
d98b2eaa-7763-4c78-88fb-c21195cb9978,BE9558,2026-05-16T04:14:38,K558LL9T.4E0W,Long,0.2898,0.2930,0.989,0.2,0
|
||||
6a146a01-0d02-4413-b231-ecb4a6fde776,BE9558,2026-05-16T04:17:35,K558LL9T.9B0W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
f6587a55-27e3-454f-997e-57e7516a296c,BE9558,2026-05-16T04:20:32,K558LL9T.E80W,Long,0.3046,0.3076,0.990,0.2,0
|
||||
1fb48250-2214-41e6-92cb-362aff1ba62b,BE9558,2026-05-16T04:26:05,K558LL9T.NH0W,Long,0.2876,0.2930,0.982,0.2,0
|
||||
2f4f3d06-1189-4e28-a1ac-5454ea586a0c,BE9558,2026-05-16T04:59:47,K558LL9V.7N0W,Long,0.2961,0.3027,0.978,0.2,0
|
||||
62b7bdab-b744-41e4-8d0e-c9141b9d4821,BE9558,2026-05-16T05:02:46,K558LL9V.CM0W,Long,0.2903,0.2930,0.991,0.2,0
|
||||
cadcb6dc-74c0-48b5-974c-87bb7a57816c,BE9558,2026-05-16T05:05:43,K558LL9V.HJ0W,Long,0.3090,0.3125,0.989,0.2,0
|
||||
a0235177-be5a-4f11-b741-c65744698e5b,BE9558,2026-05-16T05:08:35,K558LL9V.MB0W,Long,0.3167,0.3223,0.983,0.2,0
|
||||
1968c2f6-f52c-4544-a0ed-f79b91ce0da0,BE9558,2026-05-16T05:11:28,K558LL9V.R40W,Long,0.3446,0.3516,0.980,0.2,0
|
||||
caa06b94-8813-4949-b47b-61ffb16e61c4,BE9558,2026-05-16T05:14:22,K558LL9V.VY0W,Long,0.3318,0.3320,0.999,0.2,0
|
||||
fdaa8101-f033-47e6-9c65-abd76dea1870,BE9558,2026-05-16T05:17:16,K558LL9W.0S0W,Long,0.3407,0.3418,0.997,0.2,0
|
||||
29bd16bd-81b9-4ccd-a981-f1a80858536c,BE9558,2026-05-16T05:23:05,K558LL9W.AH0W,Long,0.3450,0.3516,0.981,0.2,0
|
||||
1f8bc862-d5fd-4cce-abc0-e2bd8c2f11fa,BE9558,2026-05-16T05:26:00,K558LL9W.FC0W,Long,0.3417,0.3467,0.986,0.2,0
|
||||
20220068-d498-4fca-9a2a-a7fd2ee52ab1,BE9558,2026-05-16T05:28:53,K558LL9W.K50W,Long,0.3516,0.3564,0.986,0.2,0
|
||||
9816a261-3118-417a-8334-ace36687ad8f,BE9558,2026-05-16T05:31:47,K558LL9W.OZ0W,Long,0.3416,0.3467,0.985,0.2,0
|
||||
5d2c76d7-543d-4557-9caf-996a69ab00bd,BE9558,2026-05-16T05:34:42,K558LL9W.TU0W,Long,0.3537,0.3564,0.992,0.2,0
|
||||
c7b5ae00-52e7-4920-aa27-49d3b3daff92,BE9558,2026-05-16T05:37:36,K558LL9W.YO0W,Long,0.3517,0.3564,0.987,0.2,0
|
||||
07db8fd8-ccef-4a5a-9d97-9f318f73a478,BE9558,2026-05-16T05:40:31,K558LL9X.3J0W,Long,0.3574,0.3613,0.989,0.2,0
|
||||
790fcff9-e266-4a12-87f0-a072990d2533,BE9558,2026-05-16T05:43:26,K558LL9X.8E0W,Long,0.3650,0.3662,0.997,0.2,0
|
||||
f4245f61-1dde-43dc-a121-98e102f6a193,BE9558,2026-05-16T05:50:28,K558LL9X.K40W,Long,0.3856,0.3906,0.987,0.2,0
|
||||
5a3bce7b-358e-4260-876f-3f853163d7cf,BE9558,2026-05-16T05:53:22,K558LL9X.OY0W,Long,0.3847,0.3857,0.997,0.2,0
|
||||
37c2b4b1-7a1b-43e7-b513-2c16f582109c,BE9558,2026-05-16T05:56:15,K558LL9X.TR0W,Long,0.3906,0.3955,0.988,0.2,0
|
||||
57fde109-1d8a-45a1-b398-5bd28c3e47f1,BE9558,2026-05-16T05:59:10,K558LL9X.YM0W,Long,0.4000,0.4004,0.999,0.2,0
|
||||
1e41ab40-93be-405c-a464-f7a57524d3b3,BE9558,2026-05-16T06:02:02,K558LL9Y.3E0W,Long,0.3825,0.3857,0.992,0.2,0
|
||||
e9d61eb5-fae8-4902-8fab-4828ffa8e6da,BE9558,2026-05-16T06:04:57,K558LL9Y.890W,Long,0.3802,0.3809,0.998,0.2,0
|
||||
c0e964e0-7788-4e41-bc41-6e479c3dc81b,BE9558,2026-05-16T06:07:51,K558LL9Y.D30W,Long,0.3954,0.4004,0.987,0.2,0
|
||||
0b2df8e5-1689-4fe6-abad-30970ba10aa6,BE9558,2026-05-16T06:16:06,K558LL9Y.QU0W,Long,0.4051,0.4053,1.000,0.2,0
|
||||
2bc6ce73-464b-469c-9e8f-3bf6f6cfae1d,BE9558,2026-05-16T06:21:51,K558LL9Z.0F0W,Long,0.3910,0.3955,0.989,0.2,0
|
||||
b8603ee1-616a-451e-a2cd-61f8f2634cd0,BE9558,2026-05-16T06:24:44,K558LL9Z.580W,Long,0.3969,0.4004,0.991,0.2,0
|
||||
1aecf582-66a2-4ebb-80f9-04b3aeba331a,BE9558,2026-05-16T06:27:39,K558LL9Z.A30W,Long,0.3915,0.3955,0.990,0.2,0
|
||||
885aedfd-7a1a-4120-8176-7c344dd3d8fe,BE9558,2026-05-16T06:30:30,K558LL9Z.EU0W,Long,0.4025,0.4053,0.993,0.2,0
|
||||
ec15930f-47f5-4752-afc2-427ee156ac95,BE9558,2026-05-16T06:33:25,K558LL9Z.JP0W,Long,0.4060,0.4102,0.990,0.2,0
|
||||
5ca23f47-2a38-4a54-99dd-041287aa9510,BE9558,2026-05-16T06:36:17,K558LL9Z.OH0W,Long,0.4054,0.4102,0.988,0.2,0
|
||||
03f371cf-81bc-4681-80f0-ef6fa437da85,BE9558,2026-05-16T06:39:09,K558LL9Z.T90W,Long,0.4052,0.4102,0.988,0.2,0
|
||||
ed386f54-140d-45e8-ad51-6585a58b4375,BE9558,2026-05-16T06:44:54,K558LLA0.2U0W,Long,0.3993,0.4004,0.997,0.2,0
|
||||
579f1c3f-4c1e-42a3-aa89-69aa93514033,BE9558,2026-05-16T06:47:47,K558LLA0.7N0W,Long,0.4001,0.4053,0.987,0.2,0
|
||||
57024de6-07ea-41f4-b916-c6adc3f51636,BE9558,2026-05-16T06:50:40,K558LLA0.CG0W,Long,0.4103,0.4150,0.989,0.2,0
|
||||
36bf5adf-afb5-4a5e-a106-1afbd1f56c7b,BE9558,2026-05-16T06:54:49,K558LLA0.JD0W,Long,0.4069,0.4150,0.980,0.2,0
|
||||
3e2f831b-5228-46ff-9acb-75d8c86f8bc1,BE9558,2026-05-16T06:57:43,K558LLA0.O70W,Long,0.4108,0.4150,0.990,0.2,0
|
||||
1775fa20-568b-4294-b9ca-561201a66c5b,BE9558,2026-05-16T07:00:38,K558LLA0.T20W,Long,0.3967,0.4004,0.991,0.2,0
|
||||
fd391469-03f9-4d8d-bccd-3af50c91e5b7,BE9558,2026-05-16T07:03:33,K558LLA0.XX0W,Long,0.3927,0.3955,0.993,0.2,0
|
||||
02b52ef6-b707-4dcb-b58f-43da02698832,BE9558,2026-05-16T07:06:27,K558LLA1.2R0W,Long,0.3824,0.3857,0.991,0.2,0
|
||||
8d45333f-e101-4249-9e27-913c583a0a8d,BE9558,2026-05-16T07:09:21,K558LLA1.7L0W,Long,0.4085,0.4150,0.984,0.2,0
|
||||
361d11ce-f42a-4d04-8270-ee3771fe4f09,BE9558,2026-05-16T07:12:14,K558LLA1.CE0W,Long,0.4017,0.4053,0.991,0.2,0
|
||||
59218125-ed5d-4457-aa8b-35ba03441363,BE9558,2026-05-16T07:15:07,K558LLA1.H70W,Long,0.3934,0.3955,0.995,0.2,0
|
||||
a603e55a-2ad6-4fc9-8c8c-0dc7be95c3e7,BE9558,2026-05-16T07:23:43,K558LLA1.VJ0W,Long,0.3806,0.3857,0.987,0.2,0
|
||||
c8d07902-93ea-4b03-9e69-9ad6ed5bffb1,BE9558,2026-05-16T07:26:36,K558LLA2.0C0W,Long,0.3807,0.3857,0.987,0.2,0
|
||||
4c46c0c7-42f0-4648-827e-1995f733b18f,BE9558,2026-05-16T07:30:44,K558LLA2.780W,Long,0.3667,0.3711,0.988,0.2,0
|
||||
04759a00-ba3e-4959-a4cb-be8fc1f3004e,BE9558,2026-05-16T07:36:28,K558LLA2.GS0W,Long,0.3514,0.3516,1.000,0.2,0
|
||||
0b6b0856-bd87-4a07-a5b4-f13d99e04a12,BE9558,2026-05-16T07:39:20,K558LLA2.LK0W,Long,0.3512,0.3516,0.999,0.2,0
|
||||
3d81a8bd-464d-4050-8a76-25e8373d1ddb,BE9558,2026-05-16T07:42:12,K558LLA2.QC0W,Long,0.3350,0.3369,0.994,0.2,0
|
||||
b8b9c0c4-c388-4acb-955a-be4ac356afce,BE9558,2026-05-16T07:45:04,K558LLA2.V40W,Long,0.3563,0.3564,1.000,0.2,0
|
||||
cb3d142a-fb84-4a21-a298-f61bb869b036,BE9558,2026-05-16T07:49:13,K558LLA3.210W,Long,0.3663,0.3711,0.987,0.2,0
|
||||
7401b19b-bc9d-43f0-b395-f4323aca5c72,BE9558,2026-05-16T07:52:06,K558LLA3.6U0W,Long,0.3612,0.3662,0.986,0.2,0
|
||||
2236df76-a9e6-401f-9176-ad565242f2cf,BE9558,2026-05-16T07:57:52,K558LLA3.GG0W,Long,0.3366,0.3369,0.999,0.2,0
|
||||
a645846c-cae4-4aa5-a2e6-85166bd4dd62,BE9558,2026-05-16T08:00:44,K558LLA3.L80W,Long,0.3265,0.3271,0.998,0.2,0
|
||||
7212bd33-99a9-4659-9f0b-c98cc8d1e8bc,BE9558,2026-05-16T08:04:51,K558LLA3.S30W,Long,0.3418,0.3467,0.986,0.2,0
|
||||
2cc4bf33-c63a-4c65-b0e2-5e61a9146a5d,BE9558,2026-05-16T08:07:43,K558LLA3.WV0W,Long,0.3405,0.3418,0.996,0.2,0
|
||||
4fedb486-5f1f-4623-a01f-083e829f0565,BE9558,2026-05-16T08:10:35,K558LLA4.1N0W,Long,0.3515,0.3564,0.986,0.2,0
|
||||
58aff0ba-0f9b-45e1-9bbe-a990d16192ae,BE9558,2026-05-16T08:13:27,K558LLA4.6F0W,Long,0.3513,0.3516,0.999,0.2,0
|
||||
e56d87e5-e1d4-4947-b6a5-3bbd2773c54a,BE9558,2026-05-16T08:20:03,K558LLA4.HF0W,Long,0.3564,0.3613,0.986,0.2,0
|
||||
0e96e61e-6a21-4e07-8e09-72d09dbfa1e6,BE9558,2026-05-16T08:25:21,K558LLA4.Q90W,Long,0.3565,0.3613,0.987,0.2,0
|
||||
19611f28-2da8-4362-a58e-dbed2e061379,BE9558,2026-05-16T08:34:19,K558LLA5.570W,Long,0.3647,0.3662,0.996,0.2,0
|
||||
bd580c1d-44d4-41fd-9f83-f462cda4099a,BE9558,2026-05-16T08:37:15,K558LLA5.A30W,Long,0.3536,0.3564,0.992,0.2,0
|
||||
2782df3b-3cb4-471a-a6f5-bbc4903a8ab9,BE9558,2026-05-16T08:44:00,K558LLA5.LC0W,Long,0.3612,0.3662,0.986,0.2,0
|
||||
d15a08f3-1c7c-4f80-8d9b-f5008c58c3d9,BE9558,2026-05-16T08:49:18,K558LLA5.U60W,Long,0.3610,0.3613,0.999,0.2,0
|
||||
03a10a6a-193a-476c-9543-f63818f69417,BE9558,2026-05-16T08:54:36,K558LLA6.300W,Long,0.3515,0.3516,1.000,0.2,0
|
||||
1c271856-8100-4c0d-bc8c-9357b47d7626,BE9558,2026-05-16T08:59:54,K558LLA6.BU0W,Long,0.3617,0.3662,0.988,0.2,0
|
||||
a85f125e-bfa2-42be-b877-2604b8d068c8,BE9558,2026-05-16T09:05:17,K558LLA6.KT0W,Long,0.3510,0.3516,0.998,0.2,0
|
||||
dde9aa71-d2e3-41ac-8388-f2bbddb6dae6,BE9558,2026-05-16T09:08:11,K558LLA6.PN0W,Long,0.3447,0.3467,0.994,0.2,0
|
||||
2f3f2be2-0ee3-422e-b3ad-83fb87512a2b,BE9558,2026-05-16T09:14:39,K558LLA7.0F0W,Long,0.3580,0.3613,0.991,0.2,0
|
||||
357a3034-8a9c-485e-8cb6-f526dd2baf6f,BE9558,2026-05-16T09:29:11,K558LLA7.ON0W,Long,0.3708,0.3760,0.986,0.2,0
|
||||
f8ad0274-8e6f-4714-82ff-d229e60f1442,BE9558,2026-05-16T09:32:06,K558LLA7.TI0W,Long,0.3567,0.3613,0.987,0.2,0
|
||||
42bb007a-2726-401a-b085-c25151b0dc24,BE9558,2026-05-16T09:35:02,K558LLA7.YE0W,Long,0.3575,0.3613,0.989,0.2,0
|
||||
c99bfc4a-db02-4bea-bea4-943c67485dba,BE9558,2026-05-16T09:37:58,K558LLA8.3A0W,Long,0.3527,0.3564,0.989,0.2,0
|
||||
8fc17de0-73f7-48bd-8d93-5451dce47e8e,BE9558,2026-05-16T09:40:52,K558LLA8.840W,Long,0.3613,0.3662,0.987,0.2,0
|
||||
bbee5276-03dd-4ca4-a7b9-aec02baac7e8,BE9558,2026-05-16T09:48:13,K558LLA8.KD0W,Long,0.3590,0.3613,0.993,0.2,0
|
||||
8dcdee10-db01-4224-9506-4181c3105d6f,BE9558,2026-05-16T09:53:31,K558LLA8.T70W,Long,0.3588,0.3613,0.993,0.2,0
|
||||
48c8be72-64d9-4da3-95b5-bbec2c5e1dbd,BE9558,2026-05-16T09:58:49,K558LLA9.210W,Long,0.3582,0.3662,0.978,0.2,0
|
||||
0da20919-7ce9-4feb-8ae9-12d9bb40c2b5,BE9558,2026-05-16T10:04:07,K558LLA9.AV0W,Long,0.3506,0.3516,0.997,0.2,0
|
||||
c2f7e9bc-8b93-42c3-96d3-e3af217dde35,BE9558,2026-05-16T10:09:25,K558LLA9.JP0W,Long,0.3506,0.3516,0.997,0.2,0
|
||||
522a0e42-d443-4447-bc71-af1832c6604e,BE9558,2026-05-16T10:14:43,K558LLA9.SJ0W,Long,0.3624,0.3662,0.990,0.2,0
|
||||
67f7e732-3c0b-439f-87c5-3c478a381418,BE9558,2026-05-16T10:20:01,K558LLAA.1D0W,Long,0.3494,0.3516,0.994,0.2,0
|
||||
251767e8-56f7-4091-a001-364d8e75c15c,BE9558,2026-05-16T10:25:19,K558LLAA.A70W,Long,0.3463,0.3516,0.985,0.2,0
|
||||
9457239d-a4ca-4476-b385-5e01fc8f6420,BE9558,2026-05-16T10:30:37,K558LLAA.J10W,Long,0.3436,0.3467,0.991,0.2,0
|
||||
43718d7c-9353-49e1-89b6-0841aeb1b276,BE9558,2026-05-16T10:35:55,K558LLAA.RV0W,Long,0.3452,0.3516,0.982,0.2,0
|
||||
f54ba557-ddfe-41d3-8f4c-8bbec9a3783c,BE9558,2026-05-16T10:41:13,K558LLAB.0P0W,Long,0.3419,0.3467,0.986,0.2,0
|
||||
dc26c758-ad99-49c1-b518-931368cdf8cf,BE9558,2026-05-16T10:46:31,K558LLAB.9J0W,Long,0.3463,0.3516,0.985,0.2,0
|
||||
10917eb2-d151-461c-a8cb-e9660da5a5b0,BE9558,2026-05-16T10:51:49,K558LLAB.ID0W,Long,0.3520,0.3564,0.987,0.2,0
|
||||
4938a5e6-d53b-40ee-be2b-06ec0e60398c,BE9558,2026-05-16T10:57:07,K558LLAB.R70W,Long,0.3541,0.3564,0.993,0.2,0
|
||||
0711b51d-55bd-48be-b51e-2aad67107a60,BE9558,2026-05-16T11:13:01,K558LLAC.HP0W,Long,0.3661,0.3711,0.986,0.2,0
|
||||
065564b6-aa49-40e7-9ea6-c75defdc60fe,BE9558,2026-05-16T11:18:19,K558LLAC.QJ0W,Long,0.3622,0.3662,0.989,0.2,0
|
||||
ffb6b230-1d70-4e0e-ba30-e945339a122a,BE9558,2026-05-16T11:23:37,K558LLAC.ZD0W,Long,0.3711,0.3760,0.987,0.2,0
|
||||
52b4da82-c1e0-4a8a-8365-51b090787005,BE9558,2026-05-16T11:28:55,K558LLAD.870W,Long,0.3644,0.3662,0.995,0.2,0
|
||||
cdbff3d8-fbfe-4bea-8bd6-c898800e81ba,BE9558,2026-05-16T11:39:31,K558LLAD.PV0W,Long,0.3609,0.3662,0.986,0.2,0
|
||||
3fb0bc30-1463-4cfc-9e7f-386c0eb2a34a,BE9558,2026-05-16T11:44:49,K558LLAD.YP0W,Long,0.3553,0.3564,0.997,0.2,0
|
||||
ba1f5ec8-aef7-4a9e-ac1f-276cf016e285,BE9558,2026-05-16T11:50:07,K558LLAE.7J0W,Long,0.3479,0.3516,0.990,0.2,0
|
||||
b1dd4df7-34a9-4512-a903-f8242b236fd2,BE9558,2026-05-16T11:55:25,K558LLAE.GD0W,Long,0.3427,0.3467,0.988,0.2,0
|
||||
1f23aa28-c026-4bc7-b3d1-7c78fd76a673,BE9558,2026-05-16T12:00:43,K558LLAE.P70W,Long,0.3454,0.3467,0.996,0.2,0
|
||||
0d91f54d-b20d-4a50-b7dd-d071c39a0690,BE9558,2026-05-16T12:06:01,K558LLAE.Y10W,Long,0.3431,0.3467,0.990,0.2,0
|
||||
12ccdecd-5fd9-4465-9813-3d6006ec32f3,BE9558,2026-05-16T12:11:19,K558LLAF.6V0W,Long,0.3433,0.3467,0.990,0.2,0
|
||||
a7024f1a-f071-48ab-820f-99bdf87366b5,BE9558,2026-05-16T12:16:37,K558LLAF.FP0W,Long,0.3361,0.3369,0.998,0.2,0
|
||||
de0fa439-30b8-4607-a3c3-7e17191e4624,BE9558,2026-05-16T12:21:55,K558LLAF.OJ0W,Long,0.3274,0.3320,0.986,0.2,0
|
||||
f9374ec3-05e5-477f-8e1a-0c862fed2a50,BE9558,2026-05-16T12:27:13,K558LLAF.XD0W,Long,0.3449,0.3467,0.995,0.2,0
|
||||
424cb275-3743-4174-95f0-0ca1205b374c,BE9558,2026-05-16T12:32:31,K558LLAG.670W,Long,0.3370,0.3418,0.986,0.2,0
|
||||
9accde13-cefa-41b8-bd0a-cef2ffed59b0,BE9558,2026-05-16T12:37:49,K558LLAG.F10W,Long,0.3465,0.3467,0.999,0.2,0
|
||||
4665be38-1956-4b14-b931-068ba9af5c5e,BE9558,2026-05-16T12:48:25,K558LLAG.WP0W,Long,0.3453,0.3516,0.982,0.2,0
|
||||
1aedf624-1a99-43e1-a8f2-f9d358b97f61,BE9558,2026-05-16T12:53:43,K558LLAH.5J0W,Long,0.3366,0.3418,0.985,0.2,0
|
||||
c15e1799-91d7-425e-ad17-2ba3d170d81e,BE9558,2026-05-16T13:04:19,K558LLAH.N70W,Long,0.3348,0.3369,0.994,0.2,0
|
||||
72d4c4ea-19ca-4cc6-9b04-7a2b70122c67,BE9558,2026-05-16T13:09:37,K558LLAH.W10W,Long,0.3272,0.3320,0.986,0.2,0
|
||||
b4ebf2c9-1f6d-4594-9810-40479e87c0a5,BE9558,2026-05-16T13:14:55,K558LLAI.4V0W,Long,0.3297,0.3320,0.993,0.2,0
|
||||
bb297e9e-548f-4dae-8b1a-0f161af2e766,BE9558,2026-05-16T13:20:13,K558LLAI.DP0W,Long,0.3272,0.3320,0.986,0.2,0
|
||||
87562c24-63db-48bd-9962-72a20a40f2ff,BE9558,2026-05-16T13:36:07,K558LLAJ.470W,Long,0.3174,0.3223,0.985,0.2,0
|
||||
01e9cc58-3bea-4f38-8499-a2c20e5f8550,BE9558,2026-05-16T13:46:52,K558LLAJ.M40W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
5ae7503d-ae17-4063-9208-6a420699e1ab,BE9558,2026-05-16T14:00:35,K558LLAK.8Z0W,Long,0.2879,0.2930,0.983,0.2,0
|
||||
e009ea3c-1534-4154-8623-e180ed4db9fb,BE9558,2026-05-16T14:06:19,K558LLAK.IJ0W,Long,0.2882,0.2930,0.984,0.2,0
|
||||
cd4e21f5-512b-4b2b-8054-bec01aa06400,BE9558,2026-05-16T14:12:03,K558LLAK.S30W,Long,0.2857,0.2930,0.975,0.2,0
|
||||
ae5b780f-2038-4ccf-8bfc-b15b87be139e,BE9558,2026-05-16T14:17:22,K558LLAL.0Y0W,Long,0.2899,0.2930,0.989,0.2,0
|
||||
d8c3fb81-8c66-4ebc-b33a-0559bc03334b,BE9558,2026-05-16T14:22:40,K558LLAL.9S0W,Long,0.3009,0.3027,0.994,0.2,0
|
||||
990a4c7a-3c51-4d4a-8ab7-416ccb97d29c,BE9558,2026-05-16T14:27:58,K558LLAL.IM0W,Long,0.3057,0.3076,0.994,0.2,0
|
||||
68d7a2c3-d899-4e75-96fb-3bf16ae6ea6f,BE9558,2026-05-16T14:33:16,K558LLAL.RG0W,Long,0.3110,0.3125,0.995,0.2,0
|
||||
73505b8c-f912-4116-b903-a8a4c75524d3,BE9558,2026-05-16T14:38:34,K558LLAM.0A0W,Long,0.3172,0.3223,0.984,0.2,0
|
||||
8d3c9602-7efa-488a-801b-3228bd85ab14,BE9558,2026-05-16T14:43:51,K558LLAM.930W,Long,0.3136,0.3174,0.988,0.2,0
|
||||
243e16ee-860a-4960-bc15-b797ad7e9735,BE9558,2026-05-16T14:49:08,K558LLAM.HW0W,Long,0.3135,0.3174,0.988,0.2,0
|
||||
e90c8d90-6d41-4788-9ee6-a29e4bfcc16b,BE9558,2026-05-16T15:19:35,K558LLAN.WN0W,Long,0.3132,0.3174,0.987,0.2,0
|
||||
4182b0e7-7811-46b8-87d1-a4dd0c152f3b,BE9558,2026-05-16T15:28:45,K558LLAO.BX0W,Long,0.3023,0.3076,0.983,0.2,0
|
||||
28a790da-0e48-4fe4-b8ba-2c82cc6bfa79,BE9558,2026-05-16T15:34:02,K558LLAO.KQ0W,Long,0.3176,0.3223,0.985,0.2,0
|
||||
093d2fa3-7a4b-4f0f-abda-71155ebe2dfb,BE9558,2026-05-16T15:39:19,K558LLAO.TJ0W,Long,0.3223,0.3271,0.985,0.2,0
|
||||
68dc9560-4082-49b6-af04-9244773ffbc1,BE9558,2026-05-16T15:44:36,K558LLAP.2C0W,Long,0.3227,0.3271,0.986,0.2,0
|
||||
ad6b268a-165d-4b1d-b0b3-f58db7c9b0e4,BE9558,2026-05-16T15:49:53,K558LLAP.B50W,Long,0.3177,0.3223,0.986,0.2,0
|
||||
046c5cb4-56b3-48c0-83c2-bf1f30837940,BE9558,2026-05-16T15:55:10,K558LLAP.JY0W,Long,0.3174,0.3223,0.985,0.2,0
|
||||
1b76edf4-3b1c-4bcb-a73c-27334981c350,BE9558,2026-05-16T16:00:27,K558LLAP.SR0W,Long,0.3127,0.3174,0.985,0.2,0
|
||||
a0264171-a682-4396-ad8a-cda3b2964533,BE9558,2026-05-16T16:06:55,K558LLAQ.3J0W,Long,0.2885,0.2930,0.985,0.2,0
|
||||
707da1f6-ee81-4e57-abd5-98295c14651b,BE9558,2026-05-16T16:12:30,K558LLAQ.CU0W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
b8115b64-8739-42c8-b541-713ab6b68bcd,BE9558,2026-05-16T16:17:53,K558LLAQ.LT0W,Long,0.2881,0.2930,0.983,0.2,0
|
||||
fb179c36-fef1-4df6-b0a0-2bd7792ea910,BE9558,2026-05-16T16:23:11,K558LLAQ.UN0W,Long,0.2933,0.2979,0.985,0.2,0
|
||||
0cec8793-c3c1-486b-a33a-4dbf9cb069b0,BE9558,2026-05-16T16:33:46,K558LLAR.CA0W,Long,0.3017,0.3027,0.997,0.2,0
|
||||
c531b052-ee04-4c66-888b-21e97445a615,BE9558,2026-05-16T16:49:37,K558LLAS.2P0W,Long,0.2922,0.2979,0.981,0.2,0
|
||||
0dc402f9-cab6-4c4a-8317-b8fc3c4b1ced,BE9558,2026-05-16T16:55:08,K558LLAS.BW0W,Long,0.2898,0.2930,0.989,0.2,0
|
||||
fd73733e-b42d-4a51-81d0-4acad6edfbd4,BE9558,2026-05-16T17:16:17,K558LLAT.B50W,Long,0.3115,0.3125,0.997,0.2,0
|
||||
6a254daa-ae27-4ac1-b334-58f776a6b276,BE9558,2026-05-16T17:26:51,K558LLAT.SR0W,Long,0.3174,0.3223,0.985,0.2,0
|
||||
0cc8e82f-5270-4508-beae-0d3af56095ca,BE9558,2026-05-16T17:37:27,K558LLAU.AF0W,Long,0.2899,0.2930,0.989,0.2,0
|
||||
00557a73-8dc3-4cd2-b880-c7820dc8b171,BE9558,2026-05-16T17:43:17,K558LLAU.K50W,Long,0.2881,0.2930,0.983,0.2,0
|
||||
8e5518d9-ff0a-4c09-9cf9-a681c84c0b6e,BE9558,2026-05-16T17:53:53,K558LLAV.1T0W,Long,0.2898,0.2930,0.989,0.2,0
|
||||
91dbd7e9-7344-400b-82b1-379f2ac4b49a,BE9558,2026-05-16T17:59:11,K558LLAV.AN0W,Long,0.2925,0.2930,0.998,0.2,0
|
||||
fa256408-d480-4376-95b5-d1a549c483ea,BE9558,2026-05-16T18:04:29,K558LLAV.JH0W,Long,0.2977,0.3027,0.983,0.2,0
|
||||
4ab6e66a-8364-49b6-82f1-86e86199e676,BE9558,2026-05-16T18:09:46,K558LLAV.SA0W,Long,0.2944,0.2979,0.988,0.2,0
|
||||
0a65fb7c-96e1-4ba0-85de-4620d88658c1,BE9558,2026-05-16T18:15:03,K558LLAW.130W,Long,0.2965,0.2979,0.995,0.2,0
|
||||
92b1ef3e-1696-4123-8662-163947737c83,BE9558,2026-05-16T18:20:20,K558LLAW.9W0W,Long,0.2976,0.3027,0.983,0.2,0
|
||||
9e3cb24c-4426-4220-9a73-389d0a96c94f,BE9558,2026-05-16T18:25:37,K558LLAW.IP0W,Long,0.2983,0.3027,0.985,0.2,0
|
||||
a3473215-4c46-45ab-9aa7-1720486ec4a8,BE9558,2026-05-16T18:30:54,K558LLAW.RI0W,Long,0.2956,0.2979,0.993,0.2,0
|
||||
449665b1-47c8-4bd2-984c-8f45b627e6d8,BE9558,2026-05-16T18:36:11,K558LLAX.0B0W,Long,0.2989,0.3027,0.987,0.2,0
|
||||
600cfabc-cffd-42e1-800c-70e75f312316,BE9558,2026-05-16T20:00:12,K558LLB0.WC0W,Long,0.3077,0.3125,0.985,0.2,0
|
||||
12bf5944-0194-4f5b-b486-a7acd7141c7f,BE9558,2026-05-16T20:04:28,K558LLB1.3G0W,Long,0.2888,0.2930,0.986,0.2,0
|
||||
f1fc913a-91bc-4240-a595-7dfe3091f9a2,BE9558,2026-05-16T20:07:29,K558LLB1.8H0W,Long,0.2977,0.3027,0.983,0.2,0
|
||||
e74f7ec3-20bb-4177-beb2-e802e5f801fd,BE9558,2026-05-16T20:10:26,K558LLB1.DE0W,Long,0.2978,0.3027,0.984,0.2,0
|
||||
27491c3a-b631-4643-818a-714523911178,BE9558,2026-05-16T20:16:21,K558LLB1.N90W,Long,0.2921,0.2930,0.997,0.2,0
|
||||
9d9196ce-11e2-4f28-b01c-3dcc60e60d42,BE9558,2026-05-16T20:22:28,K558LLB1.XG0W,Long,0.2881,0.2930,0.983,0.2,0
|
||||
a592d7c8-b643-4b25-9186-3d611ae22709,BE9558,2026-05-16T20:25:37,K558LLB2.2P0W,Long,0.2893,0.2930,0.987,0.2,0
|
||||
f709a3d5-27cd-4bb1-b91c-669e8ea11d77,BE9558,2026-05-16T20:28:57,K558LLB2.890W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
cc9cad87-b87f-4b67-854a-ffb21e876a92,BE9558,2026-05-16T20:32:45,K558LLB2.EL0W,Long,0.2873,0.2930,0.980,0.2,0
|
||||
10732d26-6b49-4b14-a474-6c75e259d278,BE9558,2026-05-16T20:49:32,K558LLB3.6K0W,Long,0.2881,0.2930,0.983,0.2,0
|
||||
aa63957a-fdb2-4f17-af52-a63bb015119d,BE9558,2026-05-16T21:21:45,K558LLB4.O90W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
8350440f-019d-45a4-b9f9-23058628e6f0,BE9558,2026-05-16T21:32:43,K558LLB5.6J0W,Long,0.2925,0.2930,0.999,0.2,0
|
||||
edfc10b2-dbe1-4527-a061-b0d670b5e5d2,BE9558,2026-05-16T21:35:37,K558LLB5.BD0W,Long,0.2891,0.2930,0.987,0.2,0
|
||||
f98001a3-88b2-4830-8112-b7c5164e99c3,BE9558,2026-05-16T21:38:40,K558LLB5.GG0W,Long,0.2877,0.2930,0.982,0.2,0
|
||||
f1e53e7b-b124-4fc5-82c2-504fb0c8b80d,BE9558,2026-05-16T21:41:46,K558LLB5.LM0W,Long,0.2881,0.2930,0.983,0.2,0
|
||||
7890637f-142e-4775-b48c-fd4f3b8ada77,BE9558,2026-05-16T21:45:14,K558LLB5.RE0W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
7c97c10f-b413-467c-9b56-c18e423cdcfa,BE9558,2026-05-16T21:48:26,K558LLB5.WQ0W,Long,0.2886,0.2930,0.985,0.2,0
|
||||
8178cf22-8428-4f85-8199-0a43f7334a8f,BE9558,2026-05-16T21:51:47,K558LLB6.2B0W,Long,0.2881,0.2930,0.983,0.2,0
|
||||
eceb2997-deb4-403a-802f-50e93d23d423,BE9558,2026-05-16T21:57:18,K558LLB6.BI0W,Long,0.2881,0.2930,0.984,0.2,0
|
||||
9c26690c-1983-4b21-b8af-7c7967c014c3,BE9558,2026-05-16T22:12:21,K558LLB7.0L0W,Long,0.2876,0.2930,0.982,0.2,0
|
||||
78f67fc3-08b7-4317-96ba-ee5544e0b95b,BE9558,2026-05-16T22:19:34,K558LLB7.CM0W,Long,0.2880,0.2930,0.983,0.2,0
|
||||
7f9dad14-4f1b-492d-aa26-845a908ea894,BE9558,2026-05-16T22:27:40,K558LLB7.Q40W,Long,0.2881,0.2930,0.983,0.2,0
|
||||
f75c52b4-21b9-4065-baeb-5cfbd27d130a,BE9558,2026-05-16T22:33:50,K558LLB8.0E0W,Long,0.2881,0.2930,0.984,0.2,0
|
||||
10f7496d-fa76-40a7-8bef-dc14e8a41869,BE9558,2026-05-16T22:40:48,K558LLB8.C00W,Long,0.2878,0.2930,0.982,0.2,0
|
||||
|
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Backfill events.shape_* from each event's .h5 waveform samples. Idempotent."""
|
||||
from __future__ import annotations
|
||||
import argparse, logging, 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
|
||||
from sfm.shape_metrics import shape_from_h5
|
||||
|
||||
log = logging.getLogger("backfill_event_shape")
|
||||
|
||||
def backfill_shape(db: SeismoDb, store: WaveformStore, *, dry_run: bool = False) -> dict:
|
||||
counts = {"updated": 0, "skipped_no_h5": 0, "skipped_no_samples": 0,
|
||||
"cleared_stale": 0}
|
||||
for row in db.query_events(limit=1_000_000):
|
||||
serial, filename = row.get("serial"), row.get("blastware_filename")
|
||||
if not serial or not filename:
|
||||
counts["skipped_no_h5"] += 1; continue
|
||||
h5_path = store.hdf5_path_for(serial, filename)
|
||||
if not h5_path.exists():
|
||||
counts["skipped_no_h5"] += 1; continue
|
||||
shape = shape_from_h5(h5_path)
|
||||
if shape is None:
|
||||
# The .h5 can no longer yield a shape (fewer than 2 samples, or a
|
||||
# flat trace). Clear any previously stored value rather than
|
||||
# leaving it behind — a stale shape outlives the decode it came
|
||||
# from and silently feeds the false-trigger detector. Seen after
|
||||
# a decoder fix shrinks an event: 493 rows in the prod snapshot
|
||||
# were carrying metrics from a superseded decode (2026-08-25).
|
||||
if row.get("shape_crest_factor") is not None:
|
||||
if not dry_run:
|
||||
with db._connect() as conn:
|
||||
conn.execute(
|
||||
"UPDATE events SET shape_crest_factor=NULL, "
|
||||
"shape_near_peak_count=NULL, shape_sample_count=NULL, "
|
||||
"shape_axis=NULL WHERE id=?", (row["id"],))
|
||||
counts["cleared_stale"] += 1
|
||||
counts["skipped_no_samples"] += 1; continue
|
||||
if not dry_run:
|
||||
with db._connect() as conn:
|
||||
conn.execute(
|
||||
"UPDATE events SET shape_crest_factor=?, shape_near_peak_count=?, "
|
||||
"shape_sample_count=?, shape_axis=? WHERE id=?",
|
||||
(shape["crest_factor"], shape["near_peak_count"],
|
||||
shape["sample_count"], shape["axis"], row["id"]))
|
||||
counts["updated"] += 1
|
||||
log.info("backfill_shape: %s", counts)
|
||||
return counts
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--db-path", required=True)
|
||||
ap.add_argument("--store-root", required=True)
|
||||
ap.add_argument("--dry-run", action="store_true")
|
||||
a = ap.parse_args(argv)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
counts = backfill_shape(SeismoDb(a.db_path), WaveformStore(a.store_root), dry_run=a.dry_run)
|
||||
print(counts)
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/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())
|
||||
+150
-16
@@ -12,8 +12,20 @@ Walks `<store_root>/<serial>/<filename>` and for each BW event file:
|
||||
parsing the BW binary directly (peaks computed from samples).
|
||||
|
||||
Clean waveform (.h5):
|
||||
- Skip when <filename>.h5 already exists (idempotent).
|
||||
- Else write from .a5.pkl (preferred) or BW binary parse (fallback).
|
||||
- Regenerated whenever the sidecar is regenerated (sha mismatch
|
||||
OR sidecar.source.tool_version < current TOOL_VERSION OR --force).
|
||||
The .h5 and the sidecar both come from the same decoder output,
|
||||
so if the sidecar is stale the .h5 is too.
|
||||
- Written when missing.
|
||||
- --skip-hdf5 turns off all .h5 writes.
|
||||
|
||||
Typical use after a decoder upgrade:
|
||||
1. Pull the new seismo-relay code (which bumped TOOL_VERSION).
|
||||
2. Run this script — every sidecar with an older tool_version
|
||||
stamp regenerates, and the associated .h5 cascade-regenerates.
|
||||
3. Operator review state (review.false_trigger, notes, reviewer)
|
||||
and the sidecar's extensions block are preserved across the
|
||||
regen.
|
||||
|
||||
Usage:
|
||||
python scripts/backfill_sidecars.py [--store-root PATH]
|
||||
@@ -42,14 +54,26 @@ log = logging.getLogger("backfill_sidecars")
|
||||
|
||||
|
||||
def _looks_like_event_file(path: Path) -> bool:
|
||||
"""Same heuristic as the importer CLI."""
|
||||
"""Same heuristic as the importer CLI.
|
||||
|
||||
Filters to BW (Series III) event files only — Thor (Series IV)
|
||||
`.IDFW` / `.IDFH` files share the store but have their own ingest
|
||||
path (`WaveformStore.save_imported_idf`) and are NOT decodable by
|
||||
`event_file_io.read_blastware_file`. Their sidecars are populated
|
||||
at ingest from the paired `.IDFW.txt` ASCII report; nothing the
|
||||
backfill regenerates would improve on them, so we exclude them
|
||||
from scope.
|
||||
"""
|
||||
if not path.is_file():
|
||||
return False
|
||||
if path.name.endswith((".a5.pkl", ".sfm.json")):
|
||||
if path.name.endswith((".a5.pkl", ".sfm.json", ".h5")):
|
||||
return False
|
||||
ext = path.suffix.lstrip(".")
|
||||
if not (3 <= len(ext) <= 4):
|
||||
return False
|
||||
# Thor IDF files share the .{W,H}-suffix shape but aren't BW.
|
||||
if ext.upper() in ("IDFW", "IDFH"):
|
||||
return False
|
||||
if not (ext[-1].upper() in {"W", "H"} or ext.endswith("0")):
|
||||
return False
|
||||
try:
|
||||
@@ -79,6 +103,17 @@ def main(argv=None) -> int:
|
||||
"STRT-rectime byte-offset fix in v0.15.x)."
|
||||
),
|
||||
)
|
||||
p.add_argument(
|
||||
"--reparse-txt", action="store_true",
|
||||
help=(
|
||||
"Re-parse the preserved <serial>/<filename>_ASCII.TXT with the "
|
||||
"current bw_ascii_report parser and overwrite the sidecar's "
|
||||
"bw_report block. Use this after upgrading the ASCII parser to "
|
||||
"pull in new fields (e.g. zc_freq_above_range for BW '>100 Hz' "
|
||||
"ZC peaks). No-op for events without a preserved .TXT; safely "
|
||||
"idempotent when the parser hasn't changed."
|
||||
),
|
||||
)
|
||||
p.add_argument("-v", "--verbose", action="store_true")
|
||||
args = p.parse_args(argv)
|
||||
|
||||
@@ -101,6 +136,7 @@ def main(argv=None) -> int:
|
||||
db = SeismoDb(db_path)
|
||||
|
||||
written = skipped = errors = 0
|
||||
stale_h5_removed = 0
|
||||
for serial_dir in sorted(p for p in store_root.iterdir() if p.is_dir()):
|
||||
serial = serial_dir.name
|
||||
for path in sorted(serial_dir.iterdir()):
|
||||
@@ -123,7 +159,13 @@ def main(argv=None) -> int:
|
||||
# the sidecar was written by a build that includes any
|
||||
# decoder fixes shipped since).
|
||||
# Either part failing → regenerate. --force bypasses both.
|
||||
if sidecar_path.exists() and not args.force:
|
||||
#
|
||||
# Tracks whether we're regenerating the sidecar this iteration
|
||||
# so the .h5 logic below knows to refresh that too — staleness
|
||||
# of the sidecar implies staleness of the derived .h5 (both
|
||||
# come out of the same decoder).
|
||||
sidecar_stale = True
|
||||
if sidecar_path.exists() and not args.force and not args.reparse_txt:
|
||||
try:
|
||||
existing = event_file_io.read_sidecar(sidecar_path)
|
||||
sha_ok = existing.get("blastware", {}).get("sha256") == bw_sha
|
||||
@@ -136,6 +178,7 @@ def main(argv=None) -> int:
|
||||
ver_ok = _vt(src_ver) >= _vt(event_file_io.TOOL_VERSION)
|
||||
if sha_ok and ver_ok:
|
||||
skipped += 1
|
||||
sidecar_stale = False
|
||||
continue
|
||||
if sha_ok and not ver_ok:
|
||||
log.info(
|
||||
@@ -256,19 +299,68 @@ def main(argv=None) -> int:
|
||||
or ev.total_samples < derived // 4):
|
||||
ev.total_samples = derived
|
||||
|
||||
# Preserve user-edited review state + extensions from the
|
||||
# existing sidecar (false_trigger flag, notes, etc.) so a
|
||||
# backfill never wipes them out.
|
||||
preserved_review = None
|
||||
preserved_ext = None
|
||||
# Preserve user-edited review state + extensions + the
|
||||
# bw_report block from the existing sidecar so a backfill
|
||||
# never wipes them out. The bw_report block originates
|
||||
# from the paired .TXT ASCII report parsed at ORIGINAL
|
||||
# import time (ach forward / direct upload); the .TXT
|
||||
# file is not in the waveform store, so we can't re-derive
|
||||
# it from disk. event_to_sidecar_dict takes a
|
||||
# BwAsciiReport dataclass (not a dict), so for bw_report
|
||||
# we overlay the existing block after regen instead of
|
||||
# passing it as a kwarg.
|
||||
preserved_review = None
|
||||
preserved_ext = None
|
||||
preserved_bw_report = None
|
||||
preserved_txt_fn = None
|
||||
if sidecar_path.exists():
|
||||
try:
|
||||
_existing = event_file_io.read_sidecar(sidecar_path)
|
||||
preserved_review = _existing.get("review")
|
||||
preserved_ext = _existing.get("extensions")
|
||||
preserved_review = _existing.get("review")
|
||||
preserved_ext = _existing.get("extensions")
|
||||
preserved_bw_report = _existing.get("bw_report")
|
||||
# Preserve txt_filename so backfills don't blank out the
|
||||
# pointer to the saved raw .TXT (events ingested after
|
||||
# 2026-05-27 have this).
|
||||
preserved_txt_fn = (_existing.get("source") or {}).get("txt_filename")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# --reparse-txt: if a .TXT is preserved on disk, run the
|
||||
# current parser against it and overwrite the bw_report
|
||||
# block. Picks up post-ingest parser fixes (e.g. the
|
||||
# 2026-05-28 zc_freq_above_range / ">100 Hz" addition).
|
||||
if args.reparse_txt and preserved_txt_fn:
|
||||
try:
|
||||
from minimateplus import bw_ascii_report
|
||||
txt_path = store.txt_path_for(serial, path.name)
|
||||
if txt_path.exists():
|
||||
refreshed = bw_ascii_report.parse_report_file(txt_path)
|
||||
preserved_bw_report = event_file_io._bw_report_to_dict(refreshed)
|
||||
log.debug("reparsed bw_report from %s", txt_path.name)
|
||||
else:
|
||||
log.debug("--reparse-txt: no .TXT at %s (sidecar says %r)",
|
||||
txt_path, preserved_txt_fn)
|
||||
except Exception as exc:
|
||||
log.warning("--reparse-txt failed for %s: %s", path.name, exc)
|
||||
|
||||
# Overlay BW ASCII report fields onto the rebuilt Event
|
||||
# BEFORE the sidecar + DB write. Mirrors what the ingest
|
||||
# path does — BW's reported peaks (and sample_rate /
|
||||
# record_time) win over codec output where present.
|
||||
#
|
||||
# Without this step, --force backfill silently overwrites
|
||||
# the bw_report-overlaid DB columns with codec-derived
|
||||
# values, which is wrong for events the codec doesn't
|
||||
# fully decode (e.g. waveform walker edge cases on
|
||||
# SP0/SS0/SV0-style events, or histogram sub-formats with
|
||||
# byte[5]!=0 that aren't yet RE'd). Net effect was PVS=0
|
||||
# on three top-10 events on 2026-05-22.
|
||||
if preserved_bw_report:
|
||||
event_file_io.apply_bw_report_dict_to_event(
|
||||
ev, preserved_bw_report,
|
||||
)
|
||||
|
||||
sidecar = event_file_io.event_to_sidecar_dict(
|
||||
ev,
|
||||
serial=serial,
|
||||
@@ -277,16 +369,58 @@ def main(argv=None) -> int:
|
||||
blastware_sha256=bw_sha,
|
||||
source_kind=source_kind,
|
||||
a5_pickle_filename=a5_filename,
|
||||
txt_filename=preserved_txt_fn,
|
||||
review=preserved_review,
|
||||
extensions=preserved_ext,
|
||||
)
|
||||
if preserved_bw_report is not None:
|
||||
sidecar["bw_report"] = preserved_bw_report
|
||||
|
||||
# Also emit the .h5 clean-waveform file when missing OR when
|
||||
# --force was passed (so a re-backfill picks up decoder fixes).
|
||||
# Also emit the .h5 clean-waveform file when:
|
||||
# - it's missing, OR
|
||||
# - --force was passed, OR
|
||||
# - the sidecar is being regenerated this iteration
|
||||
# (sha mismatch / tool_version too old). The .h5 and
|
||||
# the sidecar are both derived from the same decoder
|
||||
# output, so if the sidecar is stale, so is the .h5.
|
||||
#
|
||||
# Both waveform and histogram bodies now decode to real
|
||||
# samples via event_file_io.read_blastware_file → either
|
||||
# waveform_codec.decode_waveform_v2 or histogram_codec.
|
||||
# decode_histogram_body. If samples are still empty after
|
||||
# both codecs run, it's a genuine "we can't decode this
|
||||
# file" case (truncated, malformed, or unknown mode).
|
||||
#
|
||||
# In that case we REMOVE any existing .h5 rather than leave
|
||||
# it. Leaving it was the old behaviour and it silently
|
||||
# preserved output from a superseded decoder: after the
|
||||
# 2026-08-25 record-chain fix, 415 histogram files stopped
|
||||
# decoding (an unmapped block variant on BE18193/BE9440) but
|
||||
# kept .h5 files whose peaks were up to 400x the device's own
|
||||
# reported PPV — garbage that fed the charts and the
|
||||
# false-trigger detector with nothing marking it.
|
||||
has_samples = bool(
|
||||
ev.raw_samples and any(
|
||||
ev.raw_samples.get(ch) for ch in ("Tran", "Vert", "Long", "MicL")
|
||||
)
|
||||
)
|
||||
hdf5_path = store.hdf5_path_for(serial, path.name)
|
||||
hdf5_filename = hdf5_path.name if hdf5_path.exists() else None
|
||||
if not has_samples and hdf5_path.exists():
|
||||
log.warning("%s: no samples decode — removing stale %s",
|
||||
path.name, hdf5_path.name)
|
||||
if not args.dry_run:
|
||||
hdf5_path.unlink()
|
||||
hdf5_filename = None
|
||||
stale_h5_removed += 1
|
||||
hdf5_action = "kept"
|
||||
need_h5 = not args.skip_hdf5 and (args.force or not hdf5_path.exists())
|
||||
need_h5 = (
|
||||
not args.skip_hdf5
|
||||
and (args.force or not hdf5_path.exists() or sidecar_stale)
|
||||
and has_samples
|
||||
)
|
||||
if not has_samples and not args.skip_hdf5:
|
||||
hdf5_action = "skipped-undecodable"
|
||||
if need_h5:
|
||||
if args.dry_run:
|
||||
hdf5_action = "would (re)write"
|
||||
@@ -339,7 +473,7 @@ def main(argv=None) -> int:
|
||||
log.error("backfill failed for %s: %s", path, exc, exc_info=args.verbose)
|
||||
errors += 1
|
||||
|
||||
print(f"\nDone. written={written} skipped(uptodate)={skipped} errors={errors}")
|
||||
print(f"\nDone. written={written} skipped(uptodate)={skipped} errors={errors} stale_h5_removed={stale_h5_removed}")
|
||||
return 0 if errors == 0 else 1
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
"""
|
||||
scripts/backfill_thor_events.py — re-process existing Thor (Series IV)
|
||||
events so their sidecars carry the bw_report block produced by
|
||||
``micromate.idf_to_bw_report.build_bw_report_from_idf`` + their .h5
|
||||
clean-waveform files for IDFW events.
|
||||
|
||||
Why this exists
|
||||
───────────────
|
||||
|
||||
Thor events ingested before v0.21.0 (or during the v0.21.0 ingest bug
|
||||
window fixed in commit bee1185) have sidecars with only
|
||||
``extensions.idf_report`` — no ``bw_report`` block. Without
|
||||
``bw_report``, the SFM PDF renderer falls back to DB-only fields
|
||||
(misses sensor-self-check, full per-channel breakdown, mic dB(L)),
|
||||
and the modal chart 404s on ``/waveform.json`` for IDFW events
|
||||
because no .h5 was written when the codec failed at ingest.
|
||||
|
||||
Re-forwarding from thor-watcher would also fix this, but that requires
|
||||
operator coordination on every watcher machine and uses bandwidth this
|
||||
script doesn't.
|
||||
|
||||
What this does
|
||||
──────────────
|
||||
|
||||
Walks ``<store>/<serial>/<filename>`` for ``.IDFW`` / ``.IDFH`` files
|
||||
and, for each one:
|
||||
|
||||
1. Reads the existing sidecar (preserving review state + captured_at).
|
||||
2. Re-runs ``micromate.idf_file.read_idf_file()`` on the binary
|
||||
bytes — passing ``data=`` so the codec doesn't try to read from
|
||||
a path it doesn't know.
|
||||
3. Pulls ``extensions.idf_report`` (the raw parsed Thor dict the
|
||||
v0.18.0+ ingest path already stashed) and runs the v0.21.0
|
||||
``build_bw_report_from_idf`` adapter against it.
|
||||
4. Writes the refreshed sidecar with the new ``bw_report``,
|
||||
bumped ``source.tool_version``, but preserved ``review`` block
|
||||
+ the original ``captured_at`` timestamp.
|
||||
5. Regenerates the .h5 waveform file via the existing
|
||||
``event_hdf5`` writer. For IDFW that's the decoded per-sample
|
||||
stream; for IDFH it's a 1-sample-per-interval synthesised array
|
||||
(peak ADC count per channel) so the renderer's bar-chart code
|
||||
has data to group on. Mic peak psi from the binary is merged
|
||||
onto the IdfEvent before the bridge so the h5 writer's per-count
|
||||
mic scale factor lands on a sensible value (without this the
|
||||
mic chart on Thor events plots dB(L)-as-pseudo-psi and shows
|
||||
bomb-level numbers).
|
||||
|
||||
Idempotent. Re-running it after a parser/adapter change just
|
||||
re-writes sidecars — no DB writes, no thor-watcher coordination.
|
||||
|
||||
Usage
|
||||
─────
|
||||
|
||||
python scripts/backfill_thor_events.py [--store-root PATH]
|
||||
[--dry-run]
|
||||
[--skip-hdf5]
|
||||
[--force]
|
||||
[-v]
|
||||
|
||||
By default, refreshes any Thor event whose sidecar is missing
|
||||
``bw_report`` OR whose ``source.tool_version`` is older than the
|
||||
current ``TOOL_VERSION``. ``--force`` refreshes every Thor event
|
||||
regardless.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Allow running from the repo root without installation.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from minimateplus import event_file_io
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
log = logging.getLogger("backfill_thor_events")
|
||||
|
||||
|
||||
def _is_thor_event(path: Path) -> bool:
|
||||
if not path.is_file():
|
||||
return False
|
||||
if path.name.endswith((".sfm.json", ".h5", "_ASCII.TXT")):
|
||||
return False
|
||||
return path.suffix.upper() in (".IDFW", ".IDFH")
|
||||
|
||||
|
||||
def _vtuple(s: str) -> tuple:
|
||||
try:
|
||||
return tuple(int(p) for p in str(s).split(".")[:3])
|
||||
except Exception:
|
||||
return (0, 0, 0)
|
||||
|
||||
|
||||
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"),
|
||||
help="Used only to derive the default --store-root.",
|
||||
)
|
||||
p.add_argument("--store-root", default=None)
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
p.add_argument("--skip-hdf5", action="store_true",
|
||||
help="Don't regenerate .h5 files for IDFW events.")
|
||||
p.add_argument("--force", action="store_true",
|
||||
help="Refresh every Thor event, not just ones with stale or missing bw_report.")
|
||||
p.add_argument("-v", "--verbose", action="store_true")
|
||||
args = p.parse_args(argv)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG if args.verbose else logging.INFO,
|
||||
format="%(asctime)s %(levelname)-7s %(name)s %(message)s",
|
||||
datefmt="%H:%M:%S",
|
||||
)
|
||||
|
||||
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"
|
||||
)
|
||||
if not store_root.exists():
|
||||
log.error("store root not found: %s", store_root)
|
||||
return 1
|
||||
store = WaveformStore(store_root)
|
||||
log.info("store root: %s", store_root)
|
||||
log.info("current TOOL_VERSION: %s", event_file_io.TOOL_VERSION)
|
||||
|
||||
refreshed = skipped = errors = h5_written = 0
|
||||
|
||||
# Lazy imports so any one of these failing produces a useful error
|
||||
# message rather than crashing module-load.
|
||||
from micromate.idf_file import read_idf_file
|
||||
from micromate.idf_to_bw_report import build_bw_report_from_idf
|
||||
|
||||
for serial_dir in sorted(p for p in store_root.iterdir() if p.is_dir()):
|
||||
serial = serial_dir.name
|
||||
for path in sorted(serial_dir.iterdir()):
|
||||
if not _is_thor_event(path):
|
||||
continue
|
||||
|
||||
sidecar_path = store.sidecar_path_for(serial, path.name)
|
||||
if not sidecar_path.exists():
|
||||
log.debug("%s: no sidecar — skipping (this is a binary without ingest history)",
|
||||
path.name)
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
existing = event_file_io.read_sidecar(sidecar_path)
|
||||
except Exception as exc:
|
||||
log.warning("%s: failed to read sidecar — %s", path.name, exc)
|
||||
errors += 1
|
||||
continue
|
||||
|
||||
has_bw_report = bool(existing.get("bw_report"))
|
||||
existing_version = (existing.get("source") or {}).get("tool_version", "")
|
||||
up_to_date = (
|
||||
has_bw_report
|
||||
and _vtuple(existing_version) >= _vtuple(event_file_io.TOOL_VERSION)
|
||||
)
|
||||
if up_to_date and not args.force:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Re-decode the binary. Catch + log; continue with .txt-only
|
||||
# data if it fails (matches the live ingest path's behavior).
|
||||
idf_samples = None
|
||||
idf_intervals = None
|
||||
binary_md = None
|
||||
is_histogram = path.suffix.upper() == ".IDFH"
|
||||
try:
|
||||
binary_bytes = path.read_bytes()
|
||||
res = read_idf_file(path, data=binary_bytes)
|
||||
idf_samples = res.samples or None
|
||||
idf_intervals = res.intervals
|
||||
binary_md = res.binary_metadata
|
||||
is_histogram = res.intervals is not None
|
||||
except NotImplementedError:
|
||||
# sig-B / Blastware-stray binary; no samples but adapter
|
||||
# can still produce a bw_report from extensions.idf_report.
|
||||
log.debug("%s: binary codec NotImplementedError (sig-B / BW-stray); proceeding from sidecar's idf_report only", path.name)
|
||||
except Exception as exc:
|
||||
log.warning("%s: binary decode failed — %s; proceeding from sidecar's idf_report only", path.name, exc)
|
||||
|
||||
# Run the adapter. Pull report_dict from
|
||||
# extensions.idf_report (the v0.18.0+ ingest preserved it).
|
||||
report_dict = (existing.get("extensions") or {}).get("idf_report") or {}
|
||||
if not report_dict and binary_md is None:
|
||||
log.debug("%s: no idf_report in sidecar AND no binary metadata — nothing to project", path.name)
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
bw_report = build_bw_report_from_idf(
|
||||
report_dict, binary_md=binary_md,
|
||||
intervals=idf_intervals, is_histogram=is_histogram,
|
||||
)
|
||||
except Exception as exc:
|
||||
log.warning("%s: adapter failed — %s", path.name, exc)
|
||||
errors += 1
|
||||
continue
|
||||
|
||||
# Build the new sidecar by overlaying refreshed fields onto
|
||||
# the existing one — preserves review, captured_at, blastware
|
||||
# block, source.kind, etc.
|
||||
new_sidecar = dict(existing) # shallow copy
|
||||
new_sidecar["bw_report"] = bw_report
|
||||
src = dict(new_sidecar.get("source") or {})
|
||||
src["tool_version"] = event_file_io.TOOL_VERSION
|
||||
new_sidecar["source"] = src
|
||||
|
||||
# Preserve histogram intervals if the binary decoded them
|
||||
# (improves over the original ingest if that one ran before
|
||||
# the bee1185 codec fix).
|
||||
if idf_intervals is not None:
|
||||
ext = dict(new_sidecar.get("extensions") or {})
|
||||
ext["idf_intervals"] = [
|
||||
{
|
||||
"offset": iv.offset,
|
||||
"tran_peak": iv.peak_count("Tran"),
|
||||
"tran_halfp": iv.tran_halfp,
|
||||
"tran_freq": iv.freq_hz("Tran"),
|
||||
"vert_peak": iv.peak_count("Vert"),
|
||||
"vert_halfp": iv.vert_halfp,
|
||||
"vert_freq": iv.freq_hz("Vert"),
|
||||
"long_peak": iv.peak_count("Long"),
|
||||
"long_halfp": iv.long_halfp,
|
||||
"long_freq": iv.freq_hz("Long"),
|
||||
"mic_peak": iv.peak_count("MicL"),
|
||||
"mic_halfp": iv.micl_halfp,
|
||||
"mic_freq": iv.freq_hz("MicL"),
|
||||
}
|
||||
for iv in idf_intervals
|
||||
]
|
||||
new_sidecar["extensions"] = ext
|
||||
|
||||
if args.dry_run:
|
||||
will_write_h5 = (idf_samples or idf_intervals) and not args.skip_hdf5
|
||||
log.info("[DRY] %s/%s — would refresh sidecar (bw_report=%s, h5=%s)",
|
||||
serial, path.name,
|
||||
"wrote" if not has_bw_report else "refreshed",
|
||||
"would write" if will_write_h5 else "skipped")
|
||||
else:
|
||||
event_file_io.write_sidecar(sidecar_path, new_sidecar)
|
||||
log.info("%s/%s — sidecar refreshed (bw_report=%s, intervals=%d)",
|
||||
serial, path.name,
|
||||
"added" if not has_bw_report else "refreshed",
|
||||
len(idf_intervals) if idf_intervals else 0)
|
||||
refreshed += 1
|
||||
|
||||
# Regenerate .h5 by replaying the same IdfEvent → Event bridge
|
||||
# save_imported_idf uses. For IDFW we write the decoded per-
|
||||
# sample arrays. For IDFH we synthesise a 1-sample-per-interval
|
||||
# array (peak ADC count per channel per interval) so the
|
||||
# renderer's bar-chart code has something to group on.
|
||||
# Pre-condition: either real samples (IDFW) or decoded intervals
|
||||
# (IDFH). Skip otherwise.
|
||||
have_data = bool(idf_samples) or bool(idf_intervals)
|
||||
if have_data and not args.skip_hdf5:
|
||||
from sfm import event_hdf5
|
||||
hdf5_path = store.hdf5_path_for(serial, path.name)
|
||||
if args.dry_run:
|
||||
log.debug("[DRY] would write %s", hdf5_path.name)
|
||||
else:
|
||||
try:
|
||||
from micromate import IdfEvent
|
||||
from minimateplus.event_file_io import file_sha256
|
||||
idf_event = IdfEvent.from_report(report_dict, path.name)
|
||||
|
||||
# Merge the binary-derived mic peak psi (only the
|
||||
# binary path knows the proper psi value; the .txt
|
||||
# carries dB(L)). Without this, the h5 writer's
|
||||
# per-count mic factor is computed against the
|
||||
# dB(L) value-as-pseudo-psi and the mic chart
|
||||
# scales wildly.
|
||||
if (binary_md is not None and res is not None
|
||||
and res.event.peaks.mic_pspl_psi is not None):
|
||||
idf_event.peaks.mic_pspl_psi = res.event.peaks.mic_pspl_psi
|
||||
|
||||
sha256 = file_sha256(path)
|
||||
waveform_key = bytes.fromhex(sha256)[:16]
|
||||
ev = idf_event.to_minimateplus_event(waveform_key)
|
||||
|
||||
if is_histogram and idf_intervals:
|
||||
# 1 sample per interval per channel — same
|
||||
# synthesis save_imported_idf uses. The h5
|
||||
# writer's count×geo_fs/32768 conversion turns
|
||||
# each peak-ADC-count into the bar's physical
|
||||
# value.
|
||||
ev.raw_samples = {
|
||||
"Tran": [iv.peak_count("Tran") for iv in idf_intervals],
|
||||
"Vert": [iv.peak_count("Vert") for iv in idf_intervals],
|
||||
"Long": [iv.peak_count("Long") for iv in idf_intervals],
|
||||
"MicL": [iv.peak_count("MicL") for iv in idf_intervals],
|
||||
}
|
||||
ev.total_samples = ev.total_samples or len(idf_intervals)
|
||||
elif idf_samples:
|
||||
ev.raw_samples = idf_samples
|
||||
n_samp = max(
|
||||
(len(idf_samples.get(ch, []))
|
||||
for ch in ("Tran", "Vert", "Long", "MicL")),
|
||||
default=0,
|
||||
)
|
||||
ev.total_samples = ev.total_samples or n_samp
|
||||
|
||||
event_hdf5.write_event_hdf5(
|
||||
hdf5_path, ev,
|
||||
serial=serial,
|
||||
geo_range="normal",
|
||||
source_kind="idf-import",
|
||||
tool_version=event_file_io.TOOL_VERSION,
|
||||
)
|
||||
h5_written += 1
|
||||
log.debug("%s/%s — .h5 written (%s)",
|
||||
serial, path.name,
|
||||
f"{len(idf_intervals)} intervals" if is_histogram
|
||||
else f"{sum(len(v) for v in (idf_samples or {}).values())} samples")
|
||||
except Exception as exc:
|
||||
log.warning("%s/%s — .h5 write failed: %s",
|
||||
serial, path.name, exc)
|
||||
|
||||
log.info("Done. refreshed=%d skipped=%d errors=%d h5_written=%d",
|
||||
refreshed, skipped, errors, h5_written)
|
||||
return 0 if errors == 0 else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,185 @@
|
||||
"""
|
||||
scripts/check_bw_report_preservation.py — verify that running backfill_sidecars
|
||||
doesn't wipe the `bw_report` block from sidecars that already had one.
|
||||
|
||||
Two-step workflow:
|
||||
|
||||
# Before running backfill — capture a baseline snapshot:
|
||||
python scripts/check_bw_report_preservation.py snapshot \
|
||||
--store-root /path/to/waveforms \
|
||||
--out before.json
|
||||
|
||||
# Run backfill:
|
||||
python scripts/backfill_sidecars.py --store-root /path/to/waveforms --force
|
||||
|
||||
# After backfill — diff against the baseline:
|
||||
python scripts/check_bw_report_preservation.py diff \
|
||||
--store-root /path/to/waveforms \
|
||||
--baseline before.json
|
||||
|
||||
The diff classifies every sidecar into one of:
|
||||
|
||||
PRESERVED had bw_report before, has same hash now ← GOOD
|
||||
CHANGED had bw_report before, has different hash now ← suspicious
|
||||
(backfill should only ever copy the block verbatim)
|
||||
WIPED had bw_report before, doesn't now ← BUG — data loss
|
||||
STILL_MISSING didn't have bw_report before, still doesn't ← expected
|
||||
NEW didn't have bw_report before, has one now
|
||||
(only possible if a re-ingest happened between snapshots;
|
||||
shouldn't happen during backfill)
|
||||
REMOVED sidecar existed in baseline, file is gone now
|
||||
ADDED sidecar didn't exist in baseline, exists now
|
||||
|
||||
Exit code is 0 if no WIPED or CHANGED entries are found, 1 otherwise.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# Allow running from the repo root without installation.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from minimateplus import event_file_io
|
||||
|
||||
|
||||
def _bw_report_hash(sidecar_data: dict) -> Optional[str]:
|
||||
"""Canonical-JSON hash of the bw_report block, or None if absent."""
|
||||
br = sidecar_data.get("bw_report")
|
||||
if not br:
|
||||
return None
|
||||
# sort_keys for stable hashing across dict-ordering differences
|
||||
blob = json.dumps(br, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(blob.encode()).hexdigest()
|
||||
|
||||
|
||||
def _scan_store(store_root: Path) -> dict:
|
||||
"""Walk every <serial>/<file>.sfm.json and return {relpath: hash_or_None}.
|
||||
|
||||
Relpath is `<serial>/<filename>` — stable across machines/snapshots.
|
||||
"""
|
||||
out: dict[str, Optional[str]] = {}
|
||||
for serial_dir in sorted(p for p in store_root.iterdir() if p.is_dir()):
|
||||
for sidecar in sorted(serial_dir.glob("*.sfm.json")):
|
||||
relpath = f"{serial_dir.name}/{sidecar.name}"
|
||||
try:
|
||||
data = event_file_io.read_sidecar(sidecar)
|
||||
except Exception as exc:
|
||||
print(f" WARN: failed to read {relpath}: {exc}", file=sys.stderr)
|
||||
continue
|
||||
out[relpath] = _bw_report_hash(data)
|
||||
return out
|
||||
|
||||
|
||||
def cmd_snapshot(args) -> int:
|
||||
store_root = Path(args.store_root).expanduser().resolve()
|
||||
if not store_root.exists():
|
||||
print(f"error: store root does not exist: {store_root}", file=sys.stderr)
|
||||
return 2
|
||||
out_path = Path(args.out).expanduser().resolve()
|
||||
|
||||
print(f"Scanning {store_root} …")
|
||||
snapshot = _scan_store(store_root)
|
||||
|
||||
with_bw = sum(1 for v in snapshot.values() if v is not None)
|
||||
without_bw = sum(1 for v in snapshot.values() if v is None)
|
||||
print(f" total sidecars: {len(snapshot)}")
|
||||
print(f" with bw_report: {with_bw}")
|
||||
print(f" without bw_report: {without_bw}")
|
||||
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(out_path, "w") as f:
|
||||
json.dump({
|
||||
"store_root": str(store_root),
|
||||
"total": len(snapshot),
|
||||
"with_bw": with_bw,
|
||||
"sidecars": snapshot,
|
||||
}, f, indent=2, sort_keys=True)
|
||||
print(f"Wrote baseline → {out_path}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_diff(args) -> int:
|
||||
store_root = Path(args.store_root).expanduser().resolve()
|
||||
if not store_root.exists():
|
||||
print(f"error: store root does not exist: {store_root}", file=sys.stderr)
|
||||
return 2
|
||||
baseline_path = Path(args.baseline).expanduser().resolve()
|
||||
if not baseline_path.exists():
|
||||
print(f"error: baseline file not found: {baseline_path}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
with open(baseline_path) as f:
|
||||
baseline = json.load(f)
|
||||
before = baseline["sidecars"]
|
||||
print(f"Scanning {store_root} for comparison against {baseline_path.name} …")
|
||||
after = _scan_store(store_root)
|
||||
|
||||
classes = {k: [] for k in (
|
||||
"PRESERVED", "CHANGED", "WIPED", "STILL_MISSING", "NEW", "REMOVED", "ADDED",
|
||||
)}
|
||||
all_keys = set(before) | set(after)
|
||||
for key in sorted(all_keys):
|
||||
b = before.get(key, "__MISSING__")
|
||||
a = after.get(key, "__MISSING__")
|
||||
if b == "__MISSING__":
|
||||
classes["ADDED"].append(key)
|
||||
elif a == "__MISSING__":
|
||||
classes["REMOVED"].append(key)
|
||||
elif b is None and a is None:
|
||||
classes["STILL_MISSING"].append(key)
|
||||
elif b is None and a is not None:
|
||||
classes["NEW"].append(key)
|
||||
elif b is not None and a is None:
|
||||
classes["WIPED"].append(key)
|
||||
elif b == a:
|
||||
classes["PRESERVED"].append(key)
|
||||
else:
|
||||
classes["CHANGED"].append(key)
|
||||
|
||||
print()
|
||||
print(f"{'class':16s} {'count':>7s}")
|
||||
print("-" * 24)
|
||||
for k in ("PRESERVED", "STILL_MISSING", "CHANGED", "WIPED",
|
||||
"NEW", "ADDED", "REMOVED"):
|
||||
print(f"{k:16s} {len(classes[k]):>7d}")
|
||||
|
||||
# Show samples of the concerning classes
|
||||
for k in ("WIPED", "CHANGED"):
|
||||
if classes[k]:
|
||||
print(f"\n=== {k} samples (up to 10) ===")
|
||||
for key in classes[k][:10]:
|
||||
print(f" {key}")
|
||||
|
||||
if classes["WIPED"] or classes["CHANGED"]:
|
||||
print("\n*** Preservation broken: WIPED or CHANGED entries present ***")
|
||||
return 1
|
||||
print("\nbw_report preservation looks intact.")
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
p_snap = sub.add_parser("snapshot", help="capture baseline bw_report hashes")
|
||||
p_snap.add_argument("--store-root", required=True)
|
||||
p_snap.add_argument("--out", required=True, help="output JSON path")
|
||||
p_snap.set_defaults(func=cmd_snapshot)
|
||||
|
||||
p_diff = sub.add_parser("diff", help="diff current store against a baseline")
|
||||
p_diff.add_argument("--store-root", required=True)
|
||||
p_diff.add_argument("--baseline", required=True, help="JSON from `snapshot`")
|
||||
p_diff.set_defaults(func=cmd_diff)
|
||||
|
||||
args = p.parse_args(argv)
|
||||
return args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,91 @@
|
||||
"""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()
|
||||
+173
-20
@@ -81,11 +81,24 @@ CREATE TABLE IF NOT EXISTS events (
|
||||
sample_rate INTEGER,
|
||||
record_type TEXT, -- "single_shot" | "continuous"
|
||||
false_trigger INTEGER NOT NULL DEFAULT 0, -- 0=no, 1=yes (manual flag)
|
||||
reviewed_real INTEGER NOT NULL DEFAULT 0, -- 0=no, 1=operator-confirmed real (mutually exclusive with false_trigger)
|
||||
blastware_filename TEXT, -- event file within waveform store; extension is per-event (AB0T encodes timestamp)
|
||||
blastware_filesize INTEGER, -- bytes; NULL if no event file saved
|
||||
a5_pickle_filename TEXT, -- "<filename>.a5.pkl" sidecar
|
||||
sidecar_filename TEXT, -- "<filename>.sfm.json" review/metadata sidecar
|
||||
device_family TEXT, -- "series3" (MiniMate Plus / BW) | "series4" (Micromate / Thor) — drives per-family UI rendering (units, labels)
|
||||
tran_zc_freq REAL, -- Transverse ZC frequency (Hz)
|
||||
vert_zc_freq REAL, -- Vertical ZC frequency (Hz)
|
||||
long_zc_freq REAL, -- Longitudinal ZC frequency (Hz)
|
||||
mic_zc_freq REAL, -- Microphone ZC frequency (Hz)
|
||||
tran_zc_above_range INTEGER, -- 1 = value is device ceiling, render ">N Hz"
|
||||
vert_zc_above_range INTEGER,
|
||||
long_zc_above_range INTEGER,
|
||||
mic_zc_above_range INTEGER,
|
||||
shape_crest_factor REAL, -- peak / rms of the triggering channel
|
||||
shape_near_peak_count INTEGER, -- samples >= 0.5 * peak (FT: few; real: many)
|
||||
shape_sample_count INTEGER, -- total samples (to normalize near_peak_count)
|
||||
shape_axis TEXT, -- geophone channel measured ("Tran"/"Vert"/"Long")
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
UNIQUE(serial, timestamp)
|
||||
);
|
||||
@@ -200,6 +213,19 @@ class SeismoDb:
|
||||
("a5_pickle_filename", "TEXT"),
|
||||
("sidecar_filename", "TEXT"),
|
||||
("device_family", "TEXT"),
|
||||
("tran_zc_freq", "REAL"),
|
||||
("vert_zc_freq", "REAL"),
|
||||
("long_zc_freq", "REAL"),
|
||||
("mic_zc_freq", "REAL"),
|
||||
("tran_zc_above_range", "INTEGER"),
|
||||
("vert_zc_above_range", "INTEGER"),
|
||||
("long_zc_above_range", "INTEGER"),
|
||||
("mic_zc_above_range", "INTEGER"),
|
||||
("shape_crest_factor", "REAL"),
|
||||
("shape_near_peak_count", "INTEGER"),
|
||||
("shape_sample_count", "INTEGER"),
|
||||
("shape_axis", "TEXT"),
|
||||
("reviewed_real", "INTEGER NOT NULL DEFAULT 0"),
|
||||
):
|
||||
if col not in existing_cols:
|
||||
log.info("_migrate: events ADD COLUMN %s %s", col, ddl)
|
||||
@@ -399,8 +425,14 @@ class SeismoDb:
|
||||
sample_rate, record_type,
|
||||
blastware_filename, blastware_filesize,
|
||||
a5_pickle_filename, sidecar_filename,
|
||||
device_family)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
device_family,
|
||||
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,
|
||||
shape_crest_factor, shape_near_peak_count,
|
||||
shape_sample_count, shape_axis)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
self._new_id(), serial, key, session_id, ts,
|
||||
@@ -420,6 +452,18 @@ class SeismoDb:
|
||||
rec.get("a5_pickle_filename"),
|
||||
rec.get("sidecar_filename"),
|
||||
device_family,
|
||||
pv.tran_zc_freq if pv else None,
|
||||
pv.vert_zc_freq if pv else None,
|
||||
pv.long_zc_freq if pv else None,
|
||||
pv.mic_zc_freq if pv else None,
|
||||
(1 if (pv and pv.tran_zc_above_range) else 0),
|
||||
(1 if (pv and pv.vert_zc_above_range) else 0),
|
||||
(1 if (pv and pv.long_zc_above_range) else 0),
|
||||
(1 if (pv and pv.mic_zc_above_range) else 0),
|
||||
rec.get("shape_crest_factor"),
|
||||
rec.get("shape_near_peak_count"),
|
||||
rec.get("shape_sample_count"),
|
||||
rec.get("shape_axis"),
|
||||
),
|
||||
)
|
||||
inserted += 1
|
||||
@@ -461,7 +505,19 @@ class SeismoDb:
|
||||
blastware_filesize = ?,
|
||||
a5_pickle_filename = ?,
|
||||
sidecar_filename = ?,
|
||||
device_family = COALESCE(?, device_family)
|
||||
device_family = COALESCE(?, device_family),
|
||||
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 = ?,
|
||||
shape_crest_factor = COALESCE(?, shape_crest_factor),
|
||||
shape_near_peak_count = COALESCE(?, shape_near_peak_count),
|
||||
shape_sample_count = COALESCE(?, shape_sample_count),
|
||||
shape_axis = COALESCE(?, shape_axis)
|
||||
WHERE serial = ? AND timestamp = ?
|
||||
""",
|
||||
(
|
||||
@@ -481,6 +537,18 @@ class SeismoDb:
|
||||
rec.get("a5_pickle_filename") if rec else None,
|
||||
rec.get("sidecar_filename") if rec else None,
|
||||
device_family,
|
||||
pv.tran_zc_freq if pv else None,
|
||||
pv.vert_zc_freq if pv else None,
|
||||
pv.long_zc_freq if pv else None,
|
||||
pv.mic_zc_freq if pv else None,
|
||||
(1 if (pv and pv.tran_zc_above_range) else 0),
|
||||
(1 if (pv and pv.vert_zc_above_range) else 0),
|
||||
(1 if (pv and pv.long_zc_above_range) else 0),
|
||||
(1 if (pv and pv.mic_zc_above_range) else 0),
|
||||
rec.get("shape_crest_factor") if rec else None,
|
||||
rec.get("shape_near_peak_count") if rec else None,
|
||||
rec.get("shape_sample_count") if rec else None,
|
||||
rec.get("shape_axis") if rec else None,
|
||||
serial,
|
||||
ts,
|
||||
),
|
||||
@@ -535,13 +603,84 @@ class SeismoDb:
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def set_false_trigger(self, event_id: str, value: bool) -> bool:
|
||||
"""Set or clear the false_trigger flag on an event. Returns True if found."""
|
||||
def find_twins(self, event_id: str, *, window_seconds: int = 300) -> list[dict]:
|
||||
"""
|
||||
Find this event's histogram/waveform twin(s): rows sharing the same
|
||||
serial and an identical peak_vector_sum, whose timestamp falls
|
||||
within ``window_seconds`` of this event's timestamp. Excludes the
|
||||
event itself. Returns [] if the event or any required field
|
||||
(serial / peak_vector_sum / timestamp) is missing.
|
||||
|
||||
Caveat: identical-PVS matching is a proxy for "same physical event
|
||||
recorded twice," not a guarantee. In the rare case where the device
|
||||
clamps/saturates PVS (clamped to sqrt(3) * geo_range), two distinct
|
||||
saturated events on the same serial within the window can share the
|
||||
same clamped PVS value and be matched as twins even though they are
|
||||
different events. This is harmless in practice — false_trigger/
|
||||
reviewed_real are derived/index columns re-derivable from the
|
||||
sidecar source of truth — but worth knowing if twin counts look
|
||||
surprising on a saturated/clamped run.
|
||||
"""
|
||||
row = self.get_event(event_id)
|
||||
if not row:
|
||||
return []
|
||||
serial = row.get("serial"); pvs = row.get("peak_vector_sum"); ts = row.get("timestamp")
|
||||
if serial is None or pvs is None or not ts:
|
||||
return []
|
||||
try:
|
||||
t = datetime.datetime.fromisoformat(ts.replace(" ", "T"))
|
||||
except ValueError:
|
||||
return []
|
||||
lo = (t - datetime.timedelta(seconds=window_seconds)).isoformat()
|
||||
hi = (t + datetime.timedelta(seconds=window_seconds)).isoformat()
|
||||
with self._connect() as conn:
|
||||
cur = conn.execute(
|
||||
"UPDATE events SET false_trigger=? WHERE id=?",
|
||||
(1 if value else 0, event_id),
|
||||
)
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM events WHERE serial=? AND id!=? AND peak_vector_sum=? "
|
||||
"AND timestamp BETWEEN ? AND ?",
|
||||
(serial, event_id, pvs, lo, hi),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def propagate_review_to_twins(self, event_id: str, *, window_seconds: int = 300) -> list[str]:
|
||||
"""
|
||||
Copy this event's `false_trigger`/`reviewed_real` columns onto each
|
||||
of its histogram/waveform twins (see `find_twins`), so flagging one
|
||||
twin flags both. Returns the list of twin ids updated.
|
||||
"""
|
||||
row = self.get_event(event_id)
|
||||
if not row:
|
||||
return []
|
||||
ft = 1 if row.get("false_trigger") else 0
|
||||
real = 1 if row.get("reviewed_real") else 0
|
||||
twins = self.find_twins(event_id, window_seconds=window_seconds)
|
||||
moved = []
|
||||
with self._connect() as conn:
|
||||
for tw in twins:
|
||||
conn.execute("UPDATE events SET false_trigger=?, reviewed_real=? WHERE id=?",
|
||||
(ft, real, tw["id"]))
|
||||
moved.append(tw["id"])
|
||||
return moved
|
||||
|
||||
def set_false_trigger(self, event_id: str, value: bool) -> bool:
|
||||
"""
|
||||
Set or clear the false_trigger flag on an event. Returns True if found.
|
||||
|
||||
Mirrors the 3-state exclusivity enforced by `update_event_review`:
|
||||
setting false_trigger true also clears `reviewed_real` (a false
|
||||
trigger can't also be a confirmed-real event). Clearing false_trigger
|
||||
leaves `reviewed_real` untouched.
|
||||
"""
|
||||
with self._connect() as conn:
|
||||
if value:
|
||||
cur = conn.execute(
|
||||
"UPDATE events SET false_trigger=1, reviewed_real=0 WHERE id=?",
|
||||
(event_id,),
|
||||
)
|
||||
else:
|
||||
cur = conn.execute(
|
||||
"UPDATE events SET false_trigger=0 WHERE id=?",
|
||||
(event_id,),
|
||||
)
|
||||
return cur.rowcount > 0
|
||||
|
||||
def delete_event(self, event_id: str) -> Optional[dict]:
|
||||
@@ -617,17 +756,23 @@ class SeismoDb:
|
||||
"""
|
||||
Sync derived index columns from a sidecar's `review` block.
|
||||
|
||||
Currently the only derived index is `events.false_trigger` — kept
|
||||
in sync so `/db/events?false_trigger=true` queries don't have to
|
||||
scan every sidecar JSON on disk. The sidecar JSON itself remains
|
||||
the source of truth for the full review state.
|
||||
The derived indexes are `events.false_trigger` and
|
||||
`events.reviewed_real` — kept in sync so `/db/events` queries don't
|
||||
have to scan every sidecar JSON on disk. The sidecar JSON itself
|
||||
remains the source of truth for the full review state.
|
||||
|
||||
The two columns are mutually exclusive: setting either one true
|
||||
forces the other's column to 0.
|
||||
|
||||
Returns True when the row exists, False otherwise. No-op fields
|
||||
(review without `false_trigger`) leave the column untouched.
|
||||
(review without `false_trigger` or `reviewed_real`) leave both
|
||||
columns untouched.
|
||||
"""
|
||||
if not isinstance(review, dict):
|
||||
return False
|
||||
if "false_trigger" not in review:
|
||||
has_ft = "false_trigger" in review
|
||||
has_real = "reviewed_real" in review
|
||||
if not has_ft and not has_real:
|
||||
# Nothing derived to update; just confirm the row exists.
|
||||
with self._connect() as conn:
|
||||
row = conn.execute(
|
||||
@@ -635,12 +780,20 @@ class SeismoDb:
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
flag = 1 if review.get("false_trigger") else 0
|
||||
sets = {}
|
||||
if has_ft:
|
||||
sets["false_trigger"] = 1 if review.get("false_trigger") else 0
|
||||
if has_real:
|
||||
sets["reviewed_real"] = 1 if review.get("reviewed_real") else 0
|
||||
# mutual exclusivity: a true in one forces the other column to 0
|
||||
if sets.get("false_trigger") == 1:
|
||||
sets["reviewed_real"] = 0
|
||||
if sets.get("reviewed_real") == 1:
|
||||
sets["false_trigger"] = 0
|
||||
assign = ", ".join(f"{k}=?" for k in sets)
|
||||
params = list(sets.values()) + [event_id]
|
||||
with self._connect() as conn:
|
||||
cur = conn.execute(
|
||||
"UPDATE events SET false_trigger=? WHERE id=?",
|
||||
(flag, event_id),
|
||||
)
|
||||
cur = conn.execute(f"UPDATE events SET {assign} WHERE id=?", params)
|
||||
return cur.rowcount > 0
|
||||
|
||||
# ── Monitor log ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
db_snapshot.py — WAL-safe snapshot / restore helpers for seismo_relay.db and
|
||||
the waveform store, backing the /db/snapshot, /db/waveforms/recent.zip and
|
||||
/db/restore endpoints in server.py. Kept out of server.py so the logic is
|
||||
unit-testable without HTTP.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import zipfile
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def snapshot_db(src_path: Path, dest_path: Path) -> Path:
|
||||
"""WAL-safe copy of a live SQLite DB via the SQLite online backup API.
|
||||
Consistent even while the source is being written under WAL, and never
|
||||
blocks the source's writers."""
|
||||
src = sqlite3.connect(str(src_path))
|
||||
dest = sqlite3.connect(str(dest_path))
|
||||
try:
|
||||
with dest:
|
||||
src.backup(dest)
|
||||
finally:
|
||||
src.close()
|
||||
dest.close()
|
||||
return Path(dest_path)
|
||||
|
||||
|
||||
def build_recent_waveforms_zip(db, store, n: int, dest_path: Path) -> dict:
|
||||
"""Zip every on-disk file (event file + .h5/.a5.pkl/.sfm.json siblings) for
|
||||
the n most-recent events, arcname '<serial>/<filename>'. Events with no
|
||||
resolvable files on disk are skipped. Returns {'events': int, 'files': int}."""
|
||||
rows = db.query_events(limit=n, offset=0)
|
||||
events = 0
|
||||
files = 0
|
||||
with zipfile.ZipFile(dest_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
for row in rows:
|
||||
serial = row.get("serial")
|
||||
fn = row.get("blastware_filename")
|
||||
if not serial or not fn:
|
||||
continue
|
||||
serial_dir = store.root / serial
|
||||
matched = sorted(serial_dir.glob(f"{fn}*")) if serial_dir.is_dir() else []
|
||||
matched = [p for p in matched if p.is_file()]
|
||||
if not matched:
|
||||
continue
|
||||
events += 1
|
||||
for p in matched:
|
||||
zf.write(p, arcname=f"{serial}/{p.name}")
|
||||
files += 1
|
||||
return {"events": events, "files": files}
|
||||
|
||||
|
||||
def sfm_db_restore_enabled() -> bool:
|
||||
return os.getenv("SFM_DB_RESTORE_ENABLED", "").strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _assert_sqlite(path: Path) -> None:
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(16)
|
||||
if head != b"SQLite format 3\x00":
|
||||
raise ValueError(f"{path} is not a SQLite database")
|
||||
|
||||
|
||||
def restore_db_and_waveforms(db_path: Path, waveform_root: Path,
|
||||
new_db_path: Path, waveforms_zip_path) -> dict:
|
||||
"""Safety-backup the current seismo_relay.db, atomically swap in
|
||||
new_db_path, clear stale -wal/-shm sidecars, then unpack the waveforms zip
|
||||
under waveform_root. SFM opens a fresh connection per call, so an in-place
|
||||
atomic replace is safe."""
|
||||
db_path = Path(db_path)
|
||||
new_db_path = Path(new_db_path)
|
||||
_assert_sqlite(new_db_path)
|
||||
|
||||
safety_name = None
|
||||
if db_path.exists():
|
||||
ts = datetime.datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
||||
safety = db_path.with_name(f"{db_path.name}.pre-restore-{ts}")
|
||||
snapshot_db(db_path, safety)
|
||||
safety_name = safety.name
|
||||
|
||||
# Clear the OUTGOING db's WAL sidecars so they cannot attach to the incoming file.
|
||||
for sfx in ("-wal", "-shm"):
|
||||
side = Path(str(db_path) + sfx)
|
||||
if side.exists():
|
||||
side.unlink()
|
||||
|
||||
incoming = db_path.with_name(db_path.name + ".incoming")
|
||||
shutil.copy2(new_db_path, incoming)
|
||||
os.replace(incoming, db_path) # atomic within the same directory
|
||||
|
||||
unpacked = 0
|
||||
if waveforms_zip_path and Path(waveforms_zip_path).exists():
|
||||
waveform_root = Path(waveform_root)
|
||||
waveform_root.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(waveforms_zip_path) as zf:
|
||||
for m in zf.namelist():
|
||||
if m.endswith("/") or m.startswith("/") or ".." in Path(m).parts:
|
||||
continue
|
||||
zf.extract(m, waveform_root)
|
||||
unpacked += 1
|
||||
|
||||
return {"ok": True, "db_restored": True,
|
||||
"waveforms_unpacked": unpacked, "safety_backup": safety_name}
|
||||
@@ -0,0 +1,909 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>SFM Event Browser</title>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
background: #0d1117;
|
||||
color: #c9d1d9;
|
||||
font-family: 'Segoe UI', system-ui, sans-serif;
|
||||
font-size: 13px;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
header {
|
||||
background: #161b22;
|
||||
border-bottom: 1px solid #30363d;
|
||||
padding: 12px 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #f0f6fc;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
label { color: #8b949e; font-size: 12px; }
|
||||
|
||||
select, input[type="text"], input[type="search"] {
|
||||
background: #0d1117;
|
||||
border: 1px solid #30363d;
|
||||
border-radius: 6px;
|
||||
color: #c9d1d9;
|
||||
padding: 5px 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
select { min-width: 140px; }
|
||||
input[type="search"] { width: 200px; }
|
||||
select:focus, input:focus { outline: none; border-color: #388bfd; }
|
||||
|
||||
button {
|
||||
background: #1f6feb;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
padding: 5px 14px;
|
||||
}
|
||||
button:hover { background: #388bfd; }
|
||||
button:disabled { background: #21262d; color: #484f58; cursor: not-allowed; }
|
||||
|
||||
#main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ── Event list (left sidebar) ────────────────────────────────── */
|
||||
#event-list-wrap {
|
||||
width: 320px;
|
||||
flex-shrink: 0;
|
||||
background: #0d1117;
|
||||
border-right: 1px solid #21262d;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
#event-list-header {
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid #21262d;
|
||||
font-size: 11px;
|
||||
color: #8b949e;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
#event-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.event-row {
|
||||
padding: 8px 14px;
|
||||
border-bottom: 1px solid #161b22;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
.event-row:hover { background: #161b22; }
|
||||
.event-row.active { background: #1f3a5f; border-left: 3px solid #58a6ff; padding-left: 11px; }
|
||||
.event-row .er-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.event-row .er-ts { font-family: monospace; font-size: 12px; color: #c9d1d9; }
|
||||
.event-row .er-pvs { font-family: monospace; font-size: 12px; color: #58a6ff; font-weight: 600; }
|
||||
.event-row .er-meta { font-size: 11px; color: #8b949e; }
|
||||
.event-row.false_trigger .er-pvs { color: #f85149; text-decoration: line-through; }
|
||||
|
||||
/* ── Main viewer (right side) ─────────────────────────────────── */
|
||||
#viewer {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#event-meta {
|
||||
padding: 12px 20px;
|
||||
background: #161b22;
|
||||
border-bottom: 1px solid #21262d;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
gap: 8px 24px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.meta-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
.meta-field .mf-label {
|
||||
font-size: 10px;
|
||||
color: #484f58;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
.meta-field .mf-value {
|
||||
font-family: monospace;
|
||||
font-size: 13px;
|
||||
color: #c9d1d9;
|
||||
}
|
||||
.meta-field .mf-value.highlight { color: #58a6ff; font-weight: 600; }
|
||||
|
||||
#charts {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 12px 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.chart-wrap {
|
||||
background: #161b22;
|
||||
border: 1px solid #21262d;
|
||||
border-radius: 8px;
|
||||
padding: 10px 30px 8px 12px; /* right padding leaves room for the "0.0" baseline label */
|
||||
}
|
||||
.chart-label {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 4px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.chart-canvas-wrap { position: relative; height: 130px; }
|
||||
|
||||
.ch-tran { color: #58a6ff; }
|
||||
.ch-vert { color: #3fb950; }
|
||||
.ch-long { color: #d29922; }
|
||||
.ch-micl { color: #bc8cff; }
|
||||
|
||||
#status-bar {
|
||||
background: #161b22;
|
||||
border-top: 1px solid #21262d;
|
||||
padding: 5px 20px;
|
||||
font-size: 12px;
|
||||
color: #8b949e;
|
||||
min-height: 26px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
#status-bar.error { color: #f85149; }
|
||||
#status-bar.ok { color: #3fb950; }
|
||||
|
||||
#empty-state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #484f58;
|
||||
gap: 8px;
|
||||
}
|
||||
#empty-state svg { opacity: 0.3; }
|
||||
|
||||
.pill {
|
||||
background: #21262d;
|
||||
border-radius: 4px;
|
||||
padding: 2px 8px;
|
||||
color: #c9d1d9;
|
||||
font-family: monospace;
|
||||
font-size: 11px;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
/* Per-channel stats table in the metadata header */
|
||||
.stats-table {
|
||||
grid-column: 1 / -1;
|
||||
border-collapse: collapse;
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.stats-table th, .stats-table td {
|
||||
padding: 3px 14px 3px 0;
|
||||
text-align: left;
|
||||
color: #c9d1d9;
|
||||
}
|
||||
.stats-table th {
|
||||
color: #484f58;
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* ── Print view (light theme matching the Instantel printout) ─── */
|
||||
body.print-view {
|
||||
background: #ffffff;
|
||||
color: #000000;
|
||||
}
|
||||
body.print-view header,
|
||||
body.print-view #event-list-wrap,
|
||||
body.print-view #event-list-header,
|
||||
body.print-view #event-meta,
|
||||
body.print-view #status-bar,
|
||||
body.print-view .chart-wrap {
|
||||
background: #ffffff;
|
||||
border-color: #cccccc;
|
||||
color: #000000;
|
||||
}
|
||||
body.print-view .event-row { color: #000; border-bottom-color: #eee; }
|
||||
body.print-view .event-row:hover { background: #f4f4f4; }
|
||||
body.print-view .event-row.active {
|
||||
background: #e6f0ff;
|
||||
border-left-color: #1f6feb;
|
||||
}
|
||||
body.print-view .er-ts { color: #000; }
|
||||
body.print-view .er-pvs { color: #003a8c; }
|
||||
body.print-view .er-meta,
|
||||
body.print-view #event-list-header,
|
||||
body.print-view .meta-field .mf-label,
|
||||
body.print-view .stats-table th {
|
||||
color: #666;
|
||||
}
|
||||
body.print-view .mf-value { color: #000; }
|
||||
body.print-view .mf-value.highlight { color: #003a8c; }
|
||||
body.print-view label { color: #444; }
|
||||
body.print-view input, body.print-view select {
|
||||
background: #fff; color: #000; border-color: #ccc;
|
||||
}
|
||||
/* In print theme, the channel-label colors stay (they identify
|
||||
the trace). Only the chart panel background flips. */
|
||||
|
||||
@media print {
|
||||
header, #event-list-wrap, #status-bar, button { display: none !important; }
|
||||
body { overflow: visible; height: auto; }
|
||||
#main, #viewer { overflow: visible; }
|
||||
#charts { overflow: visible; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header>
|
||||
<h1>SFM Event Browser</h1>
|
||||
<label>Serial</label>
|
||||
<select id="serial-select">
|
||||
<option value="">Loading…</option>
|
||||
</select>
|
||||
<input type="search" id="event-filter" placeholder="filter events…" />
|
||||
<span class="pill" id="count-pill">—</span>
|
||||
<button id="mic-unit-toggle" style="margin-left:auto;background:#21262d"
|
||||
onclick="_setMicUnit(_getMicUnit() === 'dBL' ? 'psi' : 'dBL')"
|
||||
title="Toggle mic display unit (dBL ↔ psi). Persists across page loads.">
|
||||
Mic: dBL
|
||||
</button>
|
||||
<button id="print-btn" onclick="togglePrintView()" style="background:#21262d">Print view</button>
|
||||
<button id="reload-btn" onclick="loadSerials()">Reload</button>
|
||||
</header>
|
||||
|
||||
<div id="main">
|
||||
<div id="event-list-wrap">
|
||||
<div id="event-list-header">
|
||||
<span>Events</span>
|
||||
<span id="event-list-count">—</span>
|
||||
</div>
|
||||
<div id="event-list"></div>
|
||||
</div>
|
||||
|
||||
<div id="viewer">
|
||||
<div id="empty-state">
|
||||
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
|
||||
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
|
||||
</svg>
|
||||
<p>Select a unit and event to view its waveform.</p>
|
||||
</div>
|
||||
<div id="event-meta" style="display:none"></div>
|
||||
<div id="charts" style="display:none"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="status-bar">Ready.</div>
|
||||
|
||||
<script>
|
||||
// Channel colors and rendering order mirror Instantel's BW Event Report
|
||||
// printout: MicL at the top, Tran at the bottom. Colors approximate
|
||||
// what BW renders (magenta mic, blue long, green vert, red tran).
|
||||
const CHANNEL_COLORS = {
|
||||
MicL: '#e066ff',
|
||||
Long: '#3a80ff',
|
||||
Vert: '#3fb950',
|
||||
Tran: '#f85149',
|
||||
};
|
||||
const CHANNEL_ORDER = ['MicL', 'Long', 'Vert', 'Tran'];
|
||||
|
||||
// Reference pressure for dB(L) — 20 µPa expressed in psi (≈ 2.9e-9 psi).
|
||||
const DBL_REF = 2.9e-9;
|
||||
|
||||
// User-toggleable mic display unit: 'dBL' (default, matches BW printout
|
||||
// + the rest of SFM) or 'psi' (raw sample unit).
|
||||
function _getMicUnit() {
|
||||
return localStorage.getItem('sfm_mic_unit') === 'psi' ? 'psi' : 'dBL';
|
||||
}
|
||||
function _setMicUnit(u) {
|
||||
localStorage.setItem('sfm_mic_unit', u === 'psi' ? 'psi' : 'dBL');
|
||||
_refreshMicUnitToggle();
|
||||
if (currentEventId) loadEvent(currentEventId);
|
||||
}
|
||||
function _refreshMicUnitToggle() {
|
||||
const b = document.getElementById('mic-unit-toggle');
|
||||
if (b) b.textContent = `Mic: ${_getMicUnit()}`;
|
||||
}
|
||||
// psi → dB(L). Null for non-positive (log undefined; Chart.js renders as a gap).
|
||||
function _psiToDbl(psi) {
|
||||
if (psi == null || !(psi > 0)) return null;
|
||||
return 20 * Math.log10(psi / DBL_REF);
|
||||
}
|
||||
|
||||
// Per-sample mic chart conversion — rectify the AC waveform, dBL,
|
||||
// floor below the noise-floor minimum. Gives a continuous baseline
|
||||
// instead of the spikey/discontinuous look you get from raw _psiToDbl.
|
||||
const MIC_DBL_FLOOR = 60;
|
||||
function _psiToDblForChart(psi) {
|
||||
if (psi == null) return MIC_DBL_FLOOR;
|
||||
const a = Math.abs(psi);
|
||||
if (a === 0) return MIC_DBL_FLOOR;
|
||||
const dbl = 20 * Math.log10(a / DBL_REF);
|
||||
return dbl > MIC_DBL_FLOOR ? dbl : MIC_DBL_FLOOR;
|
||||
}
|
||||
|
||||
// Format an ISO timestamp in the browser's local timezone — UTC values
|
||||
// (with 'Z' suffix) convert; naive values are interpreted as local clock.
|
||||
// Returns '—' for null/empty/unparseable.
|
||||
function _fmtTsLocal(iso) {
|
||||
if (!iso) return '—';
|
||||
const d = new Date(iso);
|
||||
if (isNaN(d)) return iso;
|
||||
return d.toLocaleString();
|
||||
}
|
||||
|
||||
// Adaptive decimal formatter — scientific notation only for truly extreme
|
||||
// values. Normal-range peaks render as plain decimals with sensible
|
||||
// precision (was previously forcing toExponential(3) which produced ugly
|
||||
// "2.500E-2 IN/S" labels).
|
||||
function _fmtPeak(v, unit) {
|
||||
if (v == null || (typeof v === 'number' && !isFinite(v))) return '';
|
||||
if (typeof v !== 'number') return String(v) + (unit ? ' ' + unit : '');
|
||||
if (v === 0) return '0' + (unit ? ' ' + unit : '');
|
||||
const a = Math.abs(v);
|
||||
const u = unit ? ' ' + unit : '';
|
||||
if (a >= 0.0001 && a < 10000) {
|
||||
const d = a >= 100 ? 1 : a >= 10 ? 2 : a >= 1 ? 3 : a >= 0.1 ? 4 : 5;
|
||||
return v.toFixed(d) + u;
|
||||
}
|
||||
return v.toExponential(2) + u;
|
||||
}
|
||||
|
||||
let allEvents = [];
|
||||
let filteredEvents = [];
|
||||
let currentEventId = null;
|
||||
let charts = {};
|
||||
|
||||
const apiBase = window.location.origin;
|
||||
|
||||
function setStatus(msg, cls = '') {
|
||||
const bar = document.getElementById('status-bar');
|
||||
bar.textContent = msg;
|
||||
bar.className = cls;
|
||||
}
|
||||
|
||||
async function loadSerials() {
|
||||
setStatus('Loading serials…');
|
||||
try {
|
||||
const r = await fetch(`${apiBase}/db/units`);
|
||||
if (!r.ok) throw new Error(r.statusText);
|
||||
// /db/units returns a bare list[dict], not {units:[...]}
|
||||
const units = await r.json();
|
||||
const sel = document.getElementById('serial-select');
|
||||
sel.innerHTML = '';
|
||||
if (!units || units.length === 0) {
|
||||
sel.innerHTML = '<option value="">(no units found)</option>';
|
||||
setStatus('No units in DB.', 'error');
|
||||
return;
|
||||
}
|
||||
sel.innerHTML = '<option value="">— pick a unit —</option>' +
|
||||
units.map(u => {
|
||||
const n = u.total_events ?? 0;
|
||||
return `<option value="${u.serial}">${u.serial} (${n} events)</option>`;
|
||||
}).join('');
|
||||
setStatus(`Loaded ${units.length} units.`, 'ok');
|
||||
} catch (e) {
|
||||
setStatus(`Failed to load units: ${e.message}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEventsForSerial(serial) {
|
||||
if (!serial) {
|
||||
allEvents = [];
|
||||
renderEventList();
|
||||
return;
|
||||
}
|
||||
setStatus(`Loading events for ${serial}…`);
|
||||
try {
|
||||
const r = await fetch(`${apiBase}/db/events?serial=${encodeURIComponent(serial)}&limit=500`);
|
||||
if (!r.ok) throw new Error(r.statusText);
|
||||
const d = await r.json();
|
||||
allEvents = d.events || [];
|
||||
document.getElementById('count-pill').textContent = `${allEvents.length} events`;
|
||||
applyFilter();
|
||||
setStatus(`Loaded ${allEvents.length} events for ${serial}.`, 'ok');
|
||||
} catch (e) {
|
||||
setStatus(`Failed to load events: ${e.message}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function applyFilter() {
|
||||
const q = document.getElementById('event-filter').value.toLowerCase().trim();
|
||||
if (!q) {
|
||||
filteredEvents = allEvents;
|
||||
} else {
|
||||
filteredEvents = allEvents.filter(ev =>
|
||||
(ev.blastware_filename || '').toLowerCase().includes(q) ||
|
||||
(ev.timestamp || '').toLowerCase().includes(q) ||
|
||||
(ev.record_type || '').toLowerCase().includes(q) ||
|
||||
(ev.project || '').toLowerCase().includes(q)
|
||||
);
|
||||
}
|
||||
document.getElementById('event-list-count').textContent = `${filteredEvents.length} / ${allEvents.length}`;
|
||||
renderEventList();
|
||||
}
|
||||
|
||||
function renderEventList() {
|
||||
const list = document.getElementById('event-list');
|
||||
list.innerHTML = '';
|
||||
if (filteredEvents.length === 0) {
|
||||
list.innerHTML = '<div style="padding:14px;color:#484f58;font-size:12px">No events.</div>';
|
||||
return;
|
||||
}
|
||||
for (const ev of filteredEvents) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'event-row' + (ev.false_trigger ? ' false_trigger' : '');
|
||||
if (ev.id === currentEventId) row.className += ' active';
|
||||
const ts = _fmtTsLocal(ev.timestamp);
|
||||
const pvs = ev.peak_vector_sum != null ? `${ev.peak_vector_sum.toFixed(3)} in/s` : '—';
|
||||
row.innerHTML = `
|
||||
<div class="er-top">
|
||||
<span class="er-ts">${ts || '(no ts)'}</span>
|
||||
<span class="er-pvs">${pvs}</span>
|
||||
</div>
|
||||
<div class="er-meta">${ev.record_type || '?'} · ${ev.blastware_filename || ev.id.slice(0,8)}</div>
|
||||
`;
|
||||
row.onclick = () => loadEvent(ev.id);
|
||||
list.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEvent(eventId) {
|
||||
currentEventId = eventId;
|
||||
renderEventList();
|
||||
setStatus('Loading waveform…');
|
||||
try {
|
||||
// Sidecar fetch runs in parallel — its bw_report block carries ZC
|
||||
// Freq + above-range flags + sensor-check results that the per-
|
||||
// channel stats table surfaces. Failures are non-fatal (legacy
|
||||
// events without a preserved .TXT have no sidecar bw_report).
|
||||
const sidecarP = fetch(`${apiBase}/db/events/${eventId}/sidecar`)
|
||||
.then(r => r.ok ? r.json() : null)
|
||||
.catch(() => null);
|
||||
|
||||
const r = await fetch(`${apiBase}/db/events/${eventId}/waveform.json`);
|
||||
if (!r.ok) {
|
||||
if (r.status === 404) {
|
||||
showEmpty('No waveform data for this event (codec returned no samples).');
|
||||
return;
|
||||
}
|
||||
throw new Error(r.statusText);
|
||||
}
|
||||
const data = await r.json();
|
||||
renderWaveform(data);
|
||||
// Also fetch metadata from the events list for richer header
|
||||
const ev = allEvents.find(e => e.id === eventId);
|
||||
const sidecar = await sidecarP;
|
||||
renderMeta(data, ev, sidecar);
|
||||
setStatus(`Event loaded.`, 'ok');
|
||||
} catch (e) {
|
||||
setStatus(`Failed to load event: ${e.message}`, 'error');
|
||||
showEmpty(`Error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function showEmpty(msg) {
|
||||
document.getElementById('empty-state').style.display = 'flex';
|
||||
document.getElementById('empty-state').querySelector('p').textContent = msg;
|
||||
document.getElementById('event-meta').style.display = 'none';
|
||||
document.getElementById('charts').style.display = 'none';
|
||||
Object.values(charts).forEach(c => c.destroy());
|
||||
charts = {};
|
||||
}
|
||||
|
||||
function renderMeta(data, ev, sidecar) {
|
||||
const metaDiv = document.getElementById('event-meta');
|
||||
const fields = [
|
||||
['Serial', data.serial || ev?.serial || '—'],
|
||||
['Timestamp', _fmtTsLocal(data.timestamp || ev?.timestamp)],
|
||||
['Record', data.record_type || ev?.record_type || '—'],
|
||||
['Sample rate', data.sample_rate ? `${data.sample_rate} sps` : '—'],
|
||||
['Geo range', data.geo_range ? `${data.geo_range} (${data.geo_full_scale_ips} in/s FS)` : '—'],
|
||||
['Project', ev?.project || '—'],
|
||||
['Location', ev?.sensor_location || '—'],
|
||||
['Peak Vector Sum',
|
||||
ev?.peak_vector_sum != null ? `${ev.peak_vector_sum.toFixed(4)} in/s` : '—'],
|
||||
];
|
||||
|
||||
// Per-channel stats table mirroring the printout's middle block.
|
||||
// PPV from the events DB row; ZC Freq + saturation flags from the
|
||||
// sidecar's bw_report block (when a .TXT was preserved on ingest).
|
||||
const bwrPeaks = (sidecar?.bw_report || {}).peaks || {};
|
||||
const bwrMic = (sidecar?.bw_report || {}).mic || {};
|
||||
const fmt = v => (v == null ? '—' : (typeof v === 'number' ? v.toFixed(3) : v));
|
||||
const fmtZc = bwr => {
|
||||
if (!bwr || bwr.zc_freq_hz == null) return '—';
|
||||
const prefix = bwr.zc_freq_above_range ? '>' : '';
|
||||
return `${prefix}${Math.round(bwr.zc_freq_hz)} Hz`;
|
||||
};
|
||||
const rows = [
|
||||
['Tran', ev?.tran_ppv, fmtZc(bwrPeaks.tran)],
|
||||
['Vert', ev?.vert_ppv, fmtZc(bwrPeaks.vert)],
|
||||
['Long', ev?.long_ppv, fmtZc(bwrPeaks.long)],
|
||||
];
|
||||
// Mic display honors the current user preference (dBL default).
|
||||
// mic_ppv is stored as raw psi on series3 events; convert when needed.
|
||||
const micPsi = ev?.mic_ppv;
|
||||
const micUnitDisplay = _getMicUnit();
|
||||
let micStr;
|
||||
if (micPsi == null) {
|
||||
micStr = '—';
|
||||
} else if (micUnitDisplay === 'dBL') {
|
||||
const d = _psiToDbl(Number(micPsi));
|
||||
micStr = (d != null ? d.toFixed(1) : '—') + ' dBL';
|
||||
} else {
|
||||
micStr = Number(micPsi).toExponential(2) + ' psi';
|
||||
}
|
||||
const statsHtml = `
|
||||
<table class="stats-table">
|
||||
<thead>
|
||||
<tr><th>Channel</th><th>PPV (in/s)</th><th>ZC Freq</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${rows.map(([ch, ppv, zc]) => `<tr><td>${ch}</td><td>${fmt(ppv)}</td><td>${zc}</td></tr>`).join('')}
|
||||
<tr><td>MicL</td><td>${micStr}</td><td>${fmtZc(bwrMic)}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
`;
|
||||
|
||||
metaDiv.innerHTML =
|
||||
fields.map(([l, v]) =>
|
||||
`<div class="meta-field"><span class="mf-label">${l}</span><span class="mf-value${l === 'Peak Vector Sum' ? ' highlight' : ''}">${v}</span></div>`
|
||||
).join('') + statsHtml;
|
||||
metaDiv.style.display = 'grid';
|
||||
}
|
||||
|
||||
function togglePrintView() {
|
||||
document.body.classList.toggle('print-view');
|
||||
// Force chart redraw so axis/grid colors are re-evaluated against the
|
||||
// new background. Easiest: re-render the current event.
|
||||
if (currentEventId) {
|
||||
loadEvent(currentEventId);
|
||||
}
|
||||
}
|
||||
|
||||
function renderWaveform(data) {
|
||||
document.getElementById('empty-state').style.display = 'none';
|
||||
const chartsDiv = document.getElementById('charts');
|
||||
chartsDiv.style.display = 'flex';
|
||||
chartsDiv.innerHTML = '';
|
||||
Object.values(charts).forEach(c => c.destroy());
|
||||
charts = {};
|
||||
|
||||
const channels = data.channels || {};
|
||||
// time_axis is METADATA from sfm.plot.v1 — sample_rate, pretrig_samples,
|
||||
// t0_ms (first-sample time relative to trigger; negative when pretrig
|
||||
// exists), dt_ms. Trigger is at t=0 by convention.
|
||||
const ta = data.time_axis || {};
|
||||
const sr = ta.sample_rate || 1024;
|
||||
const dtMs = ta.dt_ms || (1000.0 / sr);
|
||||
const t0Ms = ta.t0_ms != null ? ta.t0_ms : 0;
|
||||
const isPrintMode = document.body.classList.contains('print-view');
|
||||
// Histograms record per-interval peaks (typically 1 per minute/5-min),
|
||||
// not per-sample waveforms. Render as a tight bar graph instead of a
|
||||
// line plot — matches the BW Event Report's histogram presentation.
|
||||
const isHistogram = String(data.record_type || '').toLowerCase().includes('histogram');
|
||||
|
||||
// Which channels actually have data → determines which one renders the
|
||||
// shared x-axis at the bottom (Instantel printout has the time scale
|
||||
// only on the bottom-most chart).
|
||||
const channelsWithData = CHANNEL_ORDER.filter(ch =>
|
||||
channels[ch] && (channels[ch].values || []).length > 0
|
||||
);
|
||||
const lastDataCh = channelsWithData[channelsWithData.length - 1];
|
||||
|
||||
const micUnit = _getMicUnit();
|
||||
for (const ch of CHANNEL_ORDER) {
|
||||
const chData = channels[ch];
|
||||
if (!chData) continue;
|
||||
if ((chData.values || []).length === 0) {
|
||||
// Render an empty card so user sees the channel exists but is missing
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'chart-wrap';
|
||||
wrap.innerHTML = `
|
||||
<div class="chart-label ch-${ch.toLowerCase()}">
|
||||
<span>${ch}</span>
|
||||
<span style="color:#484f58">no samples decoded</span>
|
||||
</div>
|
||||
<div class="chart-canvas-wrap" style="display:flex;align-items:center;justify-content:center;color:#484f58;font-size:12px">empty</div>
|
||||
`;
|
||||
chartsDiv.appendChild(wrap);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Mic channel: convert from raw psi to dB(L) when the user prefers dBL
|
||||
// (the default). We mutate `values`, `peak`, and `unit` locally so the
|
||||
// chart datasets + axis title + tooltip + peak label all stay aligned.
|
||||
let values = chData.values || [];
|
||||
let unit = chData.unit || 'unit';
|
||||
let peak = chData.peak;
|
||||
const peakT = chData.peak_t_ms;
|
||||
if (ch === 'MicL' && unit === 'psi' && micUnit === 'dBL') {
|
||||
// Per-sample chart uses rectified-and-floored conversion so the
|
||||
// baseline is continuous; the peak label uses the unrectified
|
||||
// converter to preserve the true measurement.
|
||||
values = values.map(_psiToDblForChart);
|
||||
peak = _psiToDbl(peak);
|
||||
unit = 'dB(L)';
|
||||
}
|
||||
|
||||
const peakLabel = peak != null
|
||||
? `peak ${_fmtPeak(peak, unit)}`
|
||||
+ (!isHistogram && peakT != null ? ` @ ${peakT.toFixed(1)} ms` : '')
|
||||
: '';
|
||||
// Hide x-axis on every chart except the bottom-most data channel —
|
||||
// gives the "single shared time axis" feel of the BW printout.
|
||||
const showXAxis = (ch === lastDataCh);
|
||||
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'chart-wrap';
|
||||
const lbl = document.createElement('div');
|
||||
lbl.className = `chart-label ch-${ch.toLowerCase()}`;
|
||||
lbl.innerHTML = `<span>${ch}</span><span style="color:#8b949e;font-weight:normal">${peakLabel}</span>`;
|
||||
wrap.appendChild(lbl);
|
||||
|
||||
const canvasWrap = document.createElement('div');
|
||||
canvasWrap.className = 'chart-canvas-wrap';
|
||||
const canvas = document.createElement('canvas');
|
||||
canvasWrap.appendChild(canvas);
|
||||
wrap.appendChild(canvasWrap);
|
||||
chartsDiv.appendChild(wrap);
|
||||
|
||||
// Waveform: per-sample time in ms relative to trigger (negative for pretrig).
|
||||
// Histogram: when the server has aggregated to BW-reported intervals AND
|
||||
// provides per-interval timestamps, use those as x-axis labels (HH:MM:SS).
|
||||
// Falls back to interval index.
|
||||
let times;
|
||||
if (isHistogram) {
|
||||
const intervalTimes = ta.interval_times || [];
|
||||
times = (intervalTimes.length === values.length)
|
||||
? intervalTimes
|
||||
: values.map((_, i) => i + 1);
|
||||
} else {
|
||||
times = values.map((_, i) => t0Ms + i * dtMs);
|
||||
}
|
||||
|
||||
// Downsample for rendering
|
||||
const MAX_POINTS = 4000;
|
||||
let rT = times, rV = values;
|
||||
if (values.length > MAX_POINTS) {
|
||||
const step = Math.ceil(values.length / MAX_POINTS);
|
||||
rT = times.filter((_, i) => i % step === 0);
|
||||
rV = values.filter((_, i) => i % step === 0);
|
||||
}
|
||||
|
||||
// Tick formatter — round to 1 decimal so we don't get
|
||||
// "11.7187040000000002 ms" garbage from floating-point accumulation.
|
||||
const xAxisUnit = isHistogram ? '' : ' ms';
|
||||
const fmtTick = i => {
|
||||
const v = rT[i];
|
||||
if (typeof v !== 'number') return String(v) + xAxisUnit;
|
||||
return (Number.isInteger(v) ? String(v) : v.toFixed(1)) + xAxisUnit;
|
||||
};
|
||||
|
||||
// Y-axis bounds. Geophone waveforms render symmetric around zero
|
||||
// (seismograph convention — zero line in the middle, signal goes
|
||||
// up AND down). Mic + histograms keep default auto-scale (always
|
||||
// positive values; zero at the bottom).
|
||||
let yBounds = {};
|
||||
const isGeo = ch !== 'MicL';
|
||||
if (isGeo && !isHistogram) {
|
||||
// Waveform geo: symmetric around zero for full shape detail.
|
||||
let absMax = 0;
|
||||
for (const v of values) {
|
||||
const a = Math.abs(v);
|
||||
if (a > absMax) absMax = a;
|
||||
}
|
||||
const padded = (absMax || 1) * 1.10;
|
||||
yBounds = { min: -padded, max: padded };
|
||||
} else if (isGeo && isHistogram) {
|
||||
// Histogram geo: enforce minimum chart range so quiet events
|
||||
// look quiet (matches BW's near-fixed-scale convention).
|
||||
const HIST_GEO_MIN_INS = 0.05;
|
||||
let p = 0;
|
||||
for (const v of values) { const a = Math.abs(v); if (a > p) p = a; }
|
||||
yBounds = { min: 0, max: Math.max(p * 1.10, HIST_GEO_MIN_INS) };
|
||||
} else if (ch === 'MicL' && micUnit === 'dBL') {
|
||||
// Mic dBL: baseline at noise-floor minimum, top at peak + 5 dB.
|
||||
const peakDbl = (typeof peak === 'number' && isFinite(peak))
|
||||
? peak + 5
|
||||
: 100;
|
||||
yBounds = { min: MIC_DBL_FLOOR, max: Math.max(peakDbl, MIC_DBL_FLOOR + 20) };
|
||||
} else if (ch === 'MicL' && isHistogram && micUnit === 'psi') {
|
||||
// Mic histogram in psi: same minimum-range treatment as geo.
|
||||
const HIST_MIC_MIN_PSI = 0.001;
|
||||
let p = 0;
|
||||
for (const v of values) { const a = Math.abs(v); if (a > p) p = a; }
|
||||
yBounds = { min: 0, max: Math.max(p * 1.10, HIST_MIC_MIN_PSI) };
|
||||
}
|
||||
|
||||
const chart = new Chart(canvas, {
|
||||
type: isHistogram ? 'bar' : 'line',
|
||||
data: {
|
||||
labels: rT.map(t => (typeof t === 'number' ? (Number.isInteger(t) ? String(t) : t.toFixed(2)) : t)),
|
||||
datasets: isHistogram ? [{
|
||||
data: rV,
|
||||
backgroundColor: CHANNEL_COLORS[ch],
|
||||
borderWidth: 0,
|
||||
barPercentage: 1.0,
|
||||
categoryPercentage: 1.0, // bars touch — tight bargraph
|
||||
}] : [{
|
||||
data: rV,
|
||||
borderColor: CHANNEL_COLORS[ch],
|
||||
borderWidth: 1,
|
||||
pointRadius: 0,
|
||||
tension: 0,
|
||||
}],
|
||||
},
|
||||
options: {
|
||||
animation: false,
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
callbacks: {
|
||||
title: items => isHistogram
|
||||
? `interval ${items[0].label}`
|
||||
: `t = ${items[0].label} ms`,
|
||||
label: item => `${ch}: ${_fmtPeak(item.raw, unit)}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
type: 'category',
|
||||
display: showXAxis,
|
||||
ticks: {
|
||||
color: isPrintMode ? '#666' : '#484f58',
|
||||
maxTicksLimit: 10,
|
||||
maxRotation: 0,
|
||||
callback: (val, i) => fmtTick(i),
|
||||
},
|
||||
grid: { color: isPrintMode ? '#e0e0e0' : '#21262d', drawTicks: showXAxis },
|
||||
},
|
||||
y: {
|
||||
...yBounds,
|
||||
ticks: { color: isPrintMode ? '#666' : '#484f58', maxTicksLimit: 5 },
|
||||
grid: { color: isPrintMode ? '#e0e0e0' : '#21262d' },
|
||||
title: { display: true, text: unit,
|
||||
color: isPrintMode ? '#666' : '#484f58', font: { size: 10 } },
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: isHistogram ? [] : [{
|
||||
// Trigger line @ t=0 + triangle markers above/below + "0.0"
|
||||
// baseline label on the right edge. Matches the Instantel
|
||||
// BW Event Report printout style. Skipped for histograms —
|
||||
// they have no trigger event.
|
||||
id: 'instantelOverlays',
|
||||
afterDraw(chart) {
|
||||
const ctx = chart.ctx;
|
||||
const xAxis = chart.scales.x;
|
||||
const yAxis = chart.scales.y;
|
||||
const fgPrim = isPrintMode ? '#000' : '#c9d1d9';
|
||||
const fgTrigger = '#f85149';
|
||||
|
||||
// Dashed vertical trigger line at t=0
|
||||
const zeroIdx = rT.findIndex(t => parseFloat(t) >= 0);
|
||||
if (zeroIdx >= 0) {
|
||||
const x = xAxis.getPixelForValue(zeroIdx);
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, yAxis.top);
|
||||
ctx.lineTo(x, yAxis.bottom);
|
||||
ctx.strokeStyle = isPrintMode ? '#cc0000' : 'rgba(248, 81, 73, 0.8)';
|
||||
ctx.lineWidth = 1.2;
|
||||
ctx.setLineDash([4, 3]);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
|
||||
// Triangles above and below the chart at the trigger column
|
||||
ctx.save();
|
||||
ctx.fillStyle = fgTrigger;
|
||||
ctx.beginPath(); // top triangle pointing down
|
||||
ctx.moveTo(x - 5, yAxis.top - 8);
|
||||
ctx.lineTo(x + 5, yAxis.top - 8);
|
||||
ctx.lineTo(x, yAxis.top - 1);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.beginPath(); // bottom triangle pointing up
|
||||
ctx.moveTo(x - 5, yAxis.bottom + 8);
|
||||
ctx.lineTo(x + 5, yAxis.bottom + 8);
|
||||
ctx.lineTo(x, yAxis.bottom + 1);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// "0.0" baseline label on the right edge — printout convention.
|
||||
// Position vertically at the zero-amplitude level.
|
||||
const zeroY = yAxis.getPixelForValue(0);
|
||||
if (zeroY >= yAxis.top && zeroY <= yAxis.bottom) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = isPrintMode ? '#aaa' : '#30363d';
|
||||
ctx.lineWidth = 0.8;
|
||||
ctx.setLineDash([2, 2]);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(xAxis.left, zeroY);
|
||||
ctx.lineTo(xAxis.right, zeroY);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
|
||||
ctx.save();
|
||||
ctx.fillStyle = fgPrim;
|
||||
ctx.font = '11px monospace';
|
||||
ctx.textAlign = 'left';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText('0.0', xAxis.right + 6, zeroY);
|
||||
ctx.restore();
|
||||
}
|
||||
},
|
||||
}],
|
||||
});
|
||||
charts[ch] = chart;
|
||||
}
|
||||
}
|
||||
|
||||
// Wire up handlers
|
||||
document.getElementById('serial-select').addEventListener('change', e => {
|
||||
loadEventsForSerial(e.target.value);
|
||||
});
|
||||
document.getElementById('event-filter').addEventListener('input', applyFilter);
|
||||
|
||||
// Reflect any persisted mic-unit preference in the header pill on load
|
||||
_refreshMicUnitToggle();
|
||||
|
||||
// Initial load
|
||||
loadSerials();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+18
-5
@@ -77,6 +77,20 @@ _GEO_FS_BY_RANGE = {
|
||||
}
|
||||
_INT16_FS = 32768.0
|
||||
|
||||
# Geophone full-scale count. NOT 32768: the verified body codec emits geo
|
||||
# samples in 16-count units whose documented LSB is exactly 0.005 in/s, and
|
||||
# ``waveform_codec.decoded_to_adc_counts`` multiplies by 16 — so one ADC count
|
||||
# is 0.005/16 in/s and Normal range (10.000 in/s) is 10.0 / (0.005/16) = 32000
|
||||
# counts. Using 32768 here made every geophone reading 2.3% low
|
||||
# (1 - 32000/32768 = 0.0234).
|
||||
#
|
||||
# Confirmed 2026-08-25 against 216 per-channel comparisons with the preserved
|
||||
# Blastware ASCII exports: 32000 gives 216/216 exact within 1 LSB (worst error
|
||||
# 0.005 in/s); 32768 gave 151/216 with a worst error of 0.238 in/s on a
|
||||
# 10 in/s event. The mic path is unaffected — it back-solves its own scale
|
||||
# from the device-reported peak (see _mic_scale_factor).
|
||||
_GEO_INT16_FS = 32000.0
|
||||
|
||||
# Default mic conversion: ADC count → psi. Approximate; exact factor
|
||||
# depends on firmware reference voltage and mic sensitivity, neither of
|
||||
# which is independently confirmed. We try to refine it from the device-
|
||||
@@ -125,15 +139,14 @@ def _samples_to_float(
|
||||
) -> np.ndarray:
|
||||
"""Convert int16 ADC counts → float32 physical units.
|
||||
|
||||
Uses _INT16_FS=32768 (not 32767) so that a count of -32768 maps to
|
||||
exactly -full_scale and +32767 maps to ~+full_scale * 32767/32768.
|
||||
Matches the device firmware's documented mapping (see CLAUDE.md
|
||||
geo_hardware_constant rationale).
|
||||
Uses _GEO_INT16_FS=32000 (see the constant's rationale): one decoder
|
||||
unit (16 ADC counts) is exactly 0.005 in/s, so full scale is 32000
|
||||
counts, not 32768.
|
||||
"""
|
||||
if not samples_int16:
|
||||
return np.array([], dtype=np.float32)
|
||||
arr = np.asarray(samples_int16, dtype=np.int32) # int32 to avoid overflow during scale
|
||||
return (arr.astype(np.float32) * (full_scale / _INT16_FS)).astype(np.float32)
|
||||
return (arr.astype(np.float32) * (full_scale / _GEO_INT16_FS)).astype(np.float32)
|
||||
|
||||
|
||||
def _mic_scale_factor(
|
||||
|
||||
@@ -0,0 +1,939 @@
|
||||
"""
|
||||
sfm/report_pdf.py — generate Instantel-style Event Report PDFs.
|
||||
|
||||
Stub layout for v0.20.0 — the exact visual is iterated against actual
|
||||
Blastware reference PDFs (uploaded to docs/reference/instantel/).
|
||||
Current output captures all the data fields a real BW Event Report
|
||||
contains, but the visual hierarchy / spacing is still approximate.
|
||||
|
||||
Architecture
|
||||
────────────
|
||||
1. ``gather_report_data(event_id)`` — assembles a flat dict from three
|
||||
sources: the SeismoDb events row, the .sfm.json sidecar (bw_report
|
||||
block), and the .h5 waveform samples. Returns ``None`` when the
|
||||
event doesn't exist or has no waveform data on disk.
|
||||
|
||||
2. ``render_event_report_pdf(data)`` — takes that dict and produces a
|
||||
single-page letter-sized PDF as bytes, using matplotlib's PDF
|
||||
backend (vector output, no rasterization, prints cleanly).
|
||||
|
||||
3. The HTTP endpoint at ``/db/events/{id}/report.pdf`` wires them
|
||||
together: fetch event → gather → render → stream bytes back with
|
||||
``Content-Type: application/pdf``.
|
||||
|
||||
What's in the report (every field BW's printout includes):
|
||||
|
||||
Header (left): Date/Time, Trigger Source, Range, Sample Rate, Notes,
|
||||
Project, Client, User Name, Seis. Loc
|
||||
Header (right): Serial + firmware, Battery, Calibration, File Name,
|
||||
Post Event Notes
|
||||
Mic block: PSPL (dBL + psi), ZC Freq, Channel Test result
|
||||
Stats table: per-channel PPV / ZC Freq / Time of Peak /
|
||||
Peak Acceleration / Peak Displacement / Sensor Check
|
||||
Peak Vector Sum
|
||||
Waveform plot: 4 channels stacked (MicL/Long/Vert/Tran), shared
|
||||
time axis, trigger marker, peak markers
|
||||
USBM RI8507/OSMRE compliance chart: STUBBED — separate work item
|
||||
|
||||
Histogram events: the layout differs (Number of Intervals header
|
||||
field, no trigger marker, per-interval bar chart instead of waveform).
|
||||
Handled via a record_type branch in ``render_event_report_pdf``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use("Agg") # headless — no display required
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from matplotlib.backends.backend_pdf import PdfPages
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Reference pressure for dB(L) conversion: 20 µPa expressed in psi.
|
||||
DBL_REF_PSI = 2.9e-9
|
||||
|
||||
|
||||
# ── Data assembly ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReportData:
|
||||
"""All fields needed to render an Instantel-style Event Report.
|
||||
|
||||
Most fields are Optional — BW's printout shows '—' or just omits
|
||||
sections when source data is missing. The renderer mirrors that.
|
||||
"""
|
||||
# Header — left column
|
||||
event_datetime_str: Optional[str] = None
|
||||
trigger_source: Optional[str] = None
|
||||
geo_range_str: Optional[str] = None
|
||||
sample_rate_str: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
project: Optional[str] = None
|
||||
client: Optional[str] = None
|
||||
operator: Optional[str] = None
|
||||
sensor_location: Optional[str] = None
|
||||
|
||||
# Header — right column
|
||||
serial: Optional[str] = None
|
||||
firmware: Optional[str] = None
|
||||
battery_volts: Optional[float] = None
|
||||
calibration_date: Optional[str] = None
|
||||
calibration_by: Optional[str] = None
|
||||
file_name: Optional[str] = None
|
||||
post_event_notes: Optional[str] = None
|
||||
|
||||
# Microphone block
|
||||
mic_pspl_dbl: Optional[float] = None
|
||||
mic_pspl_psi: Optional[float] = None
|
||||
mic_pspl_time_s: Optional[float] = None
|
||||
mic_pspl_when_str: Optional[str] = None # histogram absolute date+time, BW-formatted
|
||||
mic_zc_freq_hz: Optional[float] = None
|
||||
mic_zc_freq_above_range: bool = False
|
||||
mic_channel_test_result: Optional[str] = None
|
||||
mic_channel_test_freq_hz: Optional[float] = None
|
||||
mic_channel_test_amp_mv: Optional[float] = None
|
||||
|
||||
# Per-channel stats — list of dicts (one per channel)
|
||||
# Keys: name, ppv_ips, zc_freq_hz, time_of_peak_s,
|
||||
# peak_accel_g, peak_disp_in, sensor_check
|
||||
channel_stats: list[dict] = field(default_factory=list)
|
||||
|
||||
# Peak Vector Sum
|
||||
peak_vector_sum_ips: Optional[float] = None
|
||||
peak_vector_sum_time_s: Optional[float] = None
|
||||
|
||||
# Waveform samples — channels[ch] = list of floats in physical units
|
||||
# Time axis derived from sample_rate + pretrig_samples
|
||||
channels: dict = field(default_factory=dict)
|
||||
sample_rate_sps: Optional[int] = None
|
||||
pretrig_samples: Optional[int] = None
|
||||
t0_ms: Optional[float] = None
|
||||
dt_ms: Optional[float] = None
|
||||
|
||||
# Record-type discriminator
|
||||
record_type: Optional[str] = None
|
||||
is_histogram: bool = False
|
||||
|
||||
# Histogram-only fields — only populated for record_type starts with 'Hist'
|
||||
histogram_start_str: Optional[str] = None # "22:30:38 May 16, 2026"
|
||||
histogram_stop_str: Optional[str] = None
|
||||
histogram_n_intervals: Optional[float] = None # 4.00
|
||||
histogram_interval_size: Optional[str] = None # "1 minute"
|
||||
histogram_interval_size_s: Optional[float] = None # 60.0 — numeric seconds, used to derive interval_times
|
||||
histogram_interval_times: list[str] = field(default_factory=list) # per-interval timestamps for x-axis
|
||||
|
||||
# Peak Vector Sum metadata (histograms show absolute date+time)
|
||||
peak_vector_sum_when_str: Optional[str] = None
|
||||
|
||||
# Bookkeeping
|
||||
event_id: Optional[str] = None
|
||||
server_received_at: Optional[str] = None
|
||||
bw_pc_sw_version: Optional[str] = None
|
||||
|
||||
|
||||
def gather_report_data(
|
||||
db,
|
||||
store,
|
||||
event_id: str,
|
||||
) -> Optional[ReportData]:
|
||||
"""Collect every field needed to render an event report.
|
||||
|
||||
Returns ``None`` if the event is unknown or has no waveform data
|
||||
on disk (no .h5, no .a5.pkl — same condition the waveform.json
|
||||
endpoint 404s on).
|
||||
"""
|
||||
row = db.get_event(event_id)
|
||||
if row is None:
|
||||
return None
|
||||
serial = row.get("serial")
|
||||
filename = row.get("blastware_filename")
|
||||
if not serial or not filename:
|
||||
return None
|
||||
|
||||
rd = ReportData(
|
||||
event_id=event_id,
|
||||
serial=serial,
|
||||
file_name=filename,
|
||||
record_type=row.get("record_type"),
|
||||
is_histogram=str(row.get("record_type", "")).lower().startswith("hist"),
|
||||
event_datetime_str=row.get("timestamp"),
|
||||
sample_rate_sps=row.get("sample_rate"),
|
||||
project=row.get("project"),
|
||||
client=row.get("client"),
|
||||
operator=row.get("operator"),
|
||||
sensor_location=row.get("sensor_location"),
|
||||
server_received_at=row.get("created_at"),
|
||||
)
|
||||
|
||||
# ── Sidecar bw_report — the rich BW-derived fields ──
|
||||
sidecar_path = store.sidecar_path_for(serial, filename)
|
||||
if sidecar_path.exists():
|
||||
try:
|
||||
sc = json.loads(sidecar_path.read_text())
|
||||
except Exception as exc:
|
||||
log.warning("gather_report_data: sidecar read failed: %s", exc)
|
||||
sc = {}
|
||||
bw = sc.get("bw_report") or {}
|
||||
|
||||
# Trigger / range / sample-rate display
|
||||
trig = bw.get("trigger") or {}
|
||||
rd.trigger_source = (
|
||||
f"{trig.get('channel','')}: {trig.get('geo_level_ips')} in/s"
|
||||
if trig.get("channel") or trig.get("geo_level_ips") is not None
|
||||
else None
|
||||
)
|
||||
rec = bw.get("recording") or {}
|
||||
rd.geo_range_str = (
|
||||
f"Geo: {rec.get('geo_range_ips')} in/s"
|
||||
if rec.get("geo_range_ips") is not None else None
|
||||
)
|
||||
rt = rec.get("record_time_s")
|
||||
if rt is not None and rd.sample_rate_sps:
|
||||
rd.sample_rate_str = f"{rt:.1f} sec At {rd.sample_rate_sps} Sps"
|
||||
|
||||
# Device block
|
||||
dev = bw.get("device") or {}
|
||||
rd.battery_volts = dev.get("battery_volts")
|
||||
rd.calibration_date = dev.get("calibration_date")
|
||||
rd.calibration_by = dev.get("calibration_by")
|
||||
rd.firmware = bw.get("version")
|
||||
rd.bw_pc_sw_version = bw.get("pc_sw_version")
|
||||
|
||||
# Microphone block
|
||||
mic = bw.get("mic") or {}
|
||||
rd.mic_pspl_dbl = mic.get("pspl_dbl")
|
||||
if rd.mic_pspl_dbl is not None and rd.mic_pspl_dbl > 0:
|
||||
# Inverse of the dBL formula → psi. Mirrors waveform_codec convention.
|
||||
rd.mic_pspl_psi = DBL_REF_PSI * (10 ** (rd.mic_pspl_dbl / 20))
|
||||
rd.mic_pspl_time_s = mic.get("time_of_peak_s")
|
||||
rd.mic_zc_freq_hz = mic.get("zc_freq_hz")
|
||||
rd.mic_zc_freq_above_range = bool(mic.get("zc_freq_above_range"))
|
||||
sc_mic = (bw.get("sensor_check") or {}).get("mic") or {}
|
||||
rd.mic_channel_test_result = sc_mic.get("result")
|
||||
rd.mic_channel_test_freq_hz = sc_mic.get("freq_hz")
|
||||
rd.mic_channel_test_amp_mv = sc_mic.get("amplitude_mv")
|
||||
|
||||
# Per-channel stats (Tran / Vert / Long). Per-channel peak
|
||||
# date+time for histograms comes from bw_report.histogram.channel_peak_when
|
||||
# (populated when the parser captured it; see the bw_ascii_report
|
||||
# parser's histogram-fields handler).
|
||||
peaks = bw.get("peaks") or {}
|
||||
sc_block = bw.get("sensor_check") or {}
|
||||
hist_block = bw.get("histogram") or {}
|
||||
peak_when = hist_block.get("channel_peak_when") or {}
|
||||
for ch_lc, ch_label in (("tran", "Tran"), ("vert", "Vert"), ("long", "Long")):
|
||||
ch = peaks.get(ch_lc) or {}
|
||||
sc_ch = sc_block.get(ch_lc) or {}
|
||||
ch_when_iso = peak_when.get(ch_label)
|
||||
peak_date, peak_time = _split_iso_to_date_time(ch_when_iso)
|
||||
rd.channel_stats.append({
|
||||
"name": ch_label,
|
||||
"ppv_ips": ch.get("ppv_ips"),
|
||||
"zc_freq_hz": ch.get("zc_freq_hz"),
|
||||
"zc_freq_above_range": bool(ch.get("zc_freq_above_range")),
|
||||
"time_of_peak_s": ch.get("time_of_peak_s"),
|
||||
"peak_accel_g": ch.get("peak_accel_g"),
|
||||
"peak_disp_in": ch.get("peak_disp_in"),
|
||||
"sensor_check": sc_ch.get("result"),
|
||||
"peak_date": peak_date,
|
||||
"peak_time": peak_time,
|
||||
})
|
||||
|
||||
# MicL peak time (used in the mic block — "PSPL ... on DATE at TIME")
|
||||
mic_when_iso = peak_when.get("MicL")
|
||||
rd.mic_pspl_when_str = _fmt_iso_to_bw(mic_when_iso) if mic_when_iso else None
|
||||
|
||||
# Peak Vector Sum
|
||||
vs = peaks.get("vector_sum") or {}
|
||||
rd.peak_vector_sum_ips = vs.get("ips")
|
||||
rd.peak_vector_sum_time_s = vs.get("time_s")
|
||||
# PVS absolute date+time (histograms). Same formatting as Mic.
|
||||
pvs_when_iso = vs.get("when")
|
||||
rd.peak_vector_sum_when_str = _fmt_iso_to_bw(pvs_when_iso) if pvs_when_iso else None
|
||||
|
||||
# Histogram-specific header fields — keys match the projection in
|
||||
# _bw_report_to_dict ("start" / "stop", not "_str" suffixed).
|
||||
if rd.is_histogram:
|
||||
rd.histogram_start_str = hist_block.get("start") or rd.event_datetime_str
|
||||
rd.histogram_stop_str = hist_block.get("stop")
|
||||
rd.histogram_n_intervals = hist_block.get("n_intervals")
|
||||
rd.histogram_interval_size = hist_block.get("interval_size")
|
||||
rd.histogram_interval_size_s = hist_block.get("interval_size_s")
|
||||
rd.histogram_interval_times = hist_block.get("interval_times") or []
|
||||
|
||||
# ── Waveform samples — from the .h5 via the existing helper ──
|
||||
from sfm import event_hdf5
|
||||
h5_path = store.hdf5_path_for(serial, filename)
|
||||
if h5_path.exists():
|
||||
try:
|
||||
wf = event_hdf5.plot_json_from_hdf5(h5_path, event_id=event_id)
|
||||
rd.channels = {
|
||||
ch: (chd.get("values") or [])
|
||||
for ch, chd in (wf.get("channels") or {}).items()
|
||||
}
|
||||
ta = wf.get("time_axis") or {}
|
||||
rd.sample_rate_sps = rd.sample_rate_sps or ta.get("sample_rate")
|
||||
rd.pretrig_samples = ta.get("pretrig_samples")
|
||||
rd.t0_ms = ta.get("t0_ms")
|
||||
rd.dt_ms = ta.get("dt_ms")
|
||||
except Exception as exc:
|
||||
log.warning("gather_report_data: hdf5 read failed: %s", exc)
|
||||
|
||||
# ── Histogram aggregation ──
|
||||
# Codec emits ~N per-block samples (typically 1/sec); BW reports
|
||||
# one bar per configured interval (1 min / 5 min / etc.). When
|
||||
# bw_report.histogram.n_intervals is populated (events ingested
|
||||
# with the parser extension), group max-per-group to match. Also
|
||||
# derives per-interval timestamps for the x-axis. No-op for
|
||||
# waveform events or when n_intervals is missing.
|
||||
if rd.is_histogram and rd.histogram_n_intervals and rd.histogram_n_intervals >= 1:
|
||||
n = int(rd.histogram_n_intervals)
|
||||
for ch, vals in list(rd.channels.items()):
|
||||
if not vals:
|
||||
continue
|
||||
per_group = len(vals) // n
|
||||
remainder = len(vals) % n
|
||||
agg: list = []
|
||||
offset = 0
|
||||
for i in range(n):
|
||||
grp_size = per_group + (1 if i < remainder else 0)
|
||||
if grp_size > 0:
|
||||
grp = vals[offset:offset + grp_size]
|
||||
agg.append(max((abs(v) for v in grp if v is not None), default=0))
|
||||
offset += grp_size
|
||||
else:
|
||||
agg.append(0)
|
||||
rd.channels[ch] = agg
|
||||
# Derive per-interval HH:MM:SS labels if we have the start time + size
|
||||
if rd.histogram_start_str and rd.histogram_interval_size_s and not rd.histogram_interval_times:
|
||||
try:
|
||||
import datetime as _dt
|
||||
start = _dt.datetime.fromisoformat(rd.histogram_start_str)
|
||||
rd.histogram_interval_times = [
|
||||
(start + _dt.timedelta(seconds=(i + 1) * rd.histogram_interval_size_s)).strftime("%H:%M:%S")
|
||||
for i in range(n)
|
||||
]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return rd
|
||||
|
||||
|
||||
# ── PDF rendering ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def render_event_report_pdf(rd: ReportData) -> bytes:
|
||||
"""Render an event report dict to a single-page letter PDF.
|
||||
|
||||
Branches on ``rd.is_histogram`` — waveform and histogram layouts
|
||||
differ in their header fields, stats-table rows, and bottom plot.
|
||||
Layout modeled on Blastware's Event Report PDFs (samples in
|
||||
docs/reference/instantel/).
|
||||
"""
|
||||
# Letter portrait — 8.5"×11"
|
||||
fig = plt.figure(figsize=(8.5, 11), dpi=100)
|
||||
fig.patch.set_facecolor("white")
|
||||
|
||||
if rd.is_histogram:
|
||||
_render_histogram_layout(fig, rd)
|
||||
else:
|
||||
_render_waveform_layout(fig, rd)
|
||||
|
||||
# Page footer (common to both layouts) — Created date + event id.
|
||||
# Pushed to the very page bottom so it doesn't collide with the
|
||||
# waveform footer scale / trigger legend lines just above.
|
||||
# Convert UTC server_received_at to local for display.
|
||||
created_local = _fmt_iso_to_bw(rd.server_received_at) if rd.server_received_at else "—"
|
||||
fig.text(
|
||||
0.07, 0.005,
|
||||
f"Created: {created_local} • seismo-relay",
|
||||
fontsize=6, color="#888", ha="left",
|
||||
)
|
||||
fig.text(
|
||||
0.93, 0.005,
|
||||
f"Event {rd.event_id[:8] if rd.event_id else '—'}",
|
||||
fontsize=6, color="#888", ha="right",
|
||||
)
|
||||
|
||||
buf = io.BytesIO()
|
||||
fig.savefig(buf, format="pdf")
|
||||
plt.close(fig)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _render_waveform_layout(fig, rd: ReportData) -> None:
|
||||
"""Waveform layout: header / mic+USBM / per-channel stats / waveform plot.
|
||||
|
||||
Stats table includes Time (Rel. to Trig), Peak Accel, Peak Disp.
|
||||
Left margin sized to fit the channel labels (MicL/Long/Vert/Tran).
|
||||
Extra bottom margin reserves space for x-axis tick labels +
|
||||
"Amplitude Geo: X in/s/div Mic: Y psi(L)/div" footer + trigger
|
||||
legend without overlap.
|
||||
"""
|
||||
gs = fig.add_gridspec(
|
||||
nrows=4, ncols=1,
|
||||
left=0.11, right=0.94, top=0.97, bottom=0.12,
|
||||
height_ratios=[1.7, 2.0, 1.8, 5.5],
|
||||
hspace=0.35,
|
||||
)
|
||||
ax_header = fig.add_subplot(gs[0]); ax_header.axis("off")
|
||||
_draw_header_waveform(ax_header, rd)
|
||||
|
||||
ax_mid = fig.add_subplot(gs[1]); ax_mid.axis("off")
|
||||
_draw_mic_and_usbm(ax_mid, rd)
|
||||
|
||||
ax_stats = fig.add_subplot(gs[2]); ax_stats.axis("off")
|
||||
_draw_channel_stats_waveform(ax_stats, rd)
|
||||
|
||||
_draw_waveform_subplot(fig, gs[3], rd)
|
||||
|
||||
|
||||
def _render_histogram_layout(fig, rd: ReportData) -> None:
|
||||
"""Histogram layout: header / mic-only / per-channel stats / bar plot.
|
||||
|
||||
No USBM compliance chart (it's a waveform-only concept). Stats table
|
||||
uses Date + Time-of-peak instead of relative-time + accel + disp.
|
||||
Left margin sized to fit the channel labels. Extra bottom margin
|
||||
leaves room for the x-axis time labels + footer scale legend
|
||||
without overlap.
|
||||
"""
|
||||
gs = fig.add_gridspec(
|
||||
nrows=4, ncols=1,
|
||||
left=0.11, right=0.94, top=0.97, bottom=0.12,
|
||||
height_ratios=[1.8, 0.9, 1.7, 5.6],
|
||||
hspace=0.35,
|
||||
)
|
||||
ax_header = fig.add_subplot(gs[0]); ax_header.axis("off")
|
||||
_draw_header_histogram(ax_header, rd)
|
||||
|
||||
ax_mic = fig.add_subplot(gs[1]); ax_mic.axis("off")
|
||||
_draw_mic_only(ax_mic, rd)
|
||||
|
||||
ax_stats = fig.add_subplot(gs[2]); ax_stats.axis("off")
|
||||
_draw_channel_stats_histogram(ax_stats, rd)
|
||||
|
||||
_draw_histogram_subplot(fig, gs[3], rd)
|
||||
|
||||
|
||||
def _to_display_local(iso: str):
|
||||
"""Parse an ISO timestamp and return a datetime in the system's local
|
||||
timezone (set by the TZ env var, default America/New_York via the
|
||||
Dockerfile).
|
||||
|
||||
Behaviour:
|
||||
- "...Z" or "...+HH:MM" suffix → tz-aware UTC → converted to local
|
||||
- Naïve "YYYY-MM-DDTHH:MM:SS" (no tz) → returned as-is. This
|
||||
matches the convention used elsewhere in seismo-relay: BW's
|
||||
recorded-at timestamps are naïve and ALREADY in the unit's
|
||||
local clock; we don't second-guess them.
|
||||
"""
|
||||
import datetime as _dt
|
||||
dt = _dt.datetime.fromisoformat(iso.replace("Z", "+00:00"))
|
||||
if dt.tzinfo is not None:
|
||||
# Convert from UTC (or other tz) → local per the TZ env var.
|
||||
# astimezone() without arg uses the system timezone.
|
||||
dt = dt.astimezone()
|
||||
return dt
|
||||
|
||||
|
||||
def _fmt_iso_to_bw(iso: Optional[str]) -> Optional[str]:
|
||||
"""Convert an ISO-8601 timestamp to BW's display format
|
||||
'22:30:37 May 16, 2026'. UTC inputs (with Z suffix) are
|
||||
converted to the system's local timezone first; naïve inputs
|
||||
are formatted as-is. Returns input unchanged on parse failure."""
|
||||
if not iso or "T" not in iso:
|
||||
return iso
|
||||
try:
|
||||
return _to_display_local(iso).strftime("%H:%M:%S %B %d, %Y").replace(" 0", " ")
|
||||
except Exception:
|
||||
return iso
|
||||
|
||||
|
||||
def _split_iso_to_date_time(iso: Optional[str]) -> tuple[Optional[str], Optional[str]]:
|
||||
"""Split an ISO timestamp into BW-formatted ('May 27 /26', '06:06:14')
|
||||
date+time strings. Used for the histogram stats table where the
|
||||
Date and Time rows are presented separately. UTC inputs are
|
||||
converted to local time first. Returns (None, None) on parse failure."""
|
||||
if not iso:
|
||||
return (None, None)
|
||||
try:
|
||||
dt = _to_display_local(iso)
|
||||
# BW format: 'May 27 /26' (3-letter month + 2-digit year)
|
||||
date_str = dt.strftime("%b %d /%y").replace(" 0", " ")
|
||||
time_str = dt.strftime("%H:%M:%S")
|
||||
return (date_str, time_str)
|
||||
except Exception:
|
||||
return (None, None)
|
||||
|
||||
|
||||
def _kv(ax, x, y, label, value, *, label_w=0.18):
|
||||
"""Render a 'Label Value' row at axes-coordinates (x, y)."""
|
||||
ax.text(x, y, label, fontsize=8, color="#555", ha="left", va="top",
|
||||
transform=ax.transAxes)
|
||||
ax.text(x + label_w, y, _fmt(value), fontsize=8, ha="left", va="top",
|
||||
transform=ax.transAxes, family="monospace")
|
||||
|
||||
|
||||
def _fmt(v):
|
||||
"""Format any field for display — '—' for None, str otherwise."""
|
||||
if v is None:
|
||||
return "—"
|
||||
if isinstance(v, float):
|
||||
return f"{v:.4f}".rstrip("0").rstrip(".")
|
||||
return str(v)
|
||||
|
||||
|
||||
def _draw_header_waveform(ax, rd: ReportData) -> None:
|
||||
"""Two-column metadata header — waveform variant."""
|
||||
rows_left = [
|
||||
("Date/Time", _fmt_iso_to_bw(rd.event_datetime_str)),
|
||||
("Trigger Source", rd.trigger_source),
|
||||
("Range", rd.geo_range_str),
|
||||
("Sample Rate", rd.sample_rate_str),
|
||||
("Notes", rd.notes),
|
||||
("Project:", rd.project),
|
||||
("Client:", rd.client),
|
||||
("User Name:", rd.operator),
|
||||
("Seis. Loc:", rd.sensor_location),
|
||||
]
|
||||
_draw_header_columns(ax, rows_left, rd)
|
||||
|
||||
|
||||
def _draw_header_histogram(ax, rd: ReportData) -> None:
|
||||
"""Two-column metadata header — histogram variant.
|
||||
|
||||
Histograms have Start / Finish / Intervals fields instead of
|
||||
Trigger Source (there's no trigger event for a histogram capture).
|
||||
"""
|
||||
intervals_str = None
|
||||
if rd.histogram_n_intervals is not None and rd.histogram_interval_size:
|
||||
intervals_str = f"{rd.histogram_n_intervals} At {rd.histogram_interval_size}"
|
||||
rows_left = [
|
||||
("Start", _fmt_iso_to_bw(rd.histogram_start_str or rd.event_datetime_str)),
|
||||
("Finish", _fmt_iso_to_bw(rd.histogram_stop_str)),
|
||||
("Intervals", intervals_str),
|
||||
("Range", rd.geo_range_str),
|
||||
("Sample Rate", (f"{rd.sample_rate_sps} Sps" if rd.sample_rate_sps else None)),
|
||||
("Notes", rd.notes),
|
||||
("Project:", rd.project),
|
||||
("Client:", rd.client),
|
||||
("User Name:", rd.operator),
|
||||
("Seis. Loc:", rd.sensor_location),
|
||||
]
|
||||
_draw_header_columns(ax, rows_left, rd)
|
||||
|
||||
|
||||
def _draw_header_columns(ax, rows_left, rd: ReportData) -> None:
|
||||
"""Shared 2-column header rendering used by both layouts."""
|
||||
rows_right = [
|
||||
("Serial Number", f"{rd.serial or '—'}" + (f" {rd.firmware}" if rd.firmware else "")),
|
||||
("Battery Level", f"{rd.battery_volts:.1f} Volts" if rd.battery_volts is not None else None),
|
||||
("Unit Calibration", (f"{rd.calibration_date}" + (f" by {rd.calibration_by}" if rd.calibration_by else ""))
|
||||
if rd.calibration_date else None),
|
||||
("File Name", rd.file_name),
|
||||
("Post Event Notes", rd.post_event_notes),
|
||||
]
|
||||
y = 0.95
|
||||
dy = 0.095
|
||||
for label, value in rows_left:
|
||||
_kv(ax, 0.0, y, label, value, label_w=0.18)
|
||||
y -= dy
|
||||
y = 0.95
|
||||
for label, value in rows_right:
|
||||
_kv(ax, 0.55, y, label, value, label_w=0.20)
|
||||
y -= dy
|
||||
|
||||
|
||||
def _draw_mic_only(ax, rd: ReportData) -> None:
|
||||
"""Mic block (histogram variant — no USBM chart)."""
|
||||
ax.text(0.0, 0.95, "Microphone Linear Weighting", fontsize=8, color="#555",
|
||||
transform=ax.transAxes, va="top")
|
||||
rows = _mic_rows(rd)
|
||||
y = 0.70
|
||||
for label, value in rows:
|
||||
_kv(ax, 0.0, y, label, value, label_w=0.18)
|
||||
y -= 0.22
|
||||
|
||||
|
||||
def _draw_mic_and_usbm(ax, rd: ReportData) -> None:
|
||||
"""Mic block on the left + USBM compliance chart placeholder on right.
|
||||
(Waveform variant — USBM is a velocity-vs-frequency compliance plot
|
||||
that doesn't apply to histograms.)"""
|
||||
ax.text(0.0, 0.95, "Microphone Linear Weighting", fontsize=8, color="#555",
|
||||
transform=ax.transAxes, va="top")
|
||||
rows = _mic_rows(rd)
|
||||
y = 0.80
|
||||
for label, value in rows:
|
||||
_kv(ax, 0.0, y, label, value, label_w=0.18)
|
||||
y -= 0.15
|
||||
|
||||
# USBM chart placeholder — upper-right. Real piecewise compliance
|
||||
# curves are a separate work item; for now this just shows the title
|
||||
# + a "see report" message so the layout is correct.
|
||||
ax.text(0.72, 0.97, "USBM RI8507 And OSMRE",
|
||||
fontsize=9, weight="bold", color="#333", ha="center", va="top",
|
||||
transform=ax.transAxes)
|
||||
ax.text(0.72, 0.50, "[compliance chart\ncoming soon]",
|
||||
fontsize=8, color="#bbb", ha="center", va="center",
|
||||
transform=ax.transAxes, style="italic")
|
||||
|
||||
|
||||
def _mic_rows(rd: ReportData) -> list[tuple[str, Optional[str]]]:
|
||||
"""Build the mic-section value rows (shared by both layouts).
|
||||
|
||||
For histograms, BW formats the PSPL line as
|
||||
"125.7 dB(L) on May 27, 2026 at 06:19:14"
|
||||
(absolute date+time of peak). Waveform events show the relative
|
||||
"at 0.012 sec." instead. Both formats covered here based on which
|
||||
field is populated.
|
||||
"""
|
||||
rows: list[tuple[str, Optional[str]]] = []
|
||||
if rd.mic_pspl_dbl is not None:
|
||||
line = f"{rd.mic_pspl_dbl:.1f} dB(L)"
|
||||
if rd.mic_pspl_when_str:
|
||||
# Histogram-style: "PSPL 125.7 dB(L) on May 27, 2026 at 06:19:14"
|
||||
# mic_pspl_when_str is already "HH:MM:SS Month DD, YYYY";
|
||||
# reformat to "on Month DD, YYYY at HH:MM:SS" for BW match.
|
||||
parts = rd.mic_pspl_when_str.split(" ", 1)
|
||||
if len(parts) == 2:
|
||||
line += f" on {parts[1]} at {parts[0]}"
|
||||
else:
|
||||
line += f" on {rd.mic_pspl_when_str}"
|
||||
elif rd.mic_pspl_time_s is not None:
|
||||
# Waveform-style: relative-to-trigger seconds.
|
||||
line += f" at {rd.mic_pspl_time_s:.3f} sec."
|
||||
rows.append(("PSPL", line))
|
||||
if rd.mic_zc_freq_hz is not None:
|
||||
prefix = ">" if rd.mic_zc_freq_above_range else ""
|
||||
rows.append(("ZC Freq", f"{prefix}{rd.mic_zc_freq_hz:.0f} Hz"))
|
||||
if rd.mic_channel_test_result:
|
||||
line = rd.mic_channel_test_result
|
||||
if rd.mic_channel_test_freq_hz is not None and rd.mic_channel_test_amp_mv is not None:
|
||||
line += (f" (Freq = {rd.mic_channel_test_freq_hz:.1f} Hz, "
|
||||
f"Amp = {rd.mic_channel_test_amp_mv:.0f} mv)")
|
||||
rows.append(("Channel Test", line))
|
||||
return rows
|
||||
|
||||
|
||||
def _draw_channel_stats_waveform(ax, rd: ReportData) -> None:
|
||||
"""Waveform stats table — has Time (Rel. to Trig), Peak Accel, Peak Disp.
|
||||
Followed by Peak Vector Sum line."""
|
||||
rows_spec = [
|
||||
("PPV", "ppv_ips", "in/s"),
|
||||
("ZC Freq", "zc_freq_hz", "Hz"),
|
||||
("Time (Rel. to Trig)", "time_of_peak_s", "sec"),
|
||||
("Peak Acceleration", "peak_accel_g", "g"),
|
||||
("Peak Displacement", "peak_disp_in", "in"),
|
||||
("Sensor Check", "sensor_check", ""),
|
||||
]
|
||||
_draw_stats_table(ax, rd, rows_spec)
|
||||
_draw_pvs_summary(ax, rd, n_data_rows=len(rows_spec))
|
||||
|
||||
|
||||
def _draw_channel_stats_histogram(ax, rd: ReportData) -> None:
|
||||
"""Histogram stats table — PPV, ZC Freq, Date, Time of peak, Sensor Check.
|
||||
Followed by Peak Vector Sum line."""
|
||||
# Date / Time of peak are per-channel timestamps for the interval at peak.
|
||||
# bw_report stores time_of_peak_s as relative seconds, but for histograms
|
||||
# BW shows them as absolute date+time. We populate from rd.channel_stats
|
||||
# if those absolute fields are present; otherwise fall back to relative.
|
||||
rows_spec = [
|
||||
("PPV", "ppv_ips", "in/s"),
|
||||
("ZC Freq", "zc_freq_hz", "Hz"),
|
||||
("Date", "peak_date", ""),
|
||||
("Time", "peak_time", ""),
|
||||
("Sensor Check", "sensor_check", ""),
|
||||
]
|
||||
_draw_stats_table(ax, rd, rows_spec)
|
||||
_draw_pvs_summary(ax, rd, n_data_rows=len(rows_spec), histogram_when=True)
|
||||
|
||||
|
||||
def _draw_pvs_summary(
|
||||
ax,
|
||||
rd: ReportData,
|
||||
*,
|
||||
n_data_rows: int,
|
||||
histogram_when: bool = False,
|
||||
) -> None:
|
||||
"""Render the Peak Vector Sum + 'NA: Not Applicable' caption below the
|
||||
stats table.
|
||||
|
||||
Reads ``ax._stats_table_bottom`` (set by ``_draw_stats_table`` when
|
||||
it pins the table via an explicit ``bbox``) so the PVS line lands
|
||||
just below the table's known bottom edge instead of guessing at the
|
||||
geometry.
|
||||
|
||||
Centered horizontally for visual balance (the previous left-aligned
|
||||
x=0 landed under the label column, not the data, which looked off).
|
||||
"""
|
||||
if rd.peak_vector_sum_ips is None:
|
||||
return
|
||||
|
||||
line = f"Peak Vector Sum {rd.peak_vector_sum_ips:.3f} in/s"
|
||||
if histogram_when and rd.peak_vector_sum_when_str:
|
||||
# Histogram absolute date+time. when_str is "HH:MM:SS Month DD, YYYY";
|
||||
# reformat to "<value> on <date> At <time>" to match BW.
|
||||
parts = rd.peak_vector_sum_when_str.split(" ", 1)
|
||||
if len(parts) == 2:
|
||||
line += f" on {parts[1]} At {parts[0]}"
|
||||
else:
|
||||
line += f" on {rd.peak_vector_sum_when_str}"
|
||||
elif not histogram_when and rd.peak_vector_sum_time_s is not None:
|
||||
line += f" At {rd.peak_vector_sum_time_s:.3f} sec."
|
||||
|
||||
# _draw_stats_table stashes the bbox bottom on the axes so we don't
|
||||
# have to guess geometry. Falls back to a conservative default if
|
||||
# the bbox approach hasn't run.
|
||||
table_bottom_y = getattr(ax, "_stats_table_bottom", -0.10)
|
||||
pvs_y = table_bottom_y - 0.04 # small gap below the table border
|
||||
|
||||
# Centered for visual balance — looks intentional rather than offset.
|
||||
# The original BW-replica had a "NA: Not Applicable" caption below
|
||||
# this line; dropped because we use "—" for missing values and the
|
||||
# legend was always squished against the PVS line.
|
||||
ax.text(0.5, pvs_y, line, fontsize=9, weight="bold",
|
||||
ha="center", va="top", transform=ax.transAxes)
|
||||
|
||||
|
||||
def _draw_stats_table(ax, rd: ReportData, rows_spec: list[tuple[str, str, str]]) -> None:
|
||||
"""Render a per-channel stats table (Tran/Vert/Long).
|
||||
|
||||
rows_spec: list of (label, field_name_in_channel_stats, unit_string)
|
||||
"""
|
||||
headers = ["", "Tran", "Vert", "Long", ""]
|
||||
ch_lookup = {c["name"]: c for c in rd.channel_stats}
|
||||
|
||||
def _cell(field, ch_name):
|
||||
ch_rec = ch_lookup.get(ch_name, {})
|
||||
val = ch_rec.get(field)
|
||||
if val is None:
|
||||
return "—"
|
||||
if isinstance(val, float):
|
||||
# ZC Freq is integer-formatted in BW; ">100 Hz" sentinel
|
||||
# rendered as ">N" (val carries the threshold). Everything
|
||||
# else gets 3 decimals.
|
||||
if field == "zc_freq_hz":
|
||||
prefix = ">" if ch_rec.get("zc_freq_above_range") else ""
|
||||
return f"{prefix}{val:.0f}"
|
||||
return f"{val:.3f}"
|
||||
return str(val)
|
||||
|
||||
table_data = [headers]
|
||||
for label, field_name, unit in rows_spec:
|
||||
table_data.append([
|
||||
label,
|
||||
_cell(field_name, "Tran"),
|
||||
_cell(field_name, "Vert"),
|
||||
_cell(field_name, "Long"),
|
||||
unit,
|
||||
])
|
||||
# Pin the table's position+size via bbox so we know exactly where
|
||||
# the bottom edge lands. Lets _draw_pvs_summary place the PVS line
|
||||
# just below the table without guessing at row heights.
|
||||
#
|
||||
# bbox = [x, y, width, height] in axes coords. Header + data rows
|
||||
# at row_h each; horizontal extent matches sum(colWidths).
|
||||
n_rows = len(table_data) # header + data rows
|
||||
row_h = 0.12 # axes-fraction per row (fits fontsize=8)
|
||||
table_height = n_rows * row_h
|
||||
table_bottom = 1.0 - table_height
|
||||
tbl = ax.table(
|
||||
cellText=table_data,
|
||||
colWidths=[0.28, 0.14, 0.14, 0.14, 0.10],
|
||||
cellLoc="left", edges="open",
|
||||
bbox=[0.0, table_bottom, 0.80, table_height],
|
||||
)
|
||||
tbl.auto_set_font_size(False)
|
||||
tbl.set_fontsize(8)
|
||||
for j in range(5):
|
||||
tbl[(0, j)].set_text_props(weight="bold", color="#555")
|
||||
# Stash the bottom Y so _draw_pvs_summary can position itself below.
|
||||
ax._stats_table_bottom = table_bottom
|
||||
|
||||
|
||||
def _channel_axis_color(ch: str) -> str:
|
||||
return {"MicL": "#cc00cc", "Long": "#0066ff", "Vert": "#009933", "Tran": "#cc0000"}.get(ch, "#444")
|
||||
|
||||
|
||||
def _draw_waveform_subplot(fig, gridspec_cell, rd: ReportData) -> None:
|
||||
"""4-channel stacked waveform plot — Instantel printout order
|
||||
(MicL on top, Tran on bottom), shared x-axis in SECONDS, trigger
|
||||
triangle markers at t=0, '0.0' baseline label on right of each."""
|
||||
inner = gridspec_cell.subgridspec(4, 1, hspace=0.0)
|
||||
order = ["MicL", "Long", "Vert", "Tran"]
|
||||
sr = rd.sample_rate_sps or 1024
|
||||
# Convert ms-based time axis to seconds for the x-axis
|
||||
dt_s = (rd.dt_ms or (1000.0 / sr)) / 1000.0
|
||||
t0_s = (rd.t0_ms if rd.t0_ms is not None else 0.0) / 1000.0
|
||||
|
||||
last_idx = len(order) - 1
|
||||
for i, ch in enumerate(order):
|
||||
ax = fig.add_subplot(inner[i])
|
||||
values = rd.channels.get(ch) or []
|
||||
times = [t0_s + j * dt_s for j in range(len(values))]
|
||||
|
||||
if values:
|
||||
color = _channel_axis_color(ch)
|
||||
ax.plot(times, values, color=color, linewidth=0.5)
|
||||
# Symmetric y-axis for geo; zero-anchored for mic.
|
||||
if ch != "MicL":
|
||||
amax = max((abs(v) for v in values), default=0.001)
|
||||
ax.set_ylim(-amax * 1.10, amax * 1.10)
|
||||
else:
|
||||
amax = max((abs(v) for v in values), default=0.001)
|
||||
ax.set_ylim(-amax * 1.10, amax * 1.10)
|
||||
|
||||
# Channel label on the LEFT (matches BW)
|
||||
ax.set_ylabel(ch, fontsize=8, rotation=0, ha="right", va="center",
|
||||
color=_channel_axis_color(ch), weight="bold", labelpad=14)
|
||||
# "0.0" on the RIGHT (BW convention)
|
||||
ax.text(1.005, 0.5, "0.0", transform=ax.transAxes,
|
||||
fontsize=7, color="#555", va="center", ha="left")
|
||||
|
||||
ax.grid(True, linestyle="--", linewidth=0.3, color="#bbb", alpha=0.6)
|
||||
# Vertical dashed trigger line at t=0
|
||||
ax.axvline(0.0, color="#cc0000", linestyle="--", linewidth=0.6, alpha=0.7)
|
||||
# Zero baseline horizontal
|
||||
ax.axhline(0.0, color=_channel_axis_color(ch), linestyle="-",
|
||||
linewidth=0.4, alpha=0.5)
|
||||
|
||||
if i != last_idx:
|
||||
ax.set_xticklabels([])
|
||||
ax.tick_params(axis="x", length=0)
|
||||
else:
|
||||
ax.tick_params(axis="x", labelsize=7)
|
||||
ax.tick_params(axis="y", labelsize=6)
|
||||
|
||||
# Trigger triangle marker ▼ above the top channel at t=0
|
||||
top_ax = fig.axes[-4] # MicL is the first added in this gridspec
|
||||
top_ax.plot([0], [top_ax.get_ylim()[1]], marker="v", color="black",
|
||||
markersize=8, clip_on=False, zorder=10)
|
||||
|
||||
# Compute scale-per-division for the footer (10 divs across the chart)
|
||||
# and find peak geo amplitude for the geo amp/div setting.
|
||||
total_s = times[-1] - times[0] if values else 0
|
||||
div_s = total_s / 10 if total_s > 0 else 0
|
||||
geo_amp_div = "—"
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
v = rd.channels.get(ch) or []
|
||||
if v:
|
||||
amax = max(abs(x) for x in v)
|
||||
geo_amp_div = f"{(amax * 1.1 * 2) / 10:.3f}"
|
||||
break
|
||||
fig.text(
|
||||
0.11, 0.030,
|
||||
f"Time(Seconds) {div_s:.2f} sec/div Amplitude Geo: {geo_amp_div} in/s/div Mic: 0.001 psi(L)/div",
|
||||
fontsize=7, color="#444", ha="left",
|
||||
)
|
||||
fig.text(
|
||||
0.11, 0.018,
|
||||
"Trigger = ▶━━━━━ ━━━━━━◀",
|
||||
fontsize=7, color="#444", ha="left",
|
||||
)
|
||||
|
||||
|
||||
def _nice_geo_step(amax: float) -> float:
|
||||
"""Pick a "nice" per-division step for the geo y-axis.
|
||||
|
||||
Geo LSB is 0.005 in/s — sub-LSB steps like 0.003/div are nonsense.
|
||||
Quantize to the BW-style 1-2-5 sequence (0.005, 0.01, 0.025, 0.05,
|
||||
…) and return the smallest step where 5 divisions >= amax, so the
|
||||
top of the chart lands on a tick.
|
||||
"""
|
||||
if amax <= 0:
|
||||
return 0.005
|
||||
for step in (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0):
|
||||
if step * 5 >= amax:
|
||||
return step
|
||||
return 10.0
|
||||
|
||||
|
||||
def _draw_histogram_subplot(fig, gridspec_cell, rd: ReportData) -> None:
|
||||
"""4-channel stacked histogram bar chart — per-interval peaks.
|
||||
|
||||
X-axis labeled with the actual times from rd.histogram_interval_times
|
||||
when available; otherwise interval index.
|
||||
|
||||
The three geo channels share a single y-axis scale (a BW-style nice
|
||||
multiple of the 0.005 in/s LSB) so bar heights are directly
|
||||
comparable across channels. MicL has its own auto-scale.
|
||||
"""
|
||||
inner = gridspec_cell.subgridspec(4, 1, hspace=0.0)
|
||||
order = ["MicL", "Long", "Vert", "Tran"]
|
||||
last_idx = len(order) - 1
|
||||
|
||||
# X-axis: use absolute time labels if we have them, else interval index
|
||||
have_times = bool(rd.histogram_interval_times)
|
||||
|
||||
# Shared geo scale: max across Tran/Vert/Long, quantized to a nice
|
||||
# tick step. Used for ylim + the footer "Amplitude Geo: X in/s/div".
|
||||
geo_amax = 0.0
|
||||
for gch in ("Tran", "Vert", "Long"):
|
||||
gv = rd.channels.get(gch) or []
|
||||
if gv:
|
||||
geo_amax = max(geo_amax, max(abs(x) for x in gv if x is not None))
|
||||
geo_step = _nice_geo_step(geo_amax)
|
||||
geo_top = geo_step * 5 # 5 divisions — top tick lands at this value
|
||||
|
||||
for i, ch in enumerate(order):
|
||||
ax = fig.add_subplot(inner[i])
|
||||
values = rd.channels.get(ch) or []
|
||||
if values:
|
||||
# Histograms record per-interval PEAK magnitudes — always
|
||||
# non-negative. Codec output occasionally includes signed
|
||||
# values when the underlying .h5 was scaled like a waveform;
|
||||
# take the absolute value so the bars rise from zero.
|
||||
abs_vals = [abs(v) if v is not None else 0 for v in values]
|
||||
xs = np.arange(len(abs_vals))
|
||||
color = _channel_axis_color(ch)
|
||||
ax.bar(xs, abs_vals, color=color, width=0.85, linewidth=0)
|
||||
if ch in ("Tran", "Vert", "Long"):
|
||||
ax.set_ylim(0, geo_top)
|
||||
ax.set_yticks([j * geo_step for j in range(6)])
|
||||
else:
|
||||
amax = max(abs_vals, default=0)
|
||||
if amax > 0:
|
||||
ax.set_ylim(0, amax * 1.10)
|
||||
ax.set_ylabel(ch, fontsize=8, rotation=0, ha="right", va="center",
|
||||
color=_channel_axis_color(ch), weight="bold", labelpad=14)
|
||||
ax.text(1.005, 0.02, "0.0", transform=ax.transAxes,
|
||||
fontsize=7, color="#555", va="bottom", ha="left")
|
||||
ax.grid(True, axis="y", linestyle="--", linewidth=0.3, color="#bbb", alpha=0.6)
|
||||
if i != last_idx:
|
||||
ax.set_xticklabels([])
|
||||
ax.tick_params(axis="x", length=0)
|
||||
else:
|
||||
if have_times and len(rd.histogram_interval_times) == len(values):
|
||||
# Show 2-4 labels evenly spaced
|
||||
n = len(values)
|
||||
step = max(1, n // 4)
|
||||
tick_positions = list(range(0, n, step))
|
||||
ax.set_xticks(tick_positions)
|
||||
ax.set_xticklabels([rd.histogram_interval_times[t] for t in tick_positions],
|
||||
rotation=0, fontsize=6)
|
||||
else:
|
||||
ax.set_xlabel("Interval", fontsize=8)
|
||||
ax.tick_params(axis="x", labelsize=7)
|
||||
ax.tick_params(axis="y", labelsize=6)
|
||||
|
||||
# Footer scale info — histograms use minute/div. Reuses the shared
|
||||
# geo_step computed above so the label matches the actual y-axis
|
||||
# tick spacing on every subplot.
|
||||
interval_str = rd.histogram_interval_size or "—"
|
||||
geo_amp_div = f"{geo_step:.3f}"
|
||||
fig.text(
|
||||
0.11, 0.030,
|
||||
f"Time {interval_str} /div Amplitude Geo: {geo_amp_div} in/s/div Mic: 0.001 psi(L)/div",
|
||||
fontsize=7, color="#444", ha="left",
|
||||
)
|
||||
+251
-8
@@ -46,7 +46,7 @@ from typing import Optional
|
||||
|
||||
# FastAPI / Pydantic
|
||||
try:
|
||||
from fastapi import Body, FastAPI, File, HTTPException, Query, UploadFile
|
||||
from fastapi import Body, FastAPI, File, HTTPException, Query, Response, UploadFile
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
@@ -72,6 +72,7 @@ from sfm.cache import SFMCache, get_cache
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.live_cache import LiveCache as _LiveCache
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from sfm import db_snapshot
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -89,7 +90,7 @@ app = FastAPI(
|
||||
"Implements the minimateplus RS-232 protocol library.\n"
|
||||
"Proxied by terra-view at /api/sfm/*."
|
||||
),
|
||||
version="0.17.0",
|
||||
version="0.26.0",
|
||||
)
|
||||
|
||||
# Allow requests from the waveform viewer opened as a local file (file://)
|
||||
@@ -381,10 +382,24 @@ def webapp():
|
||||
|
||||
@app.get("/waveform", response_class=FileResponse)
|
||||
def waveform_viewer():
|
||||
"""Serve the standalone waveform viewer."""
|
||||
"""Serve the standalone LIVE-device waveform viewer.
|
||||
|
||||
Talks to ``/device/*`` endpoints — for plotting events pulled from
|
||||
a connected unit in real time. For the stored-event browser that
|
||||
reads from the SeismoDb + WaveformStore, see ``/events``.
|
||||
"""
|
||||
return str(Path(__file__).parent / "waveform_viewer.html")
|
||||
|
||||
|
||||
@app.get("/events", response_class=FileResponse)
|
||||
def event_browser():
|
||||
"""Serve the stored-event browser — pick a serial, list its events,
|
||||
render any one's waveform from the persisted ``.h5`` via the
|
||||
``/db/events/{id}/waveform.json`` endpoint. Standalone HTML +
|
||||
Chart.js, no auth, no build step."""
|
||||
return str(Path(__file__).parent / "event_browser.html")
|
||||
|
||||
|
||||
@app.get("/device/info")
|
||||
def device_info(
|
||||
port: Optional[str] = Query(None, description="Serial port (e.g. COM5, /dev/ttyUSB0)"),
|
||||
@@ -1942,7 +1957,10 @@ def db_set_false_trigger(
|
||||
value: bool = Query(..., description="True to flag as false trigger, False to clear"),
|
||||
) -> dict:
|
||||
"""
|
||||
Set or clear the false_trigger flag on a single event.
|
||||
Set or clear the false_trigger flag on a single event. Enforces the
|
||||
same 3-state exclusivity as the sidecar review PATCH (flagging false_trigger
|
||||
clears reviewed_real) and propagates the resulting flags to the event's
|
||||
histogram/waveform twin(s), same as the sidecar path.
|
||||
|
||||
Used by the terra-view event review UI.
|
||||
Returns 404 if the event_id is not found.
|
||||
@@ -1950,6 +1968,12 @@ def db_set_false_trigger(
|
||||
found = _get_db().set_false_trigger(event_id, value)
|
||||
if not found:
|
||||
raise HTTPException(status_code=404, detail=f"Event {event_id} not found")
|
||||
|
||||
try:
|
||||
_get_db().propagate_review_to_twins(event_id)
|
||||
except Exception as exc:
|
||||
log.warning("twin review-propagation failed for %s: %s", event_id, exc)
|
||||
|
||||
return {"status": "ok", "event_id": event_id, "false_trigger": value}
|
||||
|
||||
|
||||
@@ -1973,10 +1997,15 @@ def _cleanup_event_files(row: dict) -> dict:
|
||||
base_name = bw_name or a5_name or sc_name
|
||||
if base_name:
|
||||
bw_path, a5_path = store.paths_for(serial, base_name)
|
||||
sc_path = store.sidecar_path_for(serial, base_name)
|
||||
h5_path = store.hdf5_path_for(serial, base_name)
|
||||
sc_path = store.sidecar_path_for(serial, base_name)
|
||||
h5_path = store.hdf5_path_for(serial, base_name)
|
||||
# Preserved BW ASCII report (added 2026-05-27 with the .TXT
|
||||
# preservation feature) — needs to be cleaned up too, otherwise
|
||||
# deletes leave orphan _ASCII.TXT files behind.
|
||||
txt_path = store.txt_path_for(serial, base_name)
|
||||
for kind, p in [("blastware", bw_path), ("a5_pickle", a5_path),
|
||||
("sidecar", sc_path), ("hdf5", h5_path)]:
|
||||
("sidecar", sc_path), ("hdf5", h5_path),
|
||||
("txt", txt_path)]:
|
||||
try:
|
||||
if p.exists():
|
||||
p.unlink()
|
||||
@@ -2164,6 +2193,148 @@ def db_event_blastware_file(event_id: str) -> FileResponse:
|
||||
)
|
||||
|
||||
|
||||
@app.get("/db/events/{event_id}/ascii_report.txt")
|
||||
def db_event_ascii_report_txt(event_id: str):
|
||||
"""Serve the raw BW ASCII report (.TXT) for an event, when preserved.
|
||||
|
||||
Returns 404 for events ingested before the .TXT-preservation feature
|
||||
landed (2026-05-27) — those events have only the parsed ``bw_report``
|
||||
block in the sidecar, not the raw .TXT. Re-forwarding from the
|
||||
watcher PC will populate the .TXT going forward.
|
||||
"""
|
||||
row = _get_db().get_event(event_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail=f"Event {event_id} not found")
|
||||
serial = row.get("serial")
|
||||
filename = row.get("blastware_filename")
|
||||
if not serial or not filename:
|
||||
raise HTTPException(status_code=404, detail="Event has no associated BW file")
|
||||
txt_path = _get_store().open_txt(serial, filename)
|
||||
if txt_path is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=(
|
||||
f"Raw .TXT not preserved for {filename}. Events ingested "
|
||||
"before 2026-05-27 don't have it; re-forward from the "
|
||||
"watcher PC to populate."
|
||||
),
|
||||
)
|
||||
return FileResponse(
|
||||
path=str(txt_path),
|
||||
media_type="text/plain",
|
||||
filename=txt_path.name,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/db/events/{event_id}/report.pdf")
|
||||
def db_event_report_pdf(event_id: str):
|
||||
"""Render an Instantel-style Event Report as a PDF.
|
||||
|
||||
Single-page letter portrait, matches the BW Event Report's data
|
||||
coverage and layout (header / mic block / per-channel stats /
|
||||
waveform plot). V0.20.0 stub — exact visual being iterated
|
||||
against reference PDFs in ``docs/reference/instantel/``.
|
||||
|
||||
Returns 404 if the event is unknown or has no waveform data on
|
||||
disk (same condition as /waveform.json).
|
||||
"""
|
||||
from sfm import report_pdf
|
||||
rd = report_pdf.gather_report_data(_get_db(), _get_store(), event_id)
|
||||
if rd is None:
|
||||
raise HTTPException(status_code=404, detail=f"Event {event_id} not found or has no waveform")
|
||||
pdf_bytes = report_pdf.render_event_report_pdf(rd)
|
||||
# Suggested download filename based on the BW file basename.
|
||||
fname = (rd.file_name or event_id).replace(".", "_")
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={"Content-Disposition": f'inline; filename="{fname}_report.pdf"'},
|
||||
)
|
||||
|
||||
|
||||
def _maybe_aggregate_histogram(plot: dict, store, serial: str, filename: str, row: dict) -> dict:
|
||||
"""For histogram events, aggregate the codec's per-block samples into
|
||||
the BW-reported number of intervals. No-op for waveforms or when
|
||||
we don't have the histogram metadata (interval count + size) in the
|
||||
sidecar's bw_report block.
|
||||
|
||||
Why: the histogram codec emits one value per internal block (~1 per
|
||||
second), but BW's printout shows one bar per configured interval
|
||||
(typically 1-15 minutes). For a 1-minute-interval event the codec
|
||||
gives ~60 blocks per BW bar. Aggregating max-per-group makes the
|
||||
SFM chart + PDF visually match BW's display.
|
||||
"""
|
||||
record_type = row.get("record_type") or ""
|
||||
if not record_type.lower().startswith("hist"):
|
||||
return plot
|
||||
|
||||
# Read interval count + size from the sidecar's bw_report.histogram block
|
||||
try:
|
||||
import json as _json
|
||||
sidecar_path = store.sidecar_path_for(serial, filename)
|
||||
if not sidecar_path.exists():
|
||||
return plot
|
||||
sc = _json.loads(sidecar_path.read_text())
|
||||
hist = (sc.get("bw_report") or {}).get("histogram") or {}
|
||||
n_intervals = hist.get("n_intervals")
|
||||
interval_size_s = hist.get("interval_size_s")
|
||||
start_iso = hist.get("start")
|
||||
except Exception:
|
||||
return plot
|
||||
if not n_intervals or n_intervals < 1:
|
||||
return plot
|
||||
|
||||
# Aggregate each channel's values into n_intervals groups, max-per-group
|
||||
channels = plot.get("channels") or {}
|
||||
aggregated_channels: dict = {}
|
||||
for ch, chd in channels.items():
|
||||
vals = chd.get("values") or []
|
||||
if not vals:
|
||||
aggregated_channels[ch] = chd
|
||||
continue
|
||||
# Distribute len(vals) samples across n_intervals groups; uneven
|
||||
# remainders get distributed across the first few groups.
|
||||
per_group = len(vals) // n_intervals
|
||||
remainder = len(vals) % n_intervals
|
||||
agg: list = []
|
||||
offset = 0
|
||||
for i in range(n_intervals):
|
||||
grp_size = per_group + (1 if i < remainder else 0)
|
||||
if grp_size > 0:
|
||||
grp = vals[offset:offset + grp_size]
|
||||
# Max of absolute values (peaks are magnitudes).
|
||||
agg.append(max((abs(v) for v in grp if v is not None), default=0))
|
||||
offset += grp_size
|
||||
else:
|
||||
agg.append(0)
|
||||
aggregated_channels[ch] = {**chd, "values": agg}
|
||||
|
||||
# Build per-interval timestamp labels for the x-axis if we have start time
|
||||
interval_times: list = []
|
||||
if start_iso and interval_size_s:
|
||||
try:
|
||||
import datetime as _dt
|
||||
start = _dt.datetime.fromisoformat(start_iso)
|
||||
for i in range(int(n_intervals)):
|
||||
# Show the END of each interval (BW convention — the
|
||||
# peak reported is for samples taken THROUGH that time)
|
||||
end = start + _dt.timedelta(seconds=(i + 1) * interval_size_s)
|
||||
interval_times.append(end.strftime("%H:%M:%S"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Override the time_axis to reflect intervals (not samples).
|
||||
plot_aggr = {**plot, "channels": aggregated_channels}
|
||||
plot_aggr["time_axis"] = {
|
||||
**(plot.get("time_axis") or {}),
|
||||
"histogram_aggregated": True,
|
||||
"n_intervals": int(n_intervals),
|
||||
"interval_size_s": interval_size_s,
|
||||
"interval_times": interval_times,
|
||||
}
|
||||
return plot_aggr
|
||||
|
||||
|
||||
@app.get("/db/events/{event_id}/waveform.json")
|
||||
def db_event_waveform_json(event_id: str) -> dict:
|
||||
"""
|
||||
@@ -2195,7 +2366,8 @@ def db_event_waveform_json(event_id: str) -> dict:
|
||||
h5_path = store.hdf5_path_for(serial, filename)
|
||||
if h5_path.exists():
|
||||
try:
|
||||
return event_hdf5.plot_json_from_hdf5(h5_path, event_id=event_id)
|
||||
plot = event_hdf5.plot_json_from_hdf5(h5_path, event_id=event_id)
|
||||
return _maybe_aggregate_histogram(plot, store, serial, filename, row)
|
||||
except Exception as exc:
|
||||
log.warning("HDF5 read failed (%s); falling back to A5 path", exc)
|
||||
|
||||
@@ -2318,6 +2490,13 @@ def db_event_sidecar_patch(event_id: str, body: SidecarPatchBody) -> dict:
|
||||
if body.review is not None:
|
||||
_get_db().update_event_review(event_id, new_sidecar.get("review", {}))
|
||||
|
||||
# Propagate the review to the event's histogram/waveform twin(s) so
|
||||
# flagging one flags both (column-level; twins share serial+PVS+near time).
|
||||
try:
|
||||
_get_db().propagate_review_to_twins(event_id)
|
||||
except Exception as exc:
|
||||
log.warning("twin review-propagation failed for %s: %s", event_id, exc)
|
||||
|
||||
return new_sidecar
|
||||
|
||||
|
||||
@@ -2646,6 +2825,70 @@ def db_unit_waveforms_zip(
|
||||
return StreamingResponse(buf, media_type="application/zip", headers=headers)
|
||||
|
||||
|
||||
# ── Full-snapshot bundle endpoints (see sfm/db_snapshot.py) ───────────────────
|
||||
# SFM_DB_RESTORE_ENABLED gates /db/restore (dormant → 404). Set true on dev only.
|
||||
@app.get("/db/snapshot")
|
||||
def db_snapshot_download() -> FileResponse:
|
||||
"""WAL-safe copy of seismo_relay.db, for the terra-view full-snapshot bundle."""
|
||||
import os
|
||||
import tempfile
|
||||
from starlette.background import BackgroundTask
|
||||
fd, tmp = tempfile.mkstemp(suffix=".db")
|
||||
os.close(fd)
|
||||
db_snapshot.snapshot_db(_get_db().db_path, Path(tmp))
|
||||
return FileResponse(
|
||||
tmp, media_type="application/x-sqlite3", filename="seismo_relay.db",
|
||||
background=BackgroundTask(os.unlink, tmp),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/db/waveforms/recent.zip")
|
||||
def db_waveforms_recent_zip(n: int = Query(200, ge=1, le=2000)) -> FileResponse:
|
||||
"""Zip of the n most-recent events' waveform + sidecar files."""
|
||||
import os
|
||||
import tempfile
|
||||
from starlette.background import BackgroundTask
|
||||
fd, tmp = tempfile.mkstemp(suffix=".zip")
|
||||
os.close(fd)
|
||||
stats = db_snapshot.build_recent_waveforms_zip(_get_db(), _get_store(), n, Path(tmp))
|
||||
return FileResponse(
|
||||
tmp, media_type="application/zip", filename="waveforms.zip",
|
||||
headers={"X-Event-Count": str(stats["events"]), "X-File-Count": str(stats["files"])},
|
||||
background=BackgroundTask(os.unlink, tmp),
|
||||
)
|
||||
|
||||
|
||||
@app.post("/db/restore")
|
||||
def db_restore(
|
||||
db: UploadFile = File(...),
|
||||
waveforms: Optional[UploadFile] = File(None),
|
||||
) -> dict:
|
||||
"""Destructive: swap seismo_relay.db + unpack waveforms. Dormant (404) unless
|
||||
SFM_DB_RESTORE_ENABLED is set."""
|
||||
import os
|
||||
import shutil as _shutil
|
||||
import tempfile
|
||||
if not db_snapshot.sfm_db_restore_enabled():
|
||||
raise HTTPException(status_code=404, detail="Not found")
|
||||
|
||||
def _save(upload) -> Path:
|
||||
fd, tmp = tempfile.mkstemp()
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
_shutil.copyfileobj(upload.file, out)
|
||||
return Path(tmp)
|
||||
|
||||
db_tmp = _save(db)
|
||||
wf_tmp = _save(waveforms) if waveforms is not None else None
|
||||
try:
|
||||
return db_snapshot.restore_db_and_waveforms(
|
||||
_get_db().db_path, _get_store().root, db_tmp, wf_tmp,
|
||||
)
|
||||
finally:
|
||||
db_tmp.unlink(missing_ok=True)
|
||||
if wf_tmp is not None:
|
||||
wf_tmp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
@app.get("/db/monitor_log")
|
||||
def db_monitor_log(
|
||||
serial: Optional[str] = Query(None, description="Filter by unit serial"),
|
||||
|
||||
+557
-39
@@ -499,6 +499,20 @@
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--border);
|
||||
white-space: nowrap;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
}
|
||||
table.db-table thead th[data-sort]:hover {
|
||||
background: var(--border2);
|
||||
color: var(--text);
|
||||
}
|
||||
table.db-table thead th .sort-arrow {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
color: var(--accent, #58a6ff);
|
||||
font-weight: 900;
|
||||
text-align: center;
|
||||
}
|
||||
table.db-table tbody tr { border-bottom: 1px solid var(--border2); }
|
||||
table.db-table tbody tr:last-child { border-bottom: none; }
|
||||
@@ -758,7 +772,9 @@
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
}
|
||||
#section-db { display: none; }
|
||||
/* Default to Database view on page load — most users are here to
|
||||
browse stored events, not connect to a live unit. */
|
||||
#section-live { display: none; }
|
||||
|
||||
/* ── Live connect bar (host/port/connect, live section only) ── */
|
||||
#live-connect-bar {
|
||||
@@ -792,8 +808,8 @@
|
||||
</div>
|
||||
<div class="hdr-sep"></div>
|
||||
<div class="section-switcher">
|
||||
<button class="section-btn active" onclick="switchSection('live')">Live Device</button>
|
||||
<button class="section-btn" onclick="switchSection('db')">Database</button>
|
||||
<button class="section-btn" onclick="switchSection('live')">Live Device</button>
|
||||
<button class="section-btn active" onclick="switchSection('db')">Database</button>
|
||||
</div>
|
||||
<div class="hdr-sep"></div>
|
||||
<label class="force-toggle" id="force-toggle"
|
||||
@@ -802,6 +818,12 @@
|
||||
<span class="ft-dot"></span>
|
||||
<span>Force refresh</span>
|
||||
</label>
|
||||
<div class="hdr-sep"></div>
|
||||
<button id="mic-unit-toggle" class="section-btn"
|
||||
onclick="_setMicUnit(_getMicUnit() === 'dBL' ? 'psi' : 'dBL')"
|
||||
title="Toggle microphone display unit (dBL ↔ psi) for waveform plots. Affects all mic charts; persists across page loads.">
|
||||
Mic: dBL
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<!-- ════════════════════════════════════════════════════════════════
|
||||
@@ -1224,18 +1246,18 @@
|
||||
<div class="db-table-wrap" id="hist-table-wrap" style="display:none">
|
||||
<table class="db-table" id="hist-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Timestamp</th>
|
||||
<th>Serial</th>
|
||||
<th>Tran (in/s)</th>
|
||||
<th>Vert (in/s)</th>
|
||||
<th>Long (in/s)</th>
|
||||
<th>PVS (in/s)</th>
|
||||
<th>Mic (dBL)</th>
|
||||
<th>Project</th>
|
||||
<th>Client</th>
|
||||
<th>Type</th>
|
||||
<th>Key</th>
|
||||
<tr id="hist-header-row">
|
||||
<th data-sort="timestamp">Timestamp <span class="sort-arrow"></span></th>
|
||||
<th data-sort="serial">Serial <span class="sort-arrow"></span></th>
|
||||
<th data-sort="tran_ppv">Tran (in/s) <span class="sort-arrow"></span></th>
|
||||
<th data-sort="vert_ppv">Vert (in/s) <span class="sort-arrow"></span></th>
|
||||
<th data-sort="long_ppv">Long (in/s) <span class="sort-arrow"></span></th>
|
||||
<th data-sort="peak_vector_sum">PVS (in/s) <span class="sort-arrow"></span></th>
|
||||
<th data-sort="mic_ppv">Mic (dBL) <span class="sort-arrow"></span></th>
|
||||
<th data-sort="project">Project <span class="sort-arrow"></span></th>
|
||||
<th data-sort="client">Client <span class="sort-arrow"></span></th>
|
||||
<th data-sort="record_type">Type <span class="sort-arrow"></span></th>
|
||||
<th data-sort="waveform_key">Key <span class="sort-arrow"></span></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -1388,7 +1410,9 @@ function deviceParams() {
|
||||
}
|
||||
|
||||
// ── Section switching ─────────────────────────────────────────────────────────
|
||||
let currentSection = 'live';
|
||||
// Default to Database — most users land here to browse stored events.
|
||||
// Live Device is opt-in (click the tab to talk to a unit).
|
||||
let currentSection = 'db';
|
||||
|
||||
function switchSection(name) {
|
||||
currentSection = name;
|
||||
@@ -2333,6 +2357,12 @@ async function _fetchUnits() {
|
||||
}
|
||||
|
||||
// ── History tab ────────────────────────────────────────────────────────────────
|
||||
// Module-level state for the history table — preserved across re-sorts.
|
||||
// We sort + re-render without re-fetching.
|
||||
let _histEvents = [];
|
||||
let _histSortKey = 'timestamp';
|
||||
let _histSortDir = 'desc'; // 'asc' | 'desc'
|
||||
|
||||
async function loadHistory() {
|
||||
histLoaded = true;
|
||||
const serial = document.getElementById('hist-serial-filter').value;
|
||||
@@ -2364,10 +2394,20 @@ async function loadHistory() {
|
||||
_populateSerialDropdown('monlog-serial-filter');
|
||||
_populateSerialDropdown('sess-serial-filter');
|
||||
|
||||
document.getElementById('hist-count').textContent = `${events.length} event${events.length !== 1 ? 's' : ''}`;
|
||||
_histEvents = events;
|
||||
renderHistTable();
|
||||
}
|
||||
|
||||
// Re-render the history table from `_histEvents` using the current sort
|
||||
// state. Pulled out of `loadHistory` so column-header clicks can re-sort
|
||||
// in-memory without re-fetching from the server.
|
||||
function renderHistTable() {
|
||||
const events = _histEvents;
|
||||
document.getElementById('hist-count').textContent =
|
||||
`${events.length} event${events.length !== 1 ? 's' : ''}`;
|
||||
|
||||
const tbody = document.getElementById('hist-tbody');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
if (events.length === 0) {
|
||||
document.getElementById('hist-empty').style.display = 'block';
|
||||
document.getElementById('hist-table-wrap').style.display = 'none';
|
||||
@@ -2376,11 +2416,31 @@ async function loadHistory() {
|
||||
document.getElementById('hist-empty').style.display = 'none';
|
||||
document.getElementById('hist-table-wrap').style.display = 'block';
|
||||
|
||||
for (const ev of events) {
|
||||
// Sort in-place by current key + direction. Nulls sink to the bottom
|
||||
// regardless of direction.
|
||||
const k = _histSortKey;
|
||||
const dir = _histSortDir === 'asc' ? 1 : -1;
|
||||
const sorted = [...events].sort((a, b) => {
|
||||
const av = a[k], bv = b[k];
|
||||
if (av == null && bv == null) return 0;
|
||||
if (av == null) return 1;
|
||||
if (bv == null) return -1;
|
||||
if (typeof av === 'number' && typeof bv === 'number') return (av - bv) * dir;
|
||||
return String(av).localeCompare(String(bv)) * dir;
|
||||
});
|
||||
|
||||
// Update arrow indicators in the headers
|
||||
document.querySelectorAll('#hist-header-row th[data-sort]').forEach(th => {
|
||||
const arrow = th.querySelector('.sort-arrow');
|
||||
if (!arrow) return;
|
||||
arrow.textContent = th.dataset.sort === k ? (_histSortDir === 'asc' ? '↑' : '↓') : '';
|
||||
});
|
||||
|
||||
for (const ev of sorted) {
|
||||
const tr = document.createElement('tr');
|
||||
const pvs = ev.peak_vector_sum;
|
||||
tr.classList.add('clickable');
|
||||
tr.title = 'Click to review (open sidecar editor)';
|
||||
tr.title = 'Click to view waveform + sidecar';
|
||||
tr.dataset.eventId = ev.id;
|
||||
tr.innerHTML = `
|
||||
<td>${_fmtTs(ev.timestamp)}</td>
|
||||
@@ -2408,6 +2468,28 @@ async function loadHistory() {
|
||||
}
|
||||
}
|
||||
|
||||
// Click a column header → toggle sort. Click another → set sort to that column.
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const headerRow = document.getElementById('hist-header-row');
|
||||
if (!headerRow) return;
|
||||
headerRow.querySelectorAll('th[data-sort]').forEach(th => {
|
||||
th.style.cursor = 'pointer';
|
||||
th.style.userSelect = 'none';
|
||||
th.addEventListener('click', () => {
|
||||
const k = th.dataset.sort;
|
||||
if (_histSortKey === k) {
|
||||
_histSortDir = _histSortDir === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
_histSortKey = k;
|
||||
// Default direction: 'desc' for numbers + timestamps (biggest/newest first),
|
||||
// 'asc' for text columns (alphabetical).
|
||||
_histSortDir = ['serial','project','client','record_type','waveform_key'].includes(k) ? 'asc' : 'desc';
|
||||
}
|
||||
renderHistTable();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── Sidecar review modal ───────────────────────────────────────────────────────
|
||||
//
|
||||
// Opens on row click in the History table. Loads the .sfm.json sidecar
|
||||
@@ -2430,23 +2512,373 @@ async function openSidecarModal(eventId) {
|
||||
document.getElementById('sc-edit-ft').checked = false;
|
||||
document.getElementById('sc-edit-reviewer').value = '';
|
||||
document.getElementById('sc-edit-notes').value = '';
|
||||
// Reset waveform area
|
||||
document.getElementById('sc-waveform-status').textContent = 'Loading waveform…';
|
||||
document.getElementById('sc-waveform-charts').innerHTML = '';
|
||||
_destroyScCharts();
|
||||
|
||||
try {
|
||||
const r = await fetch(`${api()}/db/events/${eventId}/sidecar`);
|
||||
if (!r.ok) {
|
||||
const e = await r.json().catch(() => ({}));
|
||||
throw new Error(e.detail || r.statusText);
|
||||
}
|
||||
const data = await r.json();
|
||||
// Sidecar + waveform fetched in parallel — neither blocks the other.
|
||||
const sidecarP = fetch(`${api()}/db/events/${eventId}/sidecar`)
|
||||
.then(async r => {
|
||||
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); }
|
||||
return r.json();
|
||||
});
|
||||
const waveformP = fetch(`${api()}/db/events/${eventId}/waveform.json`)
|
||||
.then(async r => {
|
||||
if (r.status === 404) return null; // no waveform available — render empty state
|
||||
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); }
|
||||
return r.json();
|
||||
});
|
||||
|
||||
// Sidecar usually loads first (smaller payload). Each one renders
|
||||
// independently so the modal becomes useful as soon as either lands.
|
||||
sidecarP.then(data => {
|
||||
_scCurrentSidecar = data;
|
||||
_renderSidecar(data);
|
||||
document.getElementById('sc-status').textContent = '';
|
||||
} catch (e) {
|
||||
}).catch(e => {
|
||||
document.getElementById('sc-status').className = 'sc-status error';
|
||||
document.getElementById('sc-status').textContent = `Load failed: ${e.message}`;
|
||||
document.getElementById('sc-status').textContent = `Sidecar load failed: ${e.message}`;
|
||||
});
|
||||
|
||||
waveformP.then(data => {
|
||||
if (!data) {
|
||||
document.getElementById('sc-waveform-status').textContent = 'No waveform data for this event.';
|
||||
return;
|
||||
}
|
||||
_renderScWaveform(data);
|
||||
}).catch(e => {
|
||||
document.getElementById('sc-waveform-status').textContent = `Waveform load failed: ${e.message}`;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Sidecar-modal waveform plot ──────────────────────────────────────────────
|
||||
// Renders the 4-channel decoded waveform fetched from
|
||||
// /db/events/{id}/waveform.json — MicL on top, Tran on bottom (matches
|
||||
// Instantel BW Event Report layout). Uses Chart.js (loaded at the top of
|
||||
// the page for the live-device viewer).
|
||||
const _SC_CHANNEL_COLORS = {
|
||||
MicL: '#e066ff',
|
||||
Long: '#3a80ff',
|
||||
Vert: '#3fb950',
|
||||
Tran: '#f85149',
|
||||
};
|
||||
const _SC_CHANNEL_ORDER = ['MicL', 'Long', 'Vert', 'Tran'];
|
||||
let _scCharts = {};
|
||||
|
||||
// User preference for how mic is displayed in plots — dBL (default,
|
||||
// matches BW printout convention + the rest of SFM) or psi (the raw
|
||||
// sample unit). Toggleable via the header pill; persists in localStorage.
|
||||
function _getMicUnit() {
|
||||
return localStorage.getItem('sfm_mic_unit') === 'psi' ? 'psi' : 'dBL';
|
||||
}
|
||||
function _setMicUnit(u) {
|
||||
localStorage.setItem('sfm_mic_unit', u === 'psi' ? 'psi' : 'dBL');
|
||||
_refreshMicUnitToggleLabel();
|
||||
// Re-render the open modal so the change is immediately visible.
|
||||
if (_scCurrentEventId) openSidecarModal(_scCurrentEventId);
|
||||
}
|
||||
function _refreshMicUnitToggleLabel() {
|
||||
const b = document.getElementById('mic-unit-toggle');
|
||||
if (b) b.textContent = `Mic: ${_getMicUnit()}`;
|
||||
}
|
||||
// Convert a psi value to dB(L). Returns null for non-positive values
|
||||
// (log of zero is undefined) — Chart.js handles null as a gap in the line.
|
||||
function _psiToDbl(psi) {
|
||||
if (psi == null || !(psi > 0)) return null;
|
||||
return 20 * Math.log10(psi / DBL_REF);
|
||||
}
|
||||
|
||||
// Per-sample mic display floor. Sound pressure AC samples spend most
|
||||
// of their time at the digitization noise floor (1-2 ADC counts ≈ ~20-40
|
||||
// dBL). Rendering each one as null/-inf produces a spikey discontinuous
|
||||
// chart of "moments when sound briefly exceeded 80 dBL" — confusing.
|
||||
// Instead we rectify (abs the AC waveform), convert to dBL, and floor
|
||||
// anything below MIC_DBL_FLOOR so the chart has a continuous baseline
|
||||
// with peaks rising above it. Matches how acoustic engineers expect to
|
||||
// see SPL-vs-time.
|
||||
const MIC_DBL_FLOOR = 60;
|
||||
function _psiToDblForChart(psi) {
|
||||
if (psi == null) return MIC_DBL_FLOOR;
|
||||
const a = Math.abs(psi);
|
||||
if (a === 0) return MIC_DBL_FLOOR;
|
||||
const dbl = 20 * Math.log10(a / DBL_REF);
|
||||
return dbl > MIC_DBL_FLOOR ? dbl : MIC_DBL_FLOOR;
|
||||
}
|
||||
|
||||
// Adaptive decimal formatter — scientific notation is reserved for truly
|
||||
// extreme values (10000+ or sub-0.0001). Normal-range values (most peaks
|
||||
// fall here) render as decimals with sensible precision. Replaces the
|
||||
// previous .toExponential(3) call that turned every peak into ugly "2.500E-2".
|
||||
function _fmtPeak(v, unit) {
|
||||
if (v == null || (typeof v === 'number' && !isFinite(v))) return '';
|
||||
if (typeof v !== 'number') return String(v) + (unit ? ' ' + unit : '');
|
||||
if (v === 0) return '0' + (unit ? ' ' + unit : '');
|
||||
const a = Math.abs(v);
|
||||
const u = unit ? ' ' + unit : '';
|
||||
if (a >= 0.0001 && a < 10000) {
|
||||
const d = a >= 100 ? 1 : a >= 10 ? 2 : a >= 1 ? 3 : a >= 0.1 ? 4 : 5;
|
||||
return v.toFixed(d) + u;
|
||||
}
|
||||
return v.toExponential(2) + u;
|
||||
}
|
||||
|
||||
function _destroyScCharts() {
|
||||
Object.values(_scCharts).forEach(c => { try { c.destroy(); } catch {} });
|
||||
_scCharts = {};
|
||||
}
|
||||
|
||||
function _renderScWaveform(data) {
|
||||
document.getElementById('sc-waveform-status').textContent = '';
|
||||
const chartsDiv = document.getElementById('sc-waveform-charts');
|
||||
chartsDiv.innerHTML = '';
|
||||
_destroyScCharts();
|
||||
|
||||
const channels = data.channels || {};
|
||||
// time_axis is METADATA, not an array — it carries sample_rate,
|
||||
// pretrig_samples, t0_ms (first-sample time relative to trigger,
|
||||
// negative when pretrig samples exist), and dt_ms. Trigger is at
|
||||
// t=0 by convention.
|
||||
const ta = data.time_axis || {};
|
||||
const sr = ta.sample_rate || 1024;
|
||||
const dtMs = ta.dt_ms || (1000.0 / sr);
|
||||
const t0Ms = ta.t0_ms != null ? ta.t0_ms : 0;
|
||||
// Histogram events have per-interval peaks, not per-sample data.
|
||||
// Render as bars (one per interval) instead of a connected line, and
|
||||
// suppress trigger/zero overlays which don't apply. X-axis becomes
|
||||
// interval index since the sample_rate-based time math is meaningless
|
||||
// here (each "sample" is one interval, typically 1-5 minutes long).
|
||||
const isHistogram = String(data.record_type || '').toLowerCase().includes('histogram');
|
||||
|
||||
// Which channels have data — determines which one renders the shared bottom axis.
|
||||
const withData = _SC_CHANNEL_ORDER.filter(ch =>
|
||||
channels[ch] && (channels[ch].values || []).length > 0
|
||||
);
|
||||
const lastCh = withData[withData.length - 1];
|
||||
|
||||
const micUnit = _getMicUnit(); // user preference: 'dBL' or 'psi'
|
||||
|
||||
for (const ch of _SC_CHANNEL_ORDER) {
|
||||
const chData = channels[ch];
|
||||
if (!chData) continue;
|
||||
let values = chData.values || [];
|
||||
let chUnit = chData.unit || '';
|
||||
let chPeak = chData.peak;
|
||||
|
||||
// Mic channel: convert from raw psi to dB(L) when user prefers dBL
|
||||
// (default). Per-sample values use _psiToDblForChart which rectifies
|
||||
// (abs) the AC waveform and floors at MIC_DBL_FLOOR so the chart is
|
||||
// continuous with a baseline + peaks above it, instead of a sparse
|
||||
// pattern of isolated spikes for "moments when sound briefly exceeded
|
||||
// the Y-axis bottom". The peak label uses _psiToDbl with the
|
||||
// unrectified peak (preserves the true measurement).
|
||||
if (ch === 'MicL' && chUnit === 'psi' && micUnit === 'dBL') {
|
||||
values = values.map(_psiToDblForChart);
|
||||
chPeak = _psiToDbl(chPeak);
|
||||
chUnit = 'dB(L)';
|
||||
}
|
||||
|
||||
const wrap = document.createElement('div');
|
||||
wrap.style.cssText = 'background:var(--surface);border:1px solid var(--border2);border-radius:6px;padding:6px 30px 4px 10px';
|
||||
const lbl = document.createElement('div');
|
||||
lbl.style.cssText = `font-size:10px;font-weight:600;letter-spacing:0.05em;text-transform:uppercase;margin-bottom:2px;color:${_SC_CHANNEL_COLORS[ch]};display:flex;justify-content:space-between`;
|
||||
const peakStr = chPeak != null
|
||||
? `peak ${_fmtPeak(chPeak, chUnit)}`
|
||||
: '';
|
||||
lbl.innerHTML = `<span>${ch}</span><span style="color:var(--text-dim);font-weight:normal">${peakStr}</span>`;
|
||||
wrap.appendChild(lbl);
|
||||
|
||||
if (values.length === 0) {
|
||||
const e = document.createElement('div');
|
||||
e.style.cssText = 'height:80px;display:flex;align-items:center;justify-content:center;color:var(--text-dim);font-size:11px';
|
||||
e.textContent = 'no samples decoded';
|
||||
wrap.appendChild(e);
|
||||
chartsDiv.appendChild(wrap);
|
||||
continue;
|
||||
}
|
||||
|
||||
const canvasWrap = document.createElement('div');
|
||||
canvasWrap.style.cssText = 'position:relative;height:100px';
|
||||
const canvas = document.createElement('canvas');
|
||||
canvasWrap.appendChild(canvas);
|
||||
wrap.appendChild(canvasWrap);
|
||||
chartsDiv.appendChild(wrap);
|
||||
|
||||
// Waveform: per-sample time in ms relative to trigger (negative for pretrig).
|
||||
// Histogram: when the server has aggregated to BW-reported intervals AND
|
||||
// provides per-interval timestamps, use those as x-axis labels (HH:MM:SS).
|
||||
// Falls back to interval index.
|
||||
let times;
|
||||
if (isHistogram) {
|
||||
const intervalTimes = ta.interval_times || [];
|
||||
times = (intervalTimes.length === values.length)
|
||||
? intervalTimes
|
||||
: values.map((_, i) => i + 1);
|
||||
} else {
|
||||
times = values.map((_, i) => t0Ms + i * dtMs);
|
||||
}
|
||||
|
||||
// Downsample for rendering when very long.
|
||||
const MAX = 3000;
|
||||
let rT = times, rV = values;
|
||||
if (values.length > MAX) {
|
||||
const step = Math.ceil(values.length / MAX);
|
||||
rT = times.filter((_, i) => i % step === 0);
|
||||
rV = values.filter((_, i) => i % step === 0);
|
||||
}
|
||||
const showX = (ch === lastCh);
|
||||
|
||||
// Tick label formatter: snap floats to 1 decimal place so we don't get
|
||||
// "11.7187040000000002 ms" garbage from accumulated floating-point error.
|
||||
const xAxisLabel = isHistogram ? '' : ' ms';
|
||||
const fmtTick = i => {
|
||||
const v = rT[i];
|
||||
if (typeof v === 'number') {
|
||||
// Whole numbers (intervals) → no decimals. Sub-integer ms → 1 decimal.
|
||||
const s = Number.isInteger(v) ? String(v) : v.toFixed(1);
|
||||
return s + xAxisLabel;
|
||||
}
|
||||
return String(v) + xAxisLabel;
|
||||
};
|
||||
|
||||
// Y-axis bounds. Convention:
|
||||
// - Geophones (Tran/Vert/Long) on waveform-mode events:
|
||||
// symmetric around zero so the zero line sits in the middle and
|
||||
// positive/negative excursions are visually balanced.
|
||||
// - Mic (always positive sound pressure) + histograms (per-interval
|
||||
// peaks, always positive): default auto-scale, zero at the bottom.
|
||||
let yBounds = {};
|
||||
const isGeo = ch !== 'MicL';
|
||||
if (isGeo && !isHistogram) {
|
||||
// Waveform geo: symmetric around zero, full zoom to shape detail.
|
||||
let absMax = 0;
|
||||
for (const v of values) {
|
||||
const a = Math.abs(v);
|
||||
if (a > absMax) absMax = a;
|
||||
}
|
||||
const padded = (absMax || 1) * 1.10;
|
||||
yBounds = { min: -padded, max: padded };
|
||||
} else if (isGeo && isHistogram) {
|
||||
// Histogram geo: enforce a minimum chart range so a quiet
|
||||
// 0.005 in/s event renders as ~10% of chart height instead of
|
||||
// filling the panel. Matches BW's near-fixed-scale convention
|
||||
// (their footer is "Geo: 0.002 in/s/div" — a chart-relative scale,
|
||||
// not auto-zoom).
|
||||
const HIST_GEO_MIN_INS = 0.05;
|
||||
let peak = 0;
|
||||
for (const v of values) { const a = Math.abs(v); if (a > peak) peak = a; }
|
||||
yBounds = { min: 0, max: Math.max(peak * 1.10, HIST_GEO_MIN_INS) };
|
||||
} else if (ch === 'MicL' && micUnit === 'dBL') {
|
||||
// Mic in dBL — pin baseline at noise-floor minimum (where we floored
|
||||
// quiet samples), top at actual peak + a few dB headroom.
|
||||
const peakDbl = (typeof chPeak === 'number' && isFinite(chPeak))
|
||||
? chPeak + 5
|
||||
: 100;
|
||||
yBounds = { min: MIC_DBL_FLOOR, max: Math.max(peakDbl, MIC_DBL_FLOOR + 20) };
|
||||
} else if (ch === 'MicL' && isHistogram && micUnit === 'psi') {
|
||||
// Mic histogram in psi — same minimum-range treatment as geo.
|
||||
// 0.001 psi ≈ 110 dBL — typical "loud" mic peak. Quiet events
|
||||
// sit near the bottom.
|
||||
const HIST_MIC_MIN_PSI = 0.001;
|
||||
let peak = 0;
|
||||
for (const v of values) { const a = Math.abs(v); if (a > peak) peak = a; }
|
||||
yBounds = { min: 0, max: Math.max(peak * 1.10, HIST_MIC_MIN_PSI) };
|
||||
}
|
||||
|
||||
_scCharts[ch] = new Chart(canvas, {
|
||||
type: isHistogram ? 'bar' : 'line',
|
||||
data: {
|
||||
labels: rT.map(t => (typeof t === 'number' ? (Number.isInteger(t) ? String(t) : t.toFixed(2)) : t)),
|
||||
datasets: isHistogram ? [{
|
||||
data: rV,
|
||||
backgroundColor: _SC_CHANNEL_COLORS[ch],
|
||||
borderWidth: 0,
|
||||
barPercentage: 1.0,
|
||||
categoryPercentage: 1.0, // bars touch — "tight bargraph" look
|
||||
}] : [{
|
||||
data: rV,
|
||||
borderColor: _SC_CHANNEL_COLORS[ch],
|
||||
borderWidth: 1,
|
||||
pointRadius: 0,
|
||||
tension: 0,
|
||||
}],
|
||||
},
|
||||
options: {
|
||||
animation: false, responsive: true, maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
mode: 'index', intersect: false,
|
||||
callbacks: {
|
||||
title: items => isHistogram
|
||||
? `interval ${items[0].label}`
|
||||
: `t = ${items[0].label} ms`,
|
||||
label: item => `${ch}: ${_fmtPeak(item.raw, chUnit)}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
type: 'category', display: showX,
|
||||
ticks: { color: '#484f58', maxTicksLimit: 8, maxRotation: 0, callback: (v, i) => fmtTick(i) },
|
||||
grid: { color: '#21262d', drawTicks: showX },
|
||||
},
|
||||
y: {
|
||||
...yBounds,
|
||||
ticks: { color: '#484f58', maxTicksLimit: 4 },
|
||||
grid: { color: '#21262d' },
|
||||
title: { display: true, text: chUnit, color: '#484f58', font: { size: 9 } },
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: isHistogram ? [] : [{
|
||||
// Trigger line + triangle markers + zero baseline — only meaningful
|
||||
// for waveform-mode events. Histograms have no trigger.
|
||||
id: 'overlays',
|
||||
afterDraw(chart) {
|
||||
const ctx = chart.ctx, x = chart.scales.x, y = chart.scales.y;
|
||||
// Dashed trigger line at t=0
|
||||
const zi = rT.findIndex(t => parseFloat(t) >= 0);
|
||||
if (zi >= 0) {
|
||||
const px = x.getPixelForValue(zi);
|
||||
ctx.save();
|
||||
ctx.beginPath(); ctx.moveTo(px, y.top); ctx.lineTo(px, y.bottom);
|
||||
ctx.strokeStyle = 'rgba(248,81,73,0.8)'; ctx.lineWidth = 1.2;
|
||||
ctx.setLineDash([4, 3]); ctx.stroke(); ctx.restore();
|
||||
// Triangle markers above and below the chart
|
||||
ctx.save();
|
||||
ctx.fillStyle = '#f85149';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(px - 4, y.top - 7); ctx.lineTo(px + 4, y.top - 7); ctx.lineTo(px, y.top - 1);
|
||||
ctx.closePath(); ctx.fill();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(px - 4, y.bottom + 7); ctx.lineTo(px + 4, y.bottom + 7); ctx.lineTo(px, y.bottom + 1);
|
||||
ctx.closePath(); ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
// Zero baseline + label
|
||||
const zy = y.getPixelForValue(0);
|
||||
if (zy >= y.top && zy <= y.bottom) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = '#30363d'; ctx.lineWidth = 0.8;
|
||||
ctx.setLineDash([2, 2]);
|
||||
ctx.beginPath(); ctx.moveTo(x.left, zy); ctx.lineTo(x.right, zy); ctx.stroke();
|
||||
ctx.restore();
|
||||
ctx.save();
|
||||
ctx.fillStyle = '#c9d1d9'; ctx.font = '10px monospace';
|
||||
ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
|
||||
ctx.fillText('0.0', x.right + 6, zy);
|
||||
ctx.restore();
|
||||
}
|
||||
},
|
||||
}],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure charts get cleaned up when the modal closes.
|
||||
function _scCleanupOnClose() { _destroyScCharts(); }
|
||||
|
||||
function _renderSidecar(data) {
|
||||
const ev = data.event || {};
|
||||
const pv = data.peak_values || {};
|
||||
@@ -2454,6 +2886,12 @@ function _renderSidecar(data) {
|
||||
const bw = data.blastware || {};
|
||||
const src = data.source || {};
|
||||
const rev = data.review || {};
|
||||
// bw_report carries the per-channel ASCII-derived stats (ZC Freq,
|
||||
// saturation flags, peak time, etc.). Only present on events
|
||||
// ingested with a preserved .TXT (post-2026-05-27); falls back to
|
||||
// empty for legacy events.
|
||||
const bwrPeaks = (data.bw_report || {}).peaks || {};
|
||||
const bwrMic = (data.bw_report || {}).mic || {};
|
||||
|
||||
document.getElementById('sc-title').textContent = `Event — ${bw.filename || ev.waveform_key || 'unknown'}`;
|
||||
|
||||
@@ -2479,27 +2917,72 @@ function _renderSidecar(data) {
|
||||
};
|
||||
|
||||
document.getElementById('sc-f-serial').textContent = ev.serial || '—';
|
||||
document.getElementById('sc-f-ts').textContent = ev.timestamp || '—';
|
||||
// Route through _fmtTs so the unit-local naive timestamp shows as
|
||||
// "5/27/2026, 6:00:13 AM" instead of "2026-05-27T06:00:13".
|
||||
document.getElementById('sc-f-ts').textContent = _fmtTs(ev.timestamp);
|
||||
document.getElementById('sc-f-rt').textContent = ev.record_type || '—';
|
||||
document.getElementById('sc-f-sr').textContent = (ev.sample_rate ?? '—') + (ev.sample_rate ? ' sps' : '');
|
||||
document.getElementById('sc-f-key').textContent = ev.waveform_key || '—';
|
||||
|
||||
document.getElementById('sc-f-tran').textContent = fmtPpv(pv.transverse);
|
||||
document.getElementById('sc-f-vert').textContent = fmtPpv(pv.vertical);
|
||||
document.getElementById('sc-f-long').textContent = fmtPpv(pv.longitudinal);
|
||||
// Suffix with " · {prefix}{N} Hz" when bw_report has a ZC Freq.
|
||||
// Above-range ZC peaks (BW ">100 Hz") get a literal ">" prefix so
|
||||
// operators see the same indicator the PDF shows.
|
||||
const fmtZc = bwr => {
|
||||
if (!bwr || bwr.zc_freq_hz == null) return '';
|
||||
const prefix = bwr.zc_freq_above_range ? '>' : '';
|
||||
return ` · ${prefix}${Math.round(bwr.zc_freq_hz)} Hz`;
|
||||
};
|
||||
document.getElementById('sc-f-tran').textContent = fmtPpv(pv.transverse) + fmtZc(bwrPeaks.tran);
|
||||
document.getElementById('sc-f-vert').textContent = fmtPpv(pv.vertical) + fmtZc(bwrPeaks.vert);
|
||||
document.getElementById('sc-f-long').textContent = fmtPpv(pv.longitudinal) + fmtZc(bwrPeaks.long);
|
||||
document.getElementById('sc-f-pvs').textContent = fmtPpv(pv.vector_sum);
|
||||
document.getElementById('sc-f-mic').textContent = fmtMic(pv.mic_psi);
|
||||
document.getElementById('sc-f-mic').textContent = fmtMic(pv.mic_psi) + fmtZc(bwrMic);
|
||||
|
||||
document.getElementById('sc-f-project').textContent = pi.project || '—';
|
||||
document.getElementById('sc-f-client').textContent = pi.client || '—';
|
||||
document.getElementById('sc-f-operator').textContent = pi.operator || '—';
|
||||
document.getElementById('sc-f-loc').textContent = pi.sensor_location || '—';
|
||||
|
||||
document.getElementById('sc-f-bw').textContent = bw.filename || '—';
|
||||
// Filename rendered as a clickable download link for the original BW
|
||||
// binary. Same endpoint the live-device viewer uses for stored events
|
||||
// (/db/events/{id}/blastware_file).
|
||||
const bwCell = document.getElementById('sc-f-bw');
|
||||
bwCell.innerHTML = '';
|
||||
if (bw.filename && _scCurrentEventId) {
|
||||
const a = document.createElement('a');
|
||||
a.href = `${api()}/db/events/${_scCurrentEventId}/blastware_file`;
|
||||
a.textContent = bw.filename;
|
||||
a.download = bw.filename;
|
||||
a.title = 'Download original BW event binary';
|
||||
a.style.color = 'var(--accent, #58a6ff)';
|
||||
a.style.textDecoration = 'underline';
|
||||
bwCell.appendChild(a);
|
||||
} else {
|
||||
bwCell.textContent = '—';
|
||||
}
|
||||
document.getElementById('sc-f-bwsize').textContent = bw.filesize != null ? `${bw.filesize} bytes` : '—';
|
||||
document.getElementById('sc-f-sha').textContent = bw.sha256 || '—';
|
||||
document.getElementById('sc-f-src').textContent = src.kind || '—';
|
||||
document.getElementById('sc-f-cap').textContent = src.captured_at || '—';
|
||||
// Source kind + a download link for the preserved BW ASCII report
|
||||
// (.TXT), when available. Only events ingested after 2026-05-27
|
||||
// have the .TXT preserved; older events show "—".
|
||||
const srcCell = document.getElementById('sc-f-src');
|
||||
srcCell.innerHTML = '';
|
||||
srcCell.appendChild(document.createTextNode(src.kind || '—'));
|
||||
if (src.txt_filename && _scCurrentEventId) {
|
||||
const a = document.createElement('a');
|
||||
a.href = `${api()}/db/events/${_scCurrentEventId}/ascii_report.txt`;
|
||||
a.textContent = ' (download .TXT)';
|
||||
a.download = src.txt_filename;
|
||||
a.title = 'Download preserved BW ASCII report';
|
||||
a.style.color = 'var(--accent, #58a6ff)';
|
||||
a.style.marginLeft = '8px';
|
||||
a.style.fontSize = '11px';
|
||||
srcCell.appendChild(a);
|
||||
}
|
||||
// captured_at has a "Z" suffix (UTC); _fmtTs converts to browser local
|
||||
// — matches the BW-reported recorded-at, no more "21:59:57 vs it's 6 PM"
|
||||
// confusion from operators reading the raw UTC value.
|
||||
document.getElementById('sc-f-cap').textContent = _fmtTs(src.captured_at);
|
||||
|
||||
document.getElementById('sc-edit-ft').checked = !!rev.false_trigger;
|
||||
document.getElementById('sc-edit-reviewer').value = rev.reviewer || '';
|
||||
@@ -2512,6 +2995,19 @@ function closeSidecarModal() {
|
||||
document.getElementById('sc-overlay').classList.remove('visible');
|
||||
_scCurrentEventId = null;
|
||||
_scCurrentSidecar = null;
|
||||
_destroyScCharts();
|
||||
}
|
||||
|
||||
// Trigger a PDF download for the currently-open event. The browser
|
||||
// handles the actual save dialog from the Content-Disposition header
|
||||
// the server sends.
|
||||
function downloadEventReport() {
|
||||
if (!_scCurrentEventId) return;
|
||||
const url = `${api()}/db/events/${_scCurrentEventId}/report.pdf`;
|
||||
// Open in a new tab — browser prompts to save or displays inline,
|
||||
// and a failed fetch (e.g. 404 for events with no waveform) shows
|
||||
// its JSON error in-page rather than silently failing.
|
||||
window.open(url, '_blank');
|
||||
}
|
||||
|
||||
function onSidecarOverlayClick(e) {
|
||||
@@ -2722,6 +3218,16 @@ document.addEventListener('keydown', e => {
|
||||
// hit localhost:8200, 10.0.0.44:8200, or anything else.
|
||||
document.getElementById('api-base').value = window.location.origin;
|
||||
|
||||
// Reflect any persisted mic-unit preference in the header pill on load
|
||||
_refreshMicUnitToggleLabel();
|
||||
|
||||
// We default to Database view → trigger initial history + units load
|
||||
// (switchSection handles this when clicked, but we never click on first paint).
|
||||
if (currentSection === 'db') {
|
||||
if (!histLoaded) loadHistory();
|
||||
if (!unitsLoaded) loadUnits();
|
||||
}
|
||||
|
||||
// Press Enter in any live connect field to connect
|
||||
['dev-host','dev-port'].forEach(id => {
|
||||
document.getElementById(id)?.addEventListener('keydown', e => { if (e.key === 'Enter') connectUnit(); });
|
||||
@@ -2738,11 +3244,18 @@ document.getElementById('api-base').value = window.location.origin;
|
||||
<button class="sc-close" onclick="closeSidecarModal()">×</button>
|
||||
</div>
|
||||
<div class="sc-body">
|
||||
<!-- Waveform plot — 4 channels stacked (MicL, Long, Vert, Tran) — -->
|
||||
<div class="sc-section" id="sc-section-waveform">
|
||||
<h4>Waveform</h4>
|
||||
<div id="sc-waveform-status" style="color:var(--text-dim);font-size:11px;margin-bottom:6px">Loading…</div>
|
||||
<div id="sc-waveform-charts" style="display:flex;flex-direction:column;gap:6px"></div>
|
||||
</div>
|
||||
<div class="sc-section">
|
||||
<h4>Event</h4>
|
||||
<dl class="sc-grid">
|
||||
<dt>Serial</dt> <dd id="sc-f-serial">—</dd>
|
||||
<dt>Timestamp</dt> <dd id="sc-f-ts">—</dd>
|
||||
<dt title="When the seismograph recorded this event (from the BW report's Event Time field)">Recorded at</dt>
|
||||
<dd id="sc-f-ts">—</dd>
|
||||
<dt>Record type</dt> <dd id="sc-f-rt">—</dd>
|
||||
<dt>Sample rate</dt> <dd id="sc-f-sr">—</dd>
|
||||
<dt>Waveform key</dt> <dd id="sc-f-key">—</dd>
|
||||
@@ -2774,7 +3287,8 @@ document.getElementById('api-base').value = window.location.origin;
|
||||
<dt id="sc-l-bwsize">File size</dt> <dd id="sc-f-bwsize">—</dd>
|
||||
<dt id="sc-l-sha">File sha256</dt> <dd id="sc-f-sha">—</dd>
|
||||
<dt>Source kind</dt> <dd id="sc-f-src">—</dd>
|
||||
<dt>Captured at</dt> <dd id="sc-f-cap">—</dd>
|
||||
<dt title="When SFM received and stored this event — NOT the unit-local trigger time (see Timestamp at the top of the modal for that).">Time received</dt>
|
||||
<dd id="sc-f-cap">—</dd>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="sc-section">
|
||||
@@ -2797,6 +3311,10 @@ document.getElementById('api-base').value = window.location.origin;
|
||||
</div>
|
||||
<div class="sc-footer">
|
||||
<span class="sc-status" id="sc-status"></span>
|
||||
<button class="btn btn-ghost" id="sc-pdf-btn" onclick="downloadEventReport()"
|
||||
title="Download an Instantel-style Event Report PDF for this event">
|
||||
Download PDF
|
||||
</button>
|
||||
<button class="btn btn-ghost" onclick="closeSidecarModal()">Cancel</button>
|
||||
<button class="btn" id="sc-save-btn" onclick="saveSidecarReview()">Save</button>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Waveform-shape metrics for false-trigger detection.
|
||||
|
||||
A false trigger is an isolated impulse (quiet → spike → quiet); a real event
|
||||
rings for many cycles. Two numbers separate them: crest factor (how far the
|
||||
peak stands above the typical sample) and how many samples sit near the peak.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import numpy as np
|
||||
|
||||
_GEO_CHANNELS = ("Tran", "Vert", "Long")
|
||||
NEAR_PEAK_FRACTION = 0.5 # a sample "near the peak" is >= this * peak amplitude
|
||||
|
||||
|
||||
def channel_shape(x) -> dict | None:
|
||||
x = np.asarray(x, dtype=float)
|
||||
if x.size < 2:
|
||||
return None
|
||||
peak = float(np.max(np.abs(x)))
|
||||
if peak <= 0:
|
||||
return None
|
||||
rms = float(np.sqrt(np.mean(x ** 2)))
|
||||
if rms <= 0:
|
||||
return None
|
||||
near = int(np.sum(np.abs(x) >= NEAR_PEAK_FRACTION * peak))
|
||||
return {"crest_factor": peak / rms, "near_peak_count": near,
|
||||
"sample_count": int(x.size)}
|
||||
|
||||
|
||||
def shape_from_samples(chans: dict) -> dict | None:
|
||||
best_axis, best_peak, best_x = None, -1.0, None
|
||||
for ax in _GEO_CHANNELS:
|
||||
x = chans.get(ax)
|
||||
if x is None:
|
||||
continue
|
||||
x = np.asarray(x, dtype=float)
|
||||
if x.size < 2:
|
||||
continue
|
||||
p = float(np.max(np.abs(x)))
|
||||
if p > best_peak:
|
||||
best_axis, best_peak, best_x = ax, p, x
|
||||
if best_axis is None:
|
||||
return None
|
||||
s = channel_shape(best_x)
|
||||
if s is None:
|
||||
return None
|
||||
s["axis"] = best_axis
|
||||
return s
|
||||
|
||||
|
||||
def shape_from_h5(path) -> dict | None:
|
||||
import h5py
|
||||
try:
|
||||
with h5py.File(path, "r") as f:
|
||||
chans = {ax: f[f"samples/{ax}"][:] for ax in _GEO_CHANNELS
|
||||
if f"samples/{ax}" in f}
|
||||
except Exception:
|
||||
return None
|
||||
return shape_from_samples(chans)
|
||||
+256
-23
@@ -41,6 +41,7 @@ from minimateplus.blastware_file import blastware_filename, write_blastware_file
|
||||
from minimateplus.framing import S3Frame
|
||||
from minimateplus.models import Event
|
||||
from sfm import event_hdf5
|
||||
from sfm.shape_metrics import shape_from_h5
|
||||
|
||||
log = logging.getLogger("sfm.waveform_store")
|
||||
|
||||
@@ -108,11 +109,30 @@ class WaveformStore:
|
||||
"""Return absolute path to the .h5 clean-waveform file for a given event."""
|
||||
return self._serial_dir(serial) / f"{filename}.h5"
|
||||
|
||||
def txt_path_for(self, serial: str, filename: str) -> Path:
|
||||
"""Return absolute path to the preserved BW ASCII report (.TXT)
|
||||
for a given event.
|
||||
|
||||
We name it ``<filename>_ASCII.TXT`` to match BW's own filename
|
||||
convention in the ACH folder. Saved at ingest time alongside
|
||||
the binary so the parser bug fixes can be applied retroactively
|
||||
by re-parsing without needing to re-forward from the watcher PC.
|
||||
"""
|
||||
return self._serial_dir(serial) / f"{filename}_ASCII.TXT"
|
||||
|
||||
def open_blastware(self, serial: str, filename: str) -> Optional[Path]:
|
||||
"""Return absolute path to an existing event file or None."""
|
||||
bw_path, _ = self.paths_for(serial, filename)
|
||||
return bw_path if bw_path.exists() else None
|
||||
|
||||
def open_txt(self, serial: str, filename: str) -> Optional[Path]:
|
||||
"""Return absolute path to the preserved BW ASCII report for an
|
||||
event, or None if the .TXT wasn't saved at ingest time (events
|
||||
ingested before .TXT preservation landed will show None until
|
||||
re-forwarded)."""
|
||||
p = self.txt_path_for(serial, filename)
|
||||
return p if p.exists() else None
|
||||
|
||||
# ── save / load ─────────────────────────────────────────────────────────────
|
||||
|
||||
def save(
|
||||
@@ -243,6 +263,13 @@ class WaveformStore:
|
||||
serial, filename, filesize, len(a5_frames),
|
||||
hdf5_filename or "(skipped)", sidecar_path.name,
|
||||
)
|
||||
_shape = shape_from_h5(hdf5_path) if hdf5_filename else None
|
||||
_shape_rec = {
|
||||
"shape_crest_factor": _shape["crest_factor"],
|
||||
"shape_near_peak_count": _shape["near_peak_count"],
|
||||
"shape_sample_count": _shape["sample_count"],
|
||||
"shape_axis": _shape["axis"],
|
||||
} if _shape else {}
|
||||
return {
|
||||
"filename": filename,
|
||||
"filesize": filesize,
|
||||
@@ -250,6 +277,7 @@ class WaveformStore:
|
||||
"a5_pickle_filename": a5_path.name,
|
||||
"hdf5_filename": hdf5_filename,
|
||||
"sidecar_filename": sidecar_path.name,
|
||||
**_shape_rec,
|
||||
}
|
||||
|
||||
def save_imported_bw(
|
||||
@@ -357,6 +385,28 @@ class WaveformStore:
|
||||
filesize = bw_path.stat().st_size
|
||||
sha256 = event_file_io.file_sha256(bw_path)
|
||||
|
||||
# 1b. preserve the raw BW ASCII report (.TXT) alongside the binary.
|
||||
# Saved at <root>/<serial>/<filename>_ASCII.TXT. Lets us re-parse
|
||||
# offline after parser fixes without needing to re-forward from
|
||||
# the watcher PC. Negligible storage cost (~15 KB per event).
|
||||
# Skipped silently when no report was supplied (live download path,
|
||||
# manual upload without paired TXT).
|
||||
txt_filename: Optional[str] = None
|
||||
if bw_report_text is not None:
|
||||
try:
|
||||
txt_path = self.txt_path_for(serial, filename)
|
||||
if isinstance(bw_report_text, bytes):
|
||||
txt_path.write_bytes(bw_report_text)
|
||||
else:
|
||||
txt_path.write_text(bw_report_text)
|
||||
txt_filename = txt_path.name
|
||||
except Exception as exc:
|
||||
log.warning(
|
||||
"save_imported_bw: failed to save TXT for %s: %s — "
|
||||
"continuing without it",
|
||||
filename, exc,
|
||||
)
|
||||
|
||||
# 2. write the .h5 clean-waveform file from the parsed Event.
|
||||
# Note: peaks here are computed from raw samples (the BW file
|
||||
# doesn't carry the device-authoritative 0C peaks). Best-effort.
|
||||
@@ -393,6 +443,7 @@ class WaveformStore:
|
||||
blastware_sha256=sha256,
|
||||
source_kind="bw-import",
|
||||
a5_pickle_filename=None,
|
||||
txt_filename=txt_filename,
|
||||
review=existing_review,
|
||||
bw_report=bw_report,
|
||||
)
|
||||
@@ -403,6 +454,13 @@ class WaveformStore:
|
||||
"h5=%s (no .a5.pkl — A5 source unavailable for BW-imported files)",
|
||||
serial, filename, filesize, hdf5_filename or "(skipped)",
|
||||
)
|
||||
_shape = shape_from_h5(hdf5_path) if hdf5_filename else None
|
||||
_shape_rec = {
|
||||
"shape_crest_factor": _shape["crest_factor"],
|
||||
"shape_near_peak_count": _shape["near_peak_count"],
|
||||
"shape_sample_count": _shape["sample_count"],
|
||||
"shape_axis": _shape["axis"],
|
||||
} if _shape else {}
|
||||
return ev, {
|
||||
"filename": filename,
|
||||
"filesize": filesize,
|
||||
@@ -411,6 +469,7 @@ class WaveformStore:
|
||||
"hdf5_filename": hdf5_filename,
|
||||
"sidecar_filename": sidecar_path.name,
|
||||
"serial": serial,
|
||||
**_shape_rec,
|
||||
}
|
||||
|
||||
def save_imported_idf(
|
||||
@@ -425,21 +484,21 @@ class WaveformStore:
|
||||
Ingest a Thor (Micromate Series IV) IDF event file (`.IDFW` or
|
||||
`.IDFH`) produced by Thor's TXT exporter.
|
||||
|
||||
Thor binaries are stored as opaque bytes — seismo-relay doesn't
|
||||
yet decode the proprietary IDF binary format (codec slot lives
|
||||
at ``micromate/idf_file.py``). Device-authoritative metadata
|
||||
comes from the paired ``.IDFW.txt`` / ``.IDFH.txt`` sidecar
|
||||
when supplied.
|
||||
|
||||
Workflow:
|
||||
1. Parse the paired TXT report (when supplied) via
|
||||
``micromate.parse_idf_report`` → dict.
|
||||
2. Wrap parsed dict + filename into a typed ``micromate.IdfEvent``.
|
||||
3. Copy bytes verbatim into ``<root>/<serial>/<filename>``.
|
||||
4. Bridge IdfEvent → ``minimateplus.Event`` (for the existing
|
||||
sidecar / DB insert machinery) via
|
||||
``IdfEvent.to_minimateplus_event(waveform_key)``.
|
||||
5. Write the ``.sfm.json`` sidecar with
|
||||
1. For sig-A `.IDFW` binaries, decode samples + binary metadata
|
||||
via ``micromate.idf_file.read_idf_file()``. Failure or
|
||||
non-IDFW path falls through to the .txt-only flow.
|
||||
2. Parse the paired TXT report (when supplied) via
|
||||
``micromate.parse_idf_report`` → dict. TXT remains the
|
||||
source of truth for fields the binary doesn't yet supply
|
||||
(full peak set with ZC freq / Time of Peak, sensor self-check,
|
||||
firmware string, project strings).
|
||||
3. Wrap parsed dict + filename into a typed ``micromate.IdfEvent``.
|
||||
4. Copy bytes verbatim into ``<root>/<serial>/<filename>``.
|
||||
5. Bridge IdfEvent → ``minimateplus.Event`` and attach
|
||||
``raw_samples`` from the binary decoder (when available).
|
||||
6. Write the `.h5` clean-waveform file when samples decoded.
|
||||
7. Write the ``.sfm.json`` sidecar with
|
||||
``source.kind = "idf-import"`` and the full raw IDF report
|
||||
under ``extensions.idf_report``.
|
||||
|
||||
@@ -448,7 +507,38 @@ class WaveformStore:
|
||||
"""
|
||||
from micromate import IdfEvent, parse_idf_report
|
||||
|
||||
# Parse the .txt sidecar (best-effort; non-fatal on failure).
|
||||
# 1. Binary decode (sig-A IDFW and IDFH). Non-fatal: any failure
|
||||
# leaves samples / binary metadata unfilled and we proceed with
|
||||
# the .txt path as before.
|
||||
idf_samples: Optional[dict] = None
|
||||
idf_intervals: Optional[list] = None
|
||||
binary_md = None
|
||||
binary_peaks = None
|
||||
is_histogram = False
|
||||
try:
|
||||
from micromate.idf_file import read_idf_file
|
||||
# Pass idf_bytes through `data=` — at this point in the flow
|
||||
# the binary hasn't been written to disk yet, so the codec
|
||||
# can't read from source_path. We still pass source_path so
|
||||
# the codec has the filename for error messages + .IDFH
|
||||
# suffix detection.
|
||||
res = read_idf_file(source_path, data=idf_bytes)
|
||||
idf_samples = res.samples or None
|
||||
idf_intervals = res.intervals
|
||||
is_histogram = res.intervals is not None
|
||||
binary_md = res.binary_metadata
|
||||
binary_peaks = res.event.peaks
|
||||
except NotImplementedError:
|
||||
# sig-B — codec doesn't handle this yet.
|
||||
pass
|
||||
except Exception as exc:
|
||||
log.warning(
|
||||
"save_imported_idf: binary codec failed for %s: %s — "
|
||||
"falling back to .txt-only ingest",
|
||||
source_path.name, exc,
|
||||
)
|
||||
|
||||
# 2. Parse the .txt sidecar (best-effort; non-fatal on failure).
|
||||
report_dict: dict = {}
|
||||
if idf_report_text is not None:
|
||||
try:
|
||||
@@ -459,17 +549,58 @@ class WaveformStore:
|
||||
exc,
|
||||
)
|
||||
|
||||
# Build the typed IdfEvent. Filename is authoritative for
|
||||
# 3. Backfill report_dict with binary metadata for fields the
|
||||
# .txt didn't supply. Binary takes precedence on tied fields
|
||||
# where the binary is more reliable (timestamp, sample_rate),
|
||||
# and fills in fields entirely missing from the .txt.
|
||||
if binary_md is not None:
|
||||
if binary_md.serial and not report_dict.get("serial_number"):
|
||||
report_dict["serial_number"] = binary_md.serial
|
||||
if binary_md.event_datetime and not report_dict.get("event_datetime"):
|
||||
report_dict["event_datetime"] = binary_md.event_datetime
|
||||
if binary_md.sample_rate and not report_dict.get("sample_rate"):
|
||||
report_dict["sample_rate"] = binary_md.sample_rate
|
||||
if binary_md.record_time_sec and not report_dict.get("record_time_sec"):
|
||||
report_dict["record_time_sec"] = binary_md.record_time_sec
|
||||
# Calibration date (binary) vs calibration text (.txt) cohabit
|
||||
# under different keys; no overwrite needed.
|
||||
if binary_md.event_datetime and not report_dict.get("event_type"):
|
||||
report_dict["event_type"] = (
|
||||
"Full Histogram" if is_histogram else "Full Waveform"
|
||||
)
|
||||
|
||||
# Binary-derived peaks fill in when the .txt didn't supply them.
|
||||
# They're ~3% low vs the device-authoritative .txt values (residual
|
||||
# codec drift), so .txt always wins when present.
|
||||
if binary_peaks is not None:
|
||||
if binary_peaks.transverse_ips and not report_dict.get("tran_ppv"):
|
||||
report_dict["tran_ppv"] = binary_peaks.transverse_ips
|
||||
if binary_peaks.vertical_ips and not report_dict.get("vert_ppv"):
|
||||
report_dict["vert_ppv"] = binary_peaks.vertical_ips
|
||||
if binary_peaks.longitudinal_ips and not report_dict.get("long_ppv"):
|
||||
report_dict["long_ppv"] = binary_peaks.longitudinal_ips
|
||||
|
||||
# 4. Build the typed IdfEvent. Filename is authoritative for
|
||||
# (serial, timestamp, kind); the report's event_datetime takes
|
||||
# precedence over the filename timestamp inside from_report().
|
||||
idf_event = IdfEvent.from_report(report_dict, source_path.name)
|
||||
|
||||
# The binary mic peak (psi) isn't carried through from_report() —
|
||||
# IdfReport.from_dict only sees the .txt's dB(L) value. Pull the
|
||||
# binary-derived ``mic_pspl_psi`` onto the typed IdfEvent so the
|
||||
# downstream bridge can populate ``PeakValues.micl`` (psi-shaped)
|
||||
# and the h5 writer's per-count mic factor lands at a sensible
|
||||
# value. Without this, the h5 mic chart auto-scales against the
|
||||
# dB(L) value-as-pseudo-psi and renders ~flat.
|
||||
if binary_peaks is not None and binary_peaks.mic_pspl_psi is not None:
|
||||
idf_event.peaks.mic_pspl_psi = binary_peaks.mic_pspl_psi
|
||||
|
||||
# Operator-supplied serial_hint wins over the binary's filename
|
||||
# prefix when both are present (e.g. callers passing a known-good
|
||||
# serial that overrides a misnamed export).
|
||||
serial = serial_hint or idf_event.serial or "UNKNOWN"
|
||||
|
||||
# Filesystem write.
|
||||
# 5. Filesystem write of binary bytes.
|
||||
filename = source_path.name
|
||||
bw_path = self._serial_dir(serial) / filename
|
||||
bw_path.write_bytes(idf_bytes)
|
||||
@@ -481,13 +612,59 @@ class WaveformStore:
|
||||
# surrogate — every distinct binary maps to a distinct row.
|
||||
waveform_key = bytes.fromhex(sha256)[:16]
|
||||
|
||||
# Bridge to minimateplus.Event for the existing sidecar / DB
|
||||
# 6. Bridge to minimateplus.Event for the existing sidecar / DB
|
||||
# insert paths. See IdfEvent.to_minimateplus_event() for the
|
||||
# caveats of this bridge (mic units, missing fields → sidecar).
|
||||
ev = idf_event.to_minimateplus_event(waveform_key)
|
||||
|
||||
# Write the sidecar. Source kind "idf-import" was added to the
|
||||
# allow-list in event_file_io.event_to_sidecar_dict for this.
|
||||
# Attach the decoded sample arrays. Thor's decoder counts use
|
||||
# LSB = 0.0003 in/s for geo (vs BW's 16-count units at 0.005 in/s)
|
||||
# — the .h5 writer's geo_range="normal" yields LSB = 10/32768
|
||||
# ≈ 0.000305 in/s, so plotted samples come out ~1.7% high.
|
||||
# Acceptable known offset; refine with a Thor-aware h5 path later.
|
||||
if idf_samples is not None:
|
||||
ev.raw_samples = idf_samples
|
||||
n_samples = max((len(idf_samples.get(ch, [])) for ch in ("Tran", "Vert", "Long", "MicL")), default=0)
|
||||
ev.total_samples = ev.total_samples or n_samples
|
||||
|
||||
# For IDFH histograms there are no per-sample waveform arrays — the
|
||||
# device stores one peak ADC count per interval per channel. Synthesise
|
||||
# a 1-sample-per-interval array so the existing h5+renderer pipeline
|
||||
# (which groups samples down to ``n_intervals`` bars via max-per-group)
|
||||
# produces a non-blank histogram chart. Each "sample" is the peak ADC
|
||||
# count for that interval, so the h5 writer's ``count × geo_fs/32768``
|
||||
# conversion yields the right physical value for the bar height.
|
||||
if is_histogram and idf_intervals:
|
||||
hist_samples = {
|
||||
"Tran": [iv.peak_count("Tran") for iv in idf_intervals],
|
||||
"Vert": [iv.peak_count("Vert") for iv in idf_intervals],
|
||||
"Long": [iv.peak_count("Long") for iv in idf_intervals],
|
||||
"MicL": [iv.peak_count("MicL") for iv in idf_intervals],
|
||||
}
|
||||
ev.raw_samples = hist_samples
|
||||
ev.total_samples = ev.total_samples or len(idf_intervals)
|
||||
|
||||
# 7. Write the .h5 clean-waveform file when we have samples to write
|
||||
# (either the IDFW per-sample stream, or the IDFH synthesised per-
|
||||
# interval peak array). The renderer treats both shapes the same way.
|
||||
hdf5_filename: Optional[str] = None
|
||||
if ev.raw_samples:
|
||||
hdf5_path = self.hdf5_path_for(serial, filename)
|
||||
try:
|
||||
event_hdf5.write_event_hdf5(
|
||||
hdf5_path, ev,
|
||||
serial=serial,
|
||||
geo_range="normal", # Thor's geo full scale is also 10 in/s (Normal)
|
||||
source_kind="idf-import",
|
||||
)
|
||||
hdf5_filename = hdf5_path.name
|
||||
except Exception as exc:
|
||||
log.warning(
|
||||
"save_imported_idf: HDF5 write failed for %s: %s — continuing without .h5",
|
||||
hdf5_path, exc,
|
||||
)
|
||||
|
||||
# 8. Write the sidecar. Source kind "idf-import" is on the allow-list.
|
||||
sidecar_path = self.sidecar_path_for(serial, filename)
|
||||
existing_review = None
|
||||
if sidecar_path.exists():
|
||||
@@ -512,21 +689,77 @@ class WaveformStore:
|
||||
# Time of Peak, sensor self-check, calibration, firmware).
|
||||
if report_dict:
|
||||
sidecar["extensions"]["idf_report"] = report_dict
|
||||
|
||||
# Project the IDF report into the BW report sidecar shape so the
|
||||
# existing Event Report PDF pipeline (sfm/report_pdf.py) can
|
||||
# render Thor events without needing a separate code path. Thor
|
||||
# data is 95% the same metric set as BW — the adapter handles
|
||||
# the field-name mapping.
|
||||
if report_dict or binary_md is not None:
|
||||
try:
|
||||
from micromate.idf_to_bw_report import build_bw_report_from_idf
|
||||
sidecar["bw_report"] = build_bw_report_from_idf(
|
||||
report_dict or {},
|
||||
binary_md=binary_md,
|
||||
intervals=idf_intervals,
|
||||
is_histogram=is_histogram,
|
||||
)
|
||||
except Exception as exc:
|
||||
log.warning(
|
||||
"save_imported_idf: idf→bw_report adapter failed for %s: %s — "
|
||||
"report PDF will fall back to DB-only fields",
|
||||
filename, exc,
|
||||
)
|
||||
# For histograms, also stash the binary-decoded per-interval
|
||||
# records so the UI / report layer doesn't need to re-walk the
|
||||
# IDFH file at render time.
|
||||
if idf_intervals is not None:
|
||||
sidecar["extensions"]["idf_intervals"] = [
|
||||
{
|
||||
"offset": iv.offset,
|
||||
"tran_peak": iv.peak_count("Tran"),
|
||||
"tran_halfp": iv.tran_halfp,
|
||||
"tran_freq": iv.freq_hz("Tran"),
|
||||
"vert_peak": iv.peak_count("Vert"),
|
||||
"vert_halfp": iv.vert_halfp,
|
||||
"vert_freq": iv.freq_hz("Vert"),
|
||||
"long_peak": iv.peak_count("Long"),
|
||||
"long_halfp": iv.long_halfp,
|
||||
"long_freq": iv.freq_hz("Long"),
|
||||
"mic_peak": iv.peak_count("MicL"),
|
||||
"mic_halfp": iv.micl_halfp,
|
||||
"mic_freq": iv.freq_hz("MicL"),
|
||||
}
|
||||
for iv in idf_intervals
|
||||
]
|
||||
event_file_io.write_sidecar(sidecar_path, sidecar)
|
||||
|
||||
log.info(
|
||||
"WaveformStore.save_imported_idf serial=%s filename=%s filesize=%d "
|
||||
"report_attached=%s",
|
||||
serial, filename, filesize, bool(report_dict),
|
||||
"kind=%s report_attached=%s binary_decoded=%s h5=%s intervals=%d",
|
||||
serial, filename, filesize,
|
||||
"histogram" if is_histogram else "waveform",
|
||||
bool(report_dict),
|
||||
(idf_samples is not None) or (idf_intervals is not None),
|
||||
hdf5_filename or "(skipped)",
|
||||
len(idf_intervals) if idf_intervals else 0,
|
||||
)
|
||||
_shape = shape_from_h5(hdf5_path) if hdf5_filename else None
|
||||
_shape_rec = {
|
||||
"shape_crest_factor": _shape["crest_factor"],
|
||||
"shape_near_peak_count": _shape["near_peak_count"],
|
||||
"shape_sample_count": _shape["sample_count"],
|
||||
"shape_axis": _shape["axis"],
|
||||
} if _shape else {}
|
||||
return ev, {
|
||||
"filename": filename,
|
||||
"filesize": filesize,
|
||||
"sha256": sha256,
|
||||
"a5_pickle_filename": None,
|
||||
"hdf5_filename": None,
|
||||
"hdf5_filename": hdf5_filename,
|
||||
"sidecar_filename": sidecar_path.name,
|
||||
"serial": serial,
|
||||
**_shape_rec,
|
||||
}
|
||||
|
||||
def load_a5(self, serial: str, filename: str) -> Optional[list[S3Frame]]:
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from __future__ import annotations
|
||||
import numpy as np, h5py
|
||||
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from scripts.backfill_event_shape import backfill_shape
|
||||
from minimateplus.models import Event
|
||||
|
||||
|
||||
def _h5(path, long):
|
||||
with h5py.File(path, "w") as f:
|
||||
g = f.create_group("samples")
|
||||
for k in ("Tran", "Vert"):
|
||||
g.create_dataset(k, data=np.zeros(1024, "float32"))
|
||||
g.create_dataset("Long", data=np.asarray(long, "float32"))
|
||||
|
||||
|
||||
def test_backfill_updates_shape_and_is_idempotent(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex("0111abcd")
|
||||
db.insert_events([ev], serial="BE1",
|
||||
waveform_records={ev._waveform_key.hex():
|
||||
{"filename": "F.CE0W", "filesize": 10}})
|
||||
# place the .h5 where store.paths_for expects it
|
||||
long = np.zeros(1024); long[100] = 0.48
|
||||
_h5(store.hdf5_path_for("BE1", "F.CE0W"), long)
|
||||
|
||||
c1 = backfill_shape(db, store)
|
||||
assert c1["updated"] == 1
|
||||
row = db.query_events(serial="BE1")[0]
|
||||
assert row["shape_axis"] == "Long" and row["shape_near_peak_count"] <= 3
|
||||
c2 = backfill_shape(db, store) # idempotent: re-run overwrites same values
|
||||
assert db.query_events(serial="BE1")[0]["shape_crest_factor"] == row["shape_crest_factor"]
|
||||
@@ -385,6 +385,98 @@ def test_user_notes_extra_lines_beyond_four_are_dropped():
|
||||
assert "L5" not in r.user_note_labels.values()
|
||||
|
||||
|
||||
def test_oorange_marker_treated_as_saturation():
|
||||
"""BW writes 'OORANGE' (Out Of Range — truncated) when a channel
|
||||
exceeds its full-scale. Verify ppv_ips falls back to geo_range_ips
|
||||
+ saturated flag is set, mirroring the real T190LD5Q.LK0W,
|
||||
T438L713.RY0W, and K557L3YM.OE0W events from prod 2026-05-27.
|
||||
"""
|
||||
txt = """\
|
||||
"Event Type : Full Waveform"
|
||||
"Serial Number : BE18190"
|
||||
"Geo Range : 10.000 in/s"
|
||||
"Tran PPV : 2.140 in/s"
|
||||
"Vert PPV : OORANGE in/s"
|
||||
"Long PPV : 2.830 in/s"
|
||||
"Peak Vector Sum : OORANGE in/s"
|
||||
"Peak Vector Sum TimeSum : 0.007 s"
|
||||
"MicL PSPL : OORANGE "
|
||||
"""
|
||||
r = parse_report(txt)
|
||||
# Tran/Long parse normally
|
||||
assert r.channels["Tran"].ppv_ips == 2.14
|
||||
assert r.channels["Tran"].ppv_saturated is False
|
||||
assert r.channels["Long"].ppv_ips == 2.83
|
||||
# Vert saturated → range max + flag
|
||||
assert r.channels["Vert"].ppv_ips == 10.0
|
||||
assert r.channels["Vert"].ppv_saturated is True
|
||||
# PVS saturated → sqrt(3) * range_max as upper bound + flag
|
||||
import math
|
||||
assert r.peak_vector_sum_ips == pytest.approx(math.sqrt(3) * 10.0)
|
||||
assert r.peak_vector_sum_saturated is True
|
||||
# Mic saturated → 140 dBL conservative upper bound + flag
|
||||
assert r.mic.pspl_dbl == 140.0
|
||||
assert r.mic.pspl_saturated is True
|
||||
# PVS time still parses despite the BW typo'd label "TimeSum"
|
||||
assert r.peak_vector_sum_time_s == pytest.approx(0.007)
|
||||
|
||||
|
||||
def test_real_oorange_event_t190_parses():
|
||||
"""End-to-end against the real T190LD5Q.LK0W ASCII file pulled from
|
||||
a Windows watcher PC on 2026-05-27. This is the canonical example
|
||||
of the parser-PPV-miss bug we fixed in this iteration."""
|
||||
fixture_path = (
|
||||
Path(__file__).parent.parent / "example-events" /
|
||||
"ascii-5-27-26" / "T190LD5Q_LK0W_ASCII.TXT"
|
||||
)
|
||||
if not fixture_path.exists():
|
||||
pytest.skip("real ASCII fixture not present (local-only)")
|
||||
r = parse_report_file(fixture_path)
|
||||
assert r.serial == "BE18190"
|
||||
assert r.geo_range_ips == 10.0
|
||||
# Tran reads cleanly, Vert was OORANGE
|
||||
assert r.channels["Tran"].ppv_ips == pytest.approx(2.14)
|
||||
assert r.channels["Vert"].ppv_ips == 10.0
|
||||
assert r.channels["Vert"].ppv_saturated is True
|
||||
assert r.channels["Long"].ppv_ips == pytest.approx(2.83)
|
||||
assert r.peak_vector_sum_saturated is True
|
||||
assert r.peak_vector_sum_time_s == pytest.approx(0.007)
|
||||
# Same fixture: Tran ZC Freq is ">100 Hz" — must parse as 100 +
|
||||
# above_range flag, not None (which would render as "—" on the PDF).
|
||||
assert r.channels["Tran"].zc_freq_hz == 100.0
|
||||
assert r.channels["Tran"].zc_freq_above_range is True
|
||||
# Vert/Long are normal numeric values; flag stays False.
|
||||
assert r.channels["Vert"].zc_freq_above_range is False
|
||||
assert r.channels["Long"].zc_freq_above_range is False
|
||||
|
||||
|
||||
def test_above_range_marker_treated_as_zc_threshold():
|
||||
"""BW writes '>100 Hz' for ZC Freq when the zero-crossing algorithm
|
||||
sees a peak too fast to count (cuts off at the device's 100 Hz
|
||||
reporting ceiling). Parser must store the threshold + flag, not
|
||||
fall back to None.
|
||||
"""
|
||||
txt = """\
|
||||
"Event Type : Full Waveform"
|
||||
"Serial Number : BE18190"
|
||||
"Tran ZC Freq : >100 Hz"
|
||||
"Vert ZC Freq : 73 Hz"
|
||||
"Long ZC Freq : N/A Hz"
|
||||
"MicL ZC Freq : >100 Hz"
|
||||
"""
|
||||
r = parse_report(txt)
|
||||
assert r.channels["Tran"].zc_freq_hz == 100.0
|
||||
assert r.channels["Tran"].zc_freq_above_range is True
|
||||
assert r.channels["Vert"].zc_freq_hz == 73.0
|
||||
assert r.channels["Vert"].zc_freq_above_range is False
|
||||
# N/A → None, flag stays False
|
||||
assert r.channels["Long"].zc_freq_hz is None
|
||||
assert r.channels["Long"].zc_freq_above_range is False
|
||||
# Mic above-range
|
||||
assert r.mic.zc_freq_hz == 100.0
|
||||
assert r.mic.zc_freq_above_range is True
|
||||
|
||||
|
||||
def test_real_histogram_fixture_populates_sensor_location():
|
||||
"""End-to-end: the histogram fixture uses 'Seis. Location:' — must
|
||||
successfully populate sensor_location via position-based parsing."""
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
import os, sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event
|
||||
|
||||
SHAPE_COLS = (
|
||||
"shape_crest_factor",
|
||||
"shape_near_peak_count",
|
||||
"shape_sample_count",
|
||||
"shape_axis",
|
||||
)
|
||||
|
||||
|
||||
def test_query_events_row_includes_shape_keys(tmp_path: Path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex("0111abcd")
|
||||
|
||||
db.insert_events([ev], serial="BE1")
|
||||
row = db.query_events(serial="BE1")[0]
|
||||
|
||||
for k in SHAPE_COLS:
|
||||
assert k in row
|
||||
assert row[k] is None
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
test_db_snapshot.py — unit tests for sfm/db_snapshot.py (snapshot/restore
|
||||
helpers behind the /db/snapshot, /db/waveforms/recent.zip, /db/restore routes).
|
||||
|
||||
Run:
|
||||
python -m pytest tests/test_db_snapshot.py -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import sys
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
def _make_db(path: Path, rows: int = 3) -> None:
|
||||
conn = sqlite3.connect(str(path))
|
||||
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
|
||||
conn.executemany("INSERT INTO t (v) VALUES (?)", [(f"row{i}",) for i in range(rows)])
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def _seed_event(db_path: Path, serial: str, fn: str, ts: str) -> None:
|
||||
conn = sqlite3.connect(str(db_path))
|
||||
conn.execute(
|
||||
"INSERT INTO events (id, serial, waveform_key, timestamp, "
|
||||
"blastware_filename, a5_pickle_filename, sidecar_filename, false_trigger) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, 0)",
|
||||
(f"id-{fn}", serial, fn[:8], ts, fn, f"{fn}.a5.pkl", f"{fn}.sfm.json"),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_snapshot_db_produces_queryable_copy(tmp_path):
|
||||
from sfm.db_snapshot import snapshot_db
|
||||
src = tmp_path / "src.db"
|
||||
_make_db(src, rows=5)
|
||||
dest = tmp_path / "snap.db"
|
||||
out = snapshot_db(src, dest)
|
||||
assert out == dest and dest.exists()
|
||||
conn = sqlite3.connect(str(dest))
|
||||
n = conn.execute("SELECT COUNT(*) FROM t").fetchone()[0]
|
||||
conn.close()
|
||||
assert n == 5
|
||||
|
||||
|
||||
def test_recent_waveforms_zip_bundles_all_per_event_files(tmp_path):
|
||||
import zipfile
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from sfm.db_snapshot import build_recent_waveforms_zip
|
||||
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db") # creates schema on init
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
|
||||
def add(serial, fn, ts):
|
||||
d = store.root / serial
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
for suffix in ("", ".h5", ".a5.pkl", ".sfm.json"):
|
||||
(d / f"{fn}{suffix}").write_bytes(b"data")
|
||||
_seed_event(db.db_path, serial, fn, ts)
|
||||
|
||||
add("BE111", "AAAA1111.OE0H", "2026-06-01T00:00:00")
|
||||
add("BE111", "BBBB2222.OE0H", "2026-06-02T00:00:00") # newest
|
||||
|
||||
dest = tmp_path / "wf.zip"
|
||||
stats = build_recent_waveforms_zip(db, store, n=1, dest_path=dest)
|
||||
|
||||
assert stats["events"] == 1
|
||||
assert stats["files"] == 4
|
||||
with zipfile.ZipFile(dest) as zf:
|
||||
names = set(zf.namelist())
|
||||
assert names == {
|
||||
"BE111/BBBB2222.OE0H",
|
||||
"BE111/BBBB2222.OE0H.h5",
|
||||
"BE111/BBBB2222.OE0H.a5.pkl",
|
||||
"BE111/BBBB2222.OE0H.sfm.json",
|
||||
}
|
||||
|
||||
|
||||
def test_sfm_db_restore_enabled_reads_env(monkeypatch):
|
||||
from sfm.db_snapshot import sfm_db_restore_enabled
|
||||
monkeypatch.delenv("SFM_DB_RESTORE_ENABLED", raising=False)
|
||||
assert sfm_db_restore_enabled() is False
|
||||
monkeypatch.setenv("SFM_DB_RESTORE_ENABLED", "true")
|
||||
assert sfm_db_restore_enabled() is True
|
||||
monkeypatch.setenv("SFM_DB_RESTORE_ENABLED", "0")
|
||||
assert sfm_db_restore_enabled() is False
|
||||
|
||||
|
||||
def test_restore_swaps_db_and_unpacks_waveforms(tmp_path):
|
||||
import zipfile
|
||||
from sfm.db_snapshot import restore_db_and_waveforms
|
||||
|
||||
db_path = tmp_path / "seismo_relay.db"
|
||||
_make_db(db_path, rows=1)
|
||||
(tmp_path / "seismo_relay.db-wal").write_bytes(b"stale") # must be cleared
|
||||
|
||||
new_db = tmp_path / "incoming.db"
|
||||
_make_db(new_db, rows=9)
|
||||
|
||||
wf_root = tmp_path / "waveforms"
|
||||
wf_root.mkdir()
|
||||
wf_zip = tmp_path / "wf.zip"
|
||||
with zipfile.ZipFile(wf_zip, "w") as zf:
|
||||
zf.writestr("BE111/AAAA.OE0H", b"x")
|
||||
zf.writestr("BE111/AAAA.OE0H.h5", b"x")
|
||||
|
||||
result = restore_db_and_waveforms(db_path, wf_root, new_db, wf_zip)
|
||||
|
||||
conn = sqlite3.connect(str(db_path))
|
||||
assert conn.execute("SELECT COUNT(*) FROM t").fetchone()[0] == 9
|
||||
conn.close()
|
||||
assert not (tmp_path / "seismo_relay.db-wal").exists()
|
||||
assert (wf_root / "BE111" / "AAAA.OE0H.h5").exists()
|
||||
assert result["ok"] and result["waveforms_unpacked"] == 2
|
||||
assert result["safety_backup"] is not None
|
||||
|
||||
|
||||
def test_restore_rejects_non_sqlite(tmp_path):
|
||||
import pytest
|
||||
from sfm.db_snapshot import restore_db_and_waveforms
|
||||
db_path = tmp_path / "seismo_relay.db"
|
||||
_make_db(db_path, rows=1)
|
||||
bogus = tmp_path / "bogus.db"
|
||||
bogus.write_bytes(b"not a sqlite file at all")
|
||||
wf_root = tmp_path / "waveforms"
|
||||
wf_root.mkdir()
|
||||
original_bytes = db_path.read_bytes()
|
||||
with pytest.raises(ValueError):
|
||||
restore_db_and_waveforms(db_path, wf_root, bogus, None)
|
||||
assert db_path.read_bytes() == original_bytes
|
||||
assert list(tmp_path.glob("*.pre-restore-*")) == []
|
||||
|
||||
|
||||
def test_restore_skips_unsafe_zip_members(tmp_path):
|
||||
import zipfile
|
||||
from sfm.db_snapshot import restore_db_and_waveforms
|
||||
|
||||
db_path = tmp_path / "seismo_relay.db"
|
||||
_make_db(db_path, rows=1)
|
||||
|
||||
new_db = tmp_path / "incoming.db"
|
||||
_make_db(new_db, rows=2)
|
||||
|
||||
wf_root = tmp_path / "waveforms"
|
||||
wf_root.mkdir()
|
||||
wf_zip = tmp_path / "wf.zip"
|
||||
with zipfile.ZipFile(wf_zip, "w") as zf:
|
||||
zf.writestr("BE111/ok.h5", b"good")
|
||||
zf.writestr("../evil.txt", b"escape via parent dir")
|
||||
zf.writestr("/tmp/abs_evil.txt", b"escape via absolute path")
|
||||
zf.writestr("baddir/", b"")
|
||||
|
||||
result = restore_db_and_waveforms(db_path, wf_root, new_db, wf_zip)
|
||||
|
||||
assert (wf_root / "BE111" / "ok.h5").exists()
|
||||
assert result["waveforms_unpacked"] == 1
|
||||
assert not (wf_root.parent / "evil.txt").exists()
|
||||
assert not Path("/tmp/abs_evil.txt").exists()
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
test_db_snapshot_endpoints.py — HTTP smoke tests for the /db/snapshot,
|
||||
/db/waveforms/recent.zip and /db/restore routes. Skipped if the FastAPI
|
||||
TestClient stack (httpx) is not installed.
|
||||
|
||||
Run:
|
||||
python -m pytest tests/test_db_snapshot_endpoints.py -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("httpx") # starlette TestClient needs httpx
|
||||
|
||||
|
||||
def _client(tmp_path, monkeypatch):
|
||||
import sfm.server as srv
|
||||
from sfm.database import SeismoDb
|
||||
from sfm.waveform_store import WaveformStore
|
||||
from starlette.testclient import TestClient
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
monkeypatch.setattr(srv, "_db", db, raising=False)
|
||||
monkeypatch.setattr(srv, "_store", store, raising=False)
|
||||
return TestClient(srv.app)
|
||||
|
||||
|
||||
def test_snapshot_endpoint_returns_sqlite(tmp_path, monkeypatch):
|
||||
client = _client(tmp_path, monkeypatch)
|
||||
r = client.get("/db/snapshot")
|
||||
assert r.status_code == 200
|
||||
assert r.content[:16] == b"SQLite format 3\x00"
|
||||
|
||||
|
||||
def test_recent_waveforms_endpoint_ok(tmp_path, monkeypatch):
|
||||
client = _client(tmp_path, monkeypatch)
|
||||
r = client.get("/db/waveforms/recent.zip", params={"n": 5})
|
||||
assert r.status_code == 200
|
||||
assert r.headers["content-type"] == "application/zip"
|
||||
|
||||
|
||||
def test_restore_dormant_without_env(tmp_path, monkeypatch):
|
||||
monkeypatch.delenv("SFM_DB_RESTORE_ENABLED", raising=False)
|
||||
client = _client(tmp_path, monkeypatch)
|
||||
r = client.post(
|
||||
"/db/restore",
|
||||
files={"db": ("x.db", b"SQLite format 3\x00", "application/octet-stream")},
|
||||
)
|
||||
assert r.status_code == 404
|
||||
+180
-3
@@ -289,9 +289,106 @@ def test_read_blastware_file_round_trip(tmp_path: Path):
|
||||
assert parsed.timestamp.second == ev.timestamp.second
|
||||
# No A5 source recoverable.
|
||||
assert parsed._a5_frames is None
|
||||
# Peaks computed from samples (synthetic = zero samples → zero peaks).
|
||||
assert parsed.peak_values is not None
|
||||
assert parsed.peak_values.peak_vector_sum == 0.0
|
||||
# The synthetic event has no real waveform body, so the codec can't
|
||||
# decode samples → read_blastware_file leaves peak_values=None
|
||||
# (the "we don't know" signal) rather than fabricating all-zero
|
||||
# peaks that would otherwise overwrite real DB values via UPSERT.
|
||||
assert parsed.peak_values is None
|
||||
assert parsed.raw_samples is not None
|
||||
# Empty channels — codec returned None for the malformed synthetic body.
|
||||
for ch in ("Tran", "Vert", "Long", "MicL"):
|
||||
assert parsed.raw_samples[ch] == []
|
||||
|
||||
|
||||
_BW_CODEC_FIXTURES = [
|
||||
# (path, expected_n_samples_per_channel, BW-reported Vert PPV in/s for sanity)
|
||||
("tests/fixtures/decode-re-5-8-26/event-a/M529LKVQ.6S0", 3328, 0.780),
|
||||
("tests/fixtures/decode-re-5-8-26/event-b/M529LK5Q.RG0", 2304, 0.505),
|
||||
("tests/fixtures/decode-re-5-8-26/event-c/M529LK44.AB0", 1280, 0.610),
|
||||
("tests/fixtures/decode-re-5-8-26/event-d/M529LK2V.470", 1280, 0.565),
|
||||
("tests/fixtures/5-11-26/M529LL1L.V70", 3328, 0.010),
|
||||
("tests/fixtures/5-11-26/M529LL1L.JQ0", 3328, 3.465),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,expected_n,expected_ppv", _BW_CODEC_FIXTURES)
|
||||
def test_read_blastware_file_decodes_via_codec(path: str, expected_n: int, expected_ppv: float):
|
||||
"""Regression lock: ``read_blastware_file()`` must use the verified
|
||||
waveform-body codec (``minimateplus.waveform_codec``), not the
|
||||
retracted int16-LE assumption.
|
||||
|
||||
Verifies against the real BW fixture corpus: every event in the
|
||||
bundled fixtures must produce the expected per-channel sample count
|
||||
and a Vert PPV close to BW's own reported value. Catches any
|
||||
accidental regression of the body decoder back to the old
|
||||
``_decode_samples_4ch_int16_le`` path (which produced ±32K noise
|
||||
on every event, giving wildly wrong PPVs).
|
||||
"""
|
||||
repo_root = Path(__file__).resolve().parent.parent
|
||||
full_path = repo_root / path
|
||||
if not full_path.exists():
|
||||
pytest.skip(f"fixture missing: {full_path}")
|
||||
|
||||
ev = event_file_io.read_blastware_file(full_path)
|
||||
assert ev.raw_samples is not None
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
assert len(ev.raw_samples[ch]) == expected_n, (
|
||||
f"{ch}: expected {expected_n} samples, got {len(ev.raw_samples[ch])}"
|
||||
)
|
||||
|
||||
# PPV check: the codec produces decoded samples in 1-count ADC units;
|
||||
# _peaks_from_samples scales by GEO_NORMAL_FS_INS / 32767. BW's own
|
||||
# PPV is computed at slightly different precision/interpolation, so
|
||||
# we allow a 0.2 in/s tolerance — well under the broken-decoder
|
||||
# signature (which would produce ~10 in/s saturation).
|
||||
assert ev.peak_values is not None
|
||||
assert abs(ev.peak_values.vert - expected_ppv) < 0.2, (
|
||||
f"Vert PPV {ev.peak_values.vert:.3f} differs from BW's "
|
||||
f"{expected_ppv:.3f} by >0.2 in/s — codec regression?"
|
||||
)
|
||||
|
||||
|
||||
def test_read_blastware_file_v70_samples_match_txt_truth():
|
||||
"""Strongest regression lock: every one of V70's 3328 decoded
|
||||
sample-sets must match the .TXT ground truth table within the
|
||||
0.005 in/s display quantum."""
|
||||
repo_root = Path(__file__).resolve().parent.parent
|
||||
bw_path = repo_root / "tests/fixtures/5-11-26/M529LL1L.V70"
|
||||
txt_path = repo_root / "tests/fixtures/5-11-26/M529LL1L.V70.TXT"
|
||||
if not bw_path.exists() or not txt_path.exists():
|
||||
pytest.skip(f"V70 fixture missing")
|
||||
|
||||
import re
|
||||
ev = event_file_io.read_blastware_file(bw_path)
|
||||
|
||||
# Parse .TXT ground truth sample table
|
||||
text = txt_path.read_text()
|
||||
lines = text.splitlines()
|
||||
hdr_idx = next(i for i, line in enumerate(lines)
|
||||
if re.match(r"^Tran\s+Vert\s+Long\s+MicL?", line.strip()))
|
||||
truth = []
|
||||
for line in lines[hdr_idx + 1:]:
|
||||
parts = line.strip().split()
|
||||
if len(parts) != 4:
|
||||
continue
|
||||
try:
|
||||
truth.append([float(x) for x in parts])
|
||||
except ValueError:
|
||||
continue
|
||||
assert len(truth) == 3328, f"expected 3328 truth rows, got {len(truth)}"
|
||||
|
||||
def adc_to_ins(count):
|
||||
return count / 32767.0 * 10.0
|
||||
|
||||
for i, truth_row in enumerate(truth):
|
||||
for ch_idx, ch_name in enumerate(("Tran", "Vert", "Long")):
|
||||
decoded_ips = adc_to_ins(ev.raw_samples[ch_name][i])
|
||||
truth_ips = truth_row[ch_idx]
|
||||
# 0.003 in/s tolerance: <0.005 quantum + small float precision room
|
||||
assert abs(decoded_ips - truth_ips) < 0.003, (
|
||||
f"row {i} {ch_name}: decoded {decoded_ips:+.4f} vs "
|
||||
f"truth {truth_ips:+.4f} (delta {decoded_ips - truth_ips:+.4f})"
|
||||
)
|
||||
|
||||
|
||||
def test_save_imported_bw_with_paired_report(tmp_path: Path):
|
||||
@@ -432,6 +529,77 @@ def test_save_imported_bw_round_trip(tmp_path: Path):
|
||||
assert stored_path.read_bytes() == src.read_bytes()
|
||||
|
||||
|
||||
# ── apply_bw_report_dict_to_event ────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_apply_bw_report_dict_overlays_peaks_and_recording():
|
||||
"""Verbatim mirror of the data shape produced by `_bw_report_to_dict`
|
||||
when projecting a parsed `BwAsciiReport` into the sidecar. Confirms
|
||||
each field overlays onto Event correctly so the backfill path
|
||||
matches ingest behavior."""
|
||||
from minimateplus.models import PeakValues
|
||||
ev = Event(index=0)
|
||||
bw_report = {
|
||||
"peaks": {
|
||||
"tran": {"ppv_ips": 9.84375},
|
||||
"vert": {"ppv_ips": 0.305},
|
||||
"long": {"ppv_ips": 0.405},
|
||||
"vector_sum": {"ips": 14.86736},
|
||||
},
|
||||
"mic": {"pspl_dbl": 115.9},
|
||||
"recording": {"sample_rate_sps": 1024, "record_time_s": 3.0},
|
||||
}
|
||||
event_file_io.apply_bw_report_dict_to_event(ev, bw_report)
|
||||
assert ev.peak_values is not None
|
||||
assert ev.peak_values.tran == 9.84375
|
||||
assert ev.peak_values.vert == 0.305
|
||||
assert ev.peak_values.long == 0.405
|
||||
assert ev.peak_values.peak_vector_sum == 14.86736
|
||||
# MicL is converted dB → psi via _dbl_to_psi — just confirm non-zero
|
||||
assert ev.peak_values.micl is not None and ev.peak_values.micl > 0
|
||||
assert ev.sample_rate == 1024
|
||||
assert ev.rectime_seconds == 3.0
|
||||
|
||||
|
||||
def test_apply_bw_report_dict_overwrites_codec_peaks():
|
||||
"""The whole point of this helper: bw_report wins over whatever the
|
||||
codec produced. This is what the 2026-05-22 prod backfill missed —
|
||||
DB peaks got overwritten with codec output (incl. PVS=0 on the
|
||||
three top events) when they should have stayed bw_report-overlaid."""
|
||||
from minimateplus.models import PeakValues
|
||||
ev = Event(index=0)
|
||||
# Simulate codec output that's clearly wrong (incomplete decode):
|
||||
ev.peak_values = PeakValues(
|
||||
tran=2.09, vert=0.0, long=0.0, peak_vector_sum=0.0,
|
||||
)
|
||||
bw_report = {
|
||||
"peaks": {
|
||||
"tran": {"ppv_ips": 9.84},
|
||||
"vert": {"ppv_ips": 4.95},
|
||||
"long": {"ppv_ips": 8.05},
|
||||
"vector_sum": {"ips": 14.95},
|
||||
},
|
||||
}
|
||||
event_file_io.apply_bw_report_dict_to_event(ev, bw_report)
|
||||
assert ev.peak_values.tran == 9.84
|
||||
assert ev.peak_values.vert == 4.95
|
||||
assert ev.peak_values.long == 8.05
|
||||
assert ev.peak_values.peak_vector_sum == 14.95
|
||||
|
||||
|
||||
def test_apply_bw_report_dict_no_op_on_empty():
|
||||
"""None / empty dict / missing keys should leave Event untouched."""
|
||||
from minimateplus.models import PeakValues
|
||||
for empty in (None, {}, {"peaks": {}}, {"peaks": {"tran": {}}}):
|
||||
ev = Event(index=0)
|
||||
ev.peak_values = PeakValues(tran=1.0, vert=2.0, long=3.0)
|
||||
event_file_io.apply_bw_report_dict_to_event(ev, empty)
|
||||
# Unchanged
|
||||
assert ev.peak_values.tran == 1.0
|
||||
assert ev.peak_values.vert == 2.0
|
||||
assert ev.peak_values.long == 3.0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if pytest is not None:
|
||||
pytest.main([__file__, "-v"])
|
||||
@@ -458,3 +626,12 @@ if __name__ == "__main__":
|
||||
failed += 1
|
||||
print(f"\n{passed} passed, {failed} failed")
|
||||
sys.exit(0 if failed == 0 else 1)
|
||||
|
||||
|
||||
def test_peaks_from_samples_uses_32000_full_scale():
|
||||
"""`_peaks_from_samples` must use the same 32000-count geo full scale as
|
||||
the .h5 writer, or sidecar peaks disagree with the plotted waveform by
|
||||
2.3%. See test_event_hdf5.test_geo_full_scale_count_is_32000."""
|
||||
from minimateplus.event_file_io import _peaks_from_samples
|
||||
pv = _peaks_from_samples({"Tran": [32000], "Vert": [0], "Long": [0], "MicL": []})
|
||||
assert abs(pv.tran - 10.0) < 1e-4
|
||||
@@ -99,8 +99,14 @@ def test_hdf5_round_trip_preserves_metadata(tmp_path: Path):
|
||||
|
||||
|
||||
def test_hdf5_samples_in_physical_units_normal_range(tmp_path: Path):
|
||||
"""Vert hits ADC full-scale (32767) → with Normal range FS=10 in/s,
|
||||
the HDF5 sample value should be ≈ 10 * 32767/32768 in/s."""
|
||||
"""Vert hits 32767 ADC counts → with Normal range FS=10 in/s that is
|
||||
``10 * 32767/32000`` in/s.
|
||||
|
||||
Geo full scale is 32000 counts, not 32768 (see
|
||||
test_geo_full_scale_count_is_32000), so 32767 counts sits slightly
|
||||
ABOVE nominal full scale -- the ADC has headroom past 10.000 in/s,
|
||||
which is why Blastware reports peaks like 10.14 in/s. This test
|
||||
previously asserted the 32768 scale and was wrong by 2.3%."""
|
||||
ev = _make_event_with_samples()
|
||||
h5 = tmp_path / "n.h5"
|
||||
event_hdf5.write_event_hdf5(h5, ev, serial="BE11529", geo_range="normal")
|
||||
@@ -110,7 +116,7 @@ def test_hdf5_samples_in_physical_units_normal_range(tmp_path: Path):
|
||||
assert vert.dtype.name == "float32"
|
||||
assert max(abs(v) for v in vert) > 9.99 # full-scale ≈ 10.0
|
||||
# The dirac was at n//2 → 32767 ADC counts.
|
||||
expected_peak = 10.0 * 32767 / 32768
|
||||
expected_peak = 10.0 * 32767 / 32000
|
||||
assert abs(max(vert) - expected_peak) < 1e-3
|
||||
|
||||
|
||||
@@ -122,7 +128,7 @@ def test_hdf5_samples_in_physical_units_sensitive_range(tmp_path: Path):
|
||||
data = event_hdf5.read_event_hdf5(h5)
|
||||
|
||||
vert = data["samples"]["Vert"]
|
||||
expected_peak = 1.250 * 32767 / 32768
|
||||
expected_peak = 1.250 * 32767 / 32000
|
||||
assert abs(max(vert) - expected_peak) < 1e-4
|
||||
|
||||
|
||||
@@ -294,3 +300,35 @@ if __name__ == "__main__":
|
||||
failed += 1
|
||||
print(f"\n{passed} passed, {failed} failed")
|
||||
sys.exit(0 if failed == 0 else 1)
|
||||
|
||||
|
||||
# ── Geophone full-scale count ───────────────────────────────────────────────
|
||||
|
||||
def test_geo_full_scale_count_is_32000():
|
||||
"""Geo full scale is 32000 ADC counts, not 32768.
|
||||
|
||||
The verified body codec emits geo samples in 16-count units with a
|
||||
documented LSB of exactly 0.005 in/s, and ``decoded_to_adc_counts``
|
||||
multiplies by 16 — so one ADC count is 0.005/16 in/s and Normal range
|
||||
(10.000 in/s) is 10.0 / (0.005/16) = 32000 counts.
|
||||
|
||||
Using 32768 made every geophone reading 2.3% low (1 - 32000/32768).
|
||||
Confirmed 2026-08-25 against 216 channel comparisons with preserved
|
||||
Blastware ASCII exports: 32000 → 216/216 exact within 1 LSB;
|
||||
32768 → 151/216, worst error 0.238 in/s on a 10 in/s event.
|
||||
"""
|
||||
from sfm.event_hdf5 import _GEO_INT16_FS
|
||||
assert _GEO_INT16_FS == 32000.0
|
||||
|
||||
|
||||
def test_samples_to_float_lsb_is_exactly_5_milli_ips():
|
||||
"""One decoder unit (= 16 ADC counts) must be exactly 0.005 in/s."""
|
||||
from sfm.event_hdf5 import _samples_to_float
|
||||
out = _samples_to_float([16], 10.0)
|
||||
assert abs(float(out[0]) - 0.005) < 1e-9
|
||||
|
||||
|
||||
def test_samples_to_float_full_scale_count_maps_to_full_scale():
|
||||
from sfm.event_hdf5 import _samples_to_float
|
||||
assert abs(float(_samples_to_float([32000], 10.0)[0]) - 10.0) < 1e-4
|
||||
assert abs(float(_samples_to_float([32000], 1.25)[0]) - 1.25) < 1e-5
|
||||
@@ -0,0 +1,33 @@
|
||||
import datetime
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event, Timestamp
|
||||
|
||||
|
||||
def _ins(db, key, serial, pvs, ts):
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex(key)
|
||||
ev.timestamp = ts
|
||||
# peak_vector_sum comes from peak_values; simplest: insert then UPDATE pvs directly
|
||||
db.insert_events([ev], serial=serial)
|
||||
row = [r for r in db.query_events(serial=serial) if r["waveform_key"] == key][0]
|
||||
import sqlite3
|
||||
with sqlite3.connect(db.db_path) as c:
|
||||
c.execute("UPDATE events SET peak_vector_sum=? WHERE id=?", (pvs, row["id"]))
|
||||
return row["id"]
|
||||
|
||||
|
||||
def test_find_twins_matches_same_serial_pvs_near_time(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
base = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=20, minute=19, second=5)
|
||||
twin = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=20, minute=19, second=45)
|
||||
far = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=21, minute=0, second=0)
|
||||
# d needs a timestamp distinct from `twin` (UNIQUE(serial, timestamp) would
|
||||
# otherwise collide with b and UPSERT onto its row instead of inserting a
|
||||
# new one) while staying near `base` in time.
|
||||
near = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=20, minute=19, second=44)
|
||||
a = _ins(db, "01110001", "BE1", 0.4763, base)
|
||||
b = _ins(db, "01110002", "BE1", 0.4763, twin) # twin: same serial+pvs, 40s apart
|
||||
c = _ins(db, "01110003", "BE1", 0.4763, far) # same pvs but >window away
|
||||
d = _ins(db, "01110004", "BE1", 0.9999, near) # near time but different pvs
|
||||
ids = {r["id"] for r in db.find_twins(a, window_seconds=300)}
|
||||
assert ids == {b}
|
||||
@@ -0,0 +1,645 @@
|
||||
"""
|
||||
test_histogram_codec.py — regression locks for the histogram body codec.
|
||||
|
||||
The codec is verified byte-exact against BW's ASCII export across the
|
||||
in-repo histogram fixture bundle. Each test cross-checks decoded
|
||||
binary fields against the corresponding .TXT row.
|
||||
|
||||
Run:
|
||||
python -m pytest tests/test_histogram_codec.py -q
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from minimateplus.blastware_file import _WAVEFORM_HEADER_SIZE
|
||||
from minimateplus.histogram_codec import (
|
||||
_BLOCK_SIZE,
|
||||
decode_histogram_body,
|
||||
decode_histogram_body_full,
|
||||
geo_count_to_ins,
|
||||
half_period_to_hz,
|
||||
walk_body,
|
||||
)
|
||||
from minimateplus.waveform_codec import mic_count_to_db
|
||||
|
||||
|
||||
_FIXTURE_DIR = Path(__file__).resolve().parent.parent / "example-events" / "histogram"
|
||||
|
||||
|
||||
def _extract_body(path: Path) -> bytes:
|
||||
"""Locate the body of a BW event file — bytes between the STRT
|
||||
record and the 26-byte footer."""
|
||||
raw = path.read_bytes()
|
||||
body_start = _WAVEFORM_HEADER_SIZE + 21
|
||||
pos = body_start
|
||||
footer_pos = -1
|
||||
while True:
|
||||
pos = raw.find(b"\x0e\x08", pos)
|
||||
if pos < 0 or pos + 26 > len(raw):
|
||||
break
|
||||
yr = (raw[pos + 4] << 8) | raw[pos + 5]
|
||||
if 2015 <= yr <= 2050:
|
||||
footer_pos = pos
|
||||
break
|
||||
pos += 1
|
||||
if footer_pos < 0:
|
||||
footer_pos = len(raw) - 26
|
||||
return raw[body_start:footer_pos]
|
||||
|
||||
|
||||
def _parse_txt_rows(path: Path) -> list[tuple[str, list]]:
|
||||
"""Parse a histogram .TXT into ``[(time_str, [10 col values]), …]``.
|
||||
|
||||
Special tokens:
|
||||
- ``">100"`` (the BW-display sentinel for freq > 100 Hz) → ``None``
|
||||
- non-numeric → ``None``
|
||||
"""
|
||||
text = path.read_text()
|
||||
lines = text.splitlines()
|
||||
hdr = None
|
||||
for i, line in enumerate(lines):
|
||||
if re.match(r"^Tran\s+", line.strip()):
|
||||
hdr = i + 3 # skip 2-row header + units row
|
||||
break
|
||||
if hdr is None:
|
||||
return []
|
||||
rows: list[tuple[str, list]] = []
|
||||
for line in lines[hdr:]:
|
||||
parts = line.split("\t")
|
||||
if len(parts) != 11:
|
||||
continue
|
||||
vals: list = []
|
||||
for p in parts[1:]:
|
||||
s = p.strip()
|
||||
if s.startswith(">"):
|
||||
vals.append(None) # ">100 Hz" sentinel
|
||||
continue
|
||||
try:
|
||||
vals.append(float(s))
|
||||
except ValueError:
|
||||
vals.append(None)
|
||||
rows.append((parts[0].strip(), vals))
|
||||
return rows
|
||||
|
||||
|
||||
# ── Block-walker plumbing ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fixture", [
|
||||
"N844L20G.630H",
|
||||
"N844L21H.2R0H",
|
||||
"N844L6Z8.ZR0H",
|
||||
"N844L6XE.BH0H",
|
||||
"N844L23B.ND0H",
|
||||
])
|
||||
def test_walk_body_returns_records(fixture: str):
|
||||
"""Walker yields at least one valid block per fixture."""
|
||||
path = _FIXTURE_DIR / fixture
|
||||
if not path.exists():
|
||||
pytest.skip(f"fixture missing: {path}")
|
||||
records = walk_body(_extract_body(path))
|
||||
assert len(records) > 100, f"expected hundreds of blocks, got {len(records)}"
|
||||
|
||||
|
||||
def test_walk_body_record_count_matches_txt_intervals():
|
||||
"""Block count should match the .TXT interval count (off-by-one
|
||||
at the tail is acceptable — last interval may be truncated at
|
||||
recording stop)."""
|
||||
bin_path = _FIXTURE_DIR / "N844L20G.630H"
|
||||
txt_path = _FIXTURE_DIR / "N844L20G_630H_ASCII.TXT"
|
||||
if not bin_path.exists() or not txt_path.exists():
|
||||
pytest.skip("fixture missing")
|
||||
records = walk_body(_extract_body(bin_path))
|
||||
txt_rows = _parse_txt_rows(txt_path)
|
||||
# Allow off-by-one (final block may have been mid-write at stop)
|
||||
assert abs(len(records) - len(txt_rows)) <= 1, (
|
||||
f"binary {len(records)} blocks vs TXT {len(txt_rows)} intervals"
|
||||
)
|
||||
|
||||
|
||||
def test_walk_body_segment_id_increments_every_256_blocks():
|
||||
"""Segment ID advances 0→1→2→… after every 256 blocks within
|
||||
one event."""
|
||||
path = _FIXTURE_DIR / "N844L20G.630H"
|
||||
if not path.exists():
|
||||
pytest.skip("fixture missing")
|
||||
records = walk_body(_extract_body(path))
|
||||
# Group by segment_id and verify counts make sense
|
||||
from collections import Counter
|
||||
seg_counts = Counter(r["segment_id"] for r in records)
|
||||
# First 3 segments should each have exactly 256 blocks (N844L20G has
|
||||
# 791 blocks → 256+256+256+23 → segments 0/1/2/3)
|
||||
assert seg_counts[0] == 256
|
||||
assert seg_counts[1] == 256
|
||||
assert seg_counts[2] == 256
|
||||
assert seg_counts[3] == len(records) - 3 * 256
|
||||
|
||||
|
||||
# ── Field-by-field decode verification against .TXT ground truth ─────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fixture", [
|
||||
"N844L20G.630H",
|
||||
"N844L6Z8.ZR0H",
|
||||
"N844L6XE.BH0H",
|
||||
"N844L23B.ND0H",
|
||||
])
|
||||
def test_decoded_geo_peaks_match_txt(fixture: str):
|
||||
"""For every block, decoded Tran/Vert/Long peak (count × 0.005)
|
||||
matches the corresponding .TXT cell."""
|
||||
bin_path = _FIXTURE_DIR / fixture
|
||||
txt_path = _FIXTURE_DIR / (fixture.replace(".", "_") + "_ASCII.TXT")
|
||||
if not bin_path.exists() or not txt_path.exists():
|
||||
pytest.skip("fixture missing")
|
||||
records = walk_body(_extract_body(bin_path))
|
||||
txt_rows = _parse_txt_rows(txt_path)
|
||||
n = min(len(records), len(txt_rows))
|
||||
assert n > 0
|
||||
for i in range(n):
|
||||
rec = records[i]
|
||||
_ts, txt = txt_rows[i]
|
||||
# TXT cols 0/2/4 are T/V/L peak in in/s
|
||||
for slot, key in (("T", "t_peak"), ("V", "v_peak"), ("L", "l_peak")):
|
||||
col = {"T": 0, "V": 2, "L": 4}[slot]
|
||||
decoded_ips = geo_count_to_ins(rec[key])
|
||||
expected = txt[col]
|
||||
assert abs(decoded_ips - expected) < 0.0005, (
|
||||
f"{fixture} block {i} {slot}_peak: "
|
||||
f"decoded={decoded_ips:.4f} vs txt={expected:.4f}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fixture", [
|
||||
"N844L6Z8.ZR0H",
|
||||
"N844L6XE.BH0H",
|
||||
])
|
||||
def test_decoded_geo_freqs_match_txt(fixture: str):
|
||||
"""Decoded half-period → Hz matches the .TXT freq column for blocks
|
||||
where the freq is in-range (not the `>100 Hz` sentinel)."""
|
||||
bin_path = _FIXTURE_DIR / fixture
|
||||
txt_path = _FIXTURE_DIR / (fixture.replace(".", "_") + "_ASCII.TXT")
|
||||
if not bin_path.exists() or not txt_path.exists():
|
||||
pytest.skip("fixture missing")
|
||||
records = walk_body(_extract_body(bin_path))
|
||||
txt_rows = _parse_txt_rows(txt_path)
|
||||
n = min(len(records), len(txt_rows))
|
||||
for i in range(n):
|
||||
rec = records[i]
|
||||
_ts, txt = txt_rows[i]
|
||||
for slot, key, col in (("T", "t_halfp", 1), ("V", "v_halfp", 3), ("L", "l_halfp", 5)):
|
||||
decoded_hz = half_period_to_hz(rec[key])
|
||||
expected = txt[col]
|
||||
if expected is None:
|
||||
# TXT shows `>100 Hz` — codec should also yield None
|
||||
assert decoded_hz is None or decoded_hz > 100, (
|
||||
f"{fixture} block {i} {slot}_freq: codec says "
|
||||
f"{decoded_hz} but TXT says >100"
|
||||
)
|
||||
continue
|
||||
# TXT rounds; allow ±1 Hz
|
||||
assert decoded_hz is not None
|
||||
assert abs(decoded_hz - expected) < 1.0, (
|
||||
f"{fixture} block {i} {slot}_freq: "
|
||||
f"decoded={decoded_hz:.2f} Hz vs txt={expected:.2f} Hz"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fixture", [
|
||||
"N844L6XE.BH0H",
|
||||
"N844L23B.ND0H",
|
||||
"N844L6Z8.ZR0H",
|
||||
])
|
||||
def test_decoded_mic_db_matches_txt(fixture: str):
|
||||
"""Decoded MicL peak count → dB(L) via mic_count_to_db matches
|
||||
the .TXT dB(L) column."""
|
||||
bin_path = _FIXTURE_DIR / fixture
|
||||
txt_path = _FIXTURE_DIR / (fixture.replace(".", "_") + "_ASCII.TXT")
|
||||
if not bin_path.exists() or not txt_path.exists():
|
||||
pytest.skip("fixture missing")
|
||||
records = walk_body(_extract_body(bin_path))
|
||||
txt_rows = _parse_txt_rows(txt_path)
|
||||
n = min(len(records), len(txt_rows))
|
||||
for i in range(n):
|
||||
rec = records[i]
|
||||
_ts, txt = txt_rows[i]
|
||||
# TXT col 8 = MicL dB(L)
|
||||
decoded_db = mic_count_to_db(rec["m_peak"])
|
||||
expected = txt[8]
|
||||
if expected is None:
|
||||
continue
|
||||
# BW rounds to 1 decimal place for display. Tolerance 0.1 dB
|
||||
# absorbs both rounding modes (truncate vs round-half-even).
|
||||
assert abs(decoded_db - expected) < 0.1, (
|
||||
f"{fixture} block {i} M_dB: "
|
||||
f"decoded={decoded_db:.2f} dB vs txt={expected:.2f} dB"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fixture", [
|
||||
"N844L20G.630H",
|
||||
"N844L6Z8.ZR0H",
|
||||
])
|
||||
def test_decoded_mic_freq_matches_txt(fixture: str):
|
||||
"""Decoded MicL half-period → freq matches the .TXT col 9 freq."""
|
||||
bin_path = _FIXTURE_DIR / fixture
|
||||
txt_path = _FIXTURE_DIR / (fixture.replace(".", "_") + "_ASCII.TXT")
|
||||
if not bin_path.exists() or not txt_path.exists():
|
||||
pytest.skip("fixture missing")
|
||||
records = walk_body(_extract_body(bin_path))
|
||||
txt_rows = _parse_txt_rows(txt_path)
|
||||
n = min(len(records), len(txt_rows))
|
||||
for i in range(n):
|
||||
rec = records[i]
|
||||
_ts, txt = txt_rows[i]
|
||||
decoded_hz = half_period_to_hz(rec["m_halfp"])
|
||||
expected = txt[9]
|
||||
if expected is None:
|
||||
assert decoded_hz is None or decoded_hz > 100
|
||||
continue
|
||||
assert decoded_hz is not None
|
||||
assert abs(decoded_hz - expected) < 1.0, (
|
||||
f"{fixture} block {i} M_freq: "
|
||||
f"decoded={decoded_hz:.2f} Hz vs txt={expected:.2f} Hz"
|
||||
)
|
||||
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_decode_histogram_body_returns_four_channels():
|
||||
"""The public API returns the standard 4-channel dict shape."""
|
||||
path = _FIXTURE_DIR / "N844L20G.630H"
|
||||
if not path.exists():
|
||||
pytest.skip("fixture missing")
|
||||
decoded = decode_histogram_body(_extract_body(path))
|
||||
assert decoded is not None
|
||||
assert set(decoded.keys()) == {"Tran", "Vert", "Long", "MicL"}
|
||||
# All channels same length (one value per histogram interval)
|
||||
n = len(decoded["Tran"])
|
||||
assert all(len(decoded[ch]) == n for ch in ("Vert", "Long", "MicL"))
|
||||
assert n > 100
|
||||
|
||||
|
||||
def test_decode_histogram_body_returns_none_for_non_histogram():
|
||||
"""A waveform-mode body (starts with 00 02 00) doesn't decode as
|
||||
a histogram body."""
|
||||
fake_waveform_body = b"\x00\x02\x00" + b"\x00" * 100
|
||||
assert decode_histogram_body(fake_waveform_body) is None
|
||||
|
||||
|
||||
def test_decode_histogram_body_returns_none_for_garbage():
|
||||
"""Bytes that don't form valid blocks return None."""
|
||||
assert decode_histogram_body(b"\xff" * 256) is None
|
||||
|
||||
|
||||
def test_decode_histogram_body_full_preserves_frequency_data():
|
||||
"""The structured-record API preserves the per-channel half-period
|
||||
fields that the flat-channel API drops."""
|
||||
path = _FIXTURE_DIR / "N844L20G.630H"
|
||||
if not path.exists():
|
||||
pytest.skip("fixture missing")
|
||||
records = decode_histogram_body_full(_extract_body(path))
|
||||
assert records is not None
|
||||
r0 = records[0]
|
||||
expected_fields = {
|
||||
"segment_id", "block_ctr",
|
||||
"t_peak", "t_halfp", "v_peak", "v_halfp",
|
||||
"l_peak", "l_halfp", "m_peak", "m_halfp",
|
||||
"meta_var",
|
||||
}
|
||||
assert set(r0.keys()) >= expected_fields
|
||||
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_half_period_to_hz_sentinel():
|
||||
"""Half-period ≤ 5 returns None (the `>100 Hz` sentinel)."""
|
||||
assert half_period_to_hz(5) is None
|
||||
assert half_period_to_hz(1) is None
|
||||
# halfp=6 gives 512/6 = 85.3 Hz — below the >100 threshold
|
||||
assert half_period_to_hz(6) == pytest.approx(85.33, abs=0.01)
|
||||
|
||||
|
||||
def test_geo_count_to_ins_scale():
|
||||
"""1 count = 0.005 in/s at Normal range."""
|
||||
assert geo_count_to_ins(1) == pytest.approx(0.005)
|
||||
assert geo_count_to_ins(10) == pytest.approx(0.050)
|
||||
assert geo_count_to_ins(0) == 0.0
|
||||
|
||||
|
||||
# ── Regression: peak is uint8 byte[N], NOT uint16 LE byte[N:N+2] ────────────
|
||||
#
|
||||
# Block taken verbatim from K558LKZU.RE0H (BE9558) interval 12 — a real
|
||||
# field event where the Tran channel had developed a DC offset and was
|
||||
# producing sub-Hz drift content the device couldn't characterize.
|
||||
# The annotation byte at [7] = 0xd2 is non-zero in that case. The
|
||||
# legacy codec read [6:8] as uint16 LE, producing T_peak = 53763 →
|
||||
# 268 in/s — physically impossible and 35× too high for the actual
|
||||
# 0.015 in/s value (T_lo = 3 alone gives the correct count).
|
||||
# Verified against the paired BW ASCII export.
|
||||
_K558_INTERVAL_12_BLOCK = bytes.fromhex(
|
||||
"00 00 0c 01 0a 00 03 d2 45 00 02 00 02 00 02 00"
|
||||
"02 00 10 00 06 00 00 00 0e 91 2f 00 1e 0a 00 00".replace(" ", "")
|
||||
)
|
||||
|
||||
|
||||
def test_extension_byte_does_not_inflate_peak():
|
||||
"""The byte after each peak must NOT contribute to the peak count.
|
||||
|
||||
Still true, but for a different reason than originally recorded: the
|
||||
block is uniformly **big-endian**, so T_peak is uint16 BE at [5:7]
|
||||
(= 3 here) and the 0xd2 at [7] is the HIGH BYTE of the big-endian
|
||||
half-period at [7:9], not an "annotation" field. Reading the peak as
|
||||
uint16 LE at [6:8] gave 53763 → 268 in/s, which is what this test was
|
||||
written to prevent.
|
||||
"""
|
||||
body = _K558_INTERVAL_12_BLOCK
|
||||
records = decode_histogram_body_full(body)
|
||||
assert records is not None
|
||||
assert len(records) == 1
|
||||
r = records[0]
|
||||
assert r["t_peak"] == 3, f"T_peak should be 3, got {r['t_peak']}"
|
||||
assert r["v_peak"] == 2
|
||||
assert r["l_peak"] == 2
|
||||
assert r["m_peak"] == 16
|
||||
# Half-period is uint16 BE — 0xd245 = 53829 samples → 0.0095 Hz, which
|
||||
# is exactly the sub-Hz drift BW rendered as "<1.0" for this interval.
|
||||
assert r["t_halfp"] == 0xd245
|
||||
assert half_period_to_hz(r["t_halfp"]) < 1.0
|
||||
assert r["m_halfp"] == 6 # → 85.3 Hz
|
||||
|
||||
|
||||
def test_extension_byte_decoded_to_correct_in_s():
|
||||
"""End-to-end: the channel-grouped output for the K558 ext block
|
||||
should give T = 3 counts = 0.015 in/s, not 53763 counts = 268 in/s."""
|
||||
channels = decode_histogram_body(_K558_INTERVAL_12_BLOCK)
|
||||
assert channels is not None
|
||||
assert channels["Tran"] == [3]
|
||||
assert geo_count_to_ins(channels["Tran"][0]) == pytest.approx(0.015)
|
||||
assert channels["Vert"] == [2]
|
||||
assert channels["Long"] == [2]
|
||||
assert channels["MicL"] == [16]
|
||||
|
||||
|
||||
# ── Big-endian block layout + terminal block (2026-08-25) ───────────────────
|
||||
#
|
||||
# Verified against 1211 production histograms paired with their Blastware
|
||||
# ASCII exports: 1211/1211 decode exactly (interval count + every
|
||||
# per-interval peak), and 842,442 per-interval frequency comparisons match
|
||||
# with zero mismatches.
|
||||
|
||||
def _mk_block(t_peak=3, t_halfp=69, v_peak=2, v_halfp=69, l_peak=2, l_halfp=69,
|
||||
m_peak=16, m_halfp=6, seg=0, ctr=256, tail=b"\x1e\x0a\x00\x00",
|
||||
b22=0x00):
|
||||
"""Build one synthetic 32-byte histogram block, big-endian throughout."""
|
||||
b = bytearray(32)
|
||||
b[0] = 0x00
|
||||
b[1] = seg
|
||||
b[2], b[3] = ctr & 0xFF, (ctr >> 8) & 0xFF # block_ctr is uint16 LE
|
||||
b[4] = 0x0A # marker, uint8
|
||||
for off, val in ((5, t_peak), (7, t_halfp), (9, v_peak), (11, v_halfp),
|
||||
(13, l_peak), (15, l_halfp), (17, m_peak), (19, m_halfp)):
|
||||
b[off], b[off + 1] = (val >> 8) & 0xFF, val & 0xFF # uint16 BE
|
||||
b[22] = b22
|
||||
b[28:32] = tail
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def test_geo_peak_is_uint16_be_not_uint8():
|
||||
"""A peak above the uint8 ceiling (255 counts = 1.275 in/s) must decode.
|
||||
|
||||
Real example: BE18193/T193LQ9K.OE0H's final interval reads 8.270 in/s
|
||||
in the BW export = 1654 counts = 0x0676, which needs both bytes.
|
||||
Reading only byte[6] gave 0x76 = 118 = 0.590 in/s.
|
||||
"""
|
||||
r = decode_histogram_body_full(_mk_block(t_peak=1654))
|
||||
assert r is not None and len(r) == 1
|
||||
assert r[0]["t_peak"] == 1654
|
||||
assert geo_count_to_ins(r[0]["t_peak"]) == pytest.approx(8.27)
|
||||
|
||||
|
||||
def test_half_period_is_uint16_be():
|
||||
"""Half-period spans two bytes big-endian; a large value is sub-Hz."""
|
||||
r = decode_histogram_body_full(_mk_block(t_halfp=53829))
|
||||
assert r[0]["t_halfp"] == 53829
|
||||
assert half_period_to_hz(53829) == pytest.approx(512 / 53829)
|
||||
|
||||
|
||||
def test_terminal_block_tail_is_accepted():
|
||||
"""The LAST block of a histogram stream carries tail `9c 06 00 42`
|
||||
instead of `1e 0a 00 00`. Rejecting it dropped the final interval —
|
||||
which is where the event peak often lives. Observed in 1206 of 1211
|
||||
production histograms, always after every standard-tail block."""
|
||||
body = _mk_block(ctr=256) + _mk_block(ctr=257, t_peak=1654,
|
||||
tail=b"\x9c\x06\x00\x42")
|
||||
ch = decode_histogram_body(body)
|
||||
assert ch is not None
|
||||
assert ch["Tran"] == [3, 1654], "terminal block must not be dropped"
|
||||
|
||||
|
||||
def test_terminal_block_exempt_from_byte22_constraint():
|
||||
"""Terminal blocks carry arbitrary bytes at [22:24]; only standard
|
||||
blocks hold 0x00 there. Requiring it dropped the final interval on
|
||||
files such as BE18438/T438LO30.DC0H."""
|
||||
body = _mk_block(ctr=256) + _mk_block(ctr=257, tail=b"\x9c\x06\x00\x42",
|
||||
b22=0x01)
|
||||
ch = decode_histogram_body(body)
|
||||
assert ch is not None and len(ch["Tran"]) == 2
|
||||
|
||||
|
||||
def test_standard_block_accepts_nonzero_byte22():
|
||||
"""block[22] is NOT a constant and must not be tested.
|
||||
|
||||
It was documented as always 0x00, but it carries data on loud blocks.
|
||||
Rejecting those threw away the interval holding the event peak:
|
||||
BE18350/T350L7HR.NL0H block 92 has block[22]=0x26 and a Tran peak of
|
||||
0x0563 = 1379 counts = 6.895 in/s — exactly the device-reported PPV —
|
||||
while the file as a whole decoded to 0.015 in/s.
|
||||
|
||||
block[0]==0x00, block[4]==0x0A and the 4-byte tail are six bytes of
|
||||
constraint, which is what keeps trailer content out.
|
||||
"""
|
||||
ch = decode_histogram_body(_mk_block(t_peak=1379, b22=0x26))
|
||||
assert ch is not None
|
||||
assert ch["Tran"] == [1379]
|
||||
assert geo_count_to_ins(ch["Tran"][0]) == pytest.approx(6.895)
|
||||
|
||||
|
||||
def test_marker_is_single_byte_not_uint16():
|
||||
"""block[4] alone is the 0x0A marker. Treating [4:6] as a uint16 LE
|
||||
marker forced block[5] to zero, which capped every geo peak at 255
|
||||
counts — block[5] is the peak's high byte."""
|
||||
r = decode_histogram_body_full(_mk_block(t_peak=0x0676))
|
||||
assert r is not None, "block[5] != 0 must not disqualify the block"
|
||||
assert r[0]["t_peak"] == 0x0676
|
||||
|
||||
|
||||
# ── Multi-interval block variant (2026-08-26) ───────────────────────────────
|
||||
#
|
||||
# When the histogram interval is SHORTER than one minute the device packs
|
||||
# several intervals into one block, so that every block still covers exactly
|
||||
# one minute of data:
|
||||
#
|
||||
# interval intervals/block stride
|
||||
# 1 min 1 32 (the standard big-endian block)
|
||||
# 15 s 4 92
|
||||
# 2 s 30 612
|
||||
#
|
||||
# stride = 12 + n_intervals * 20
|
||||
#
|
||||
# Block layout:
|
||||
# [0] 0x00
|
||||
# [1] segment_id (256 blocks per segment)
|
||||
# [2:4] block_ctr uint16 LE
|
||||
# [4] 0x0a marker
|
||||
# [5] 0x00
|
||||
# [6 ...] n x 20-byte interval records, each 8 x uint16 LITTLE-endian:
|
||||
# T_peak, T_halfp, V_peak, V_halfp,
|
||||
# L_peak, L_halfp, M_peak, M_halfp
|
||||
# followed by 2 words (first is 0x0000)
|
||||
# [-6:] 6-byte block trailer
|
||||
#
|
||||
# NOTE the endianness flip: the standard 32-byte block is big-endian, this
|
||||
# variant is little-endian.
|
||||
#
|
||||
# Ground truth: BE9440/K440L3AQ.T70H (15 s intervals, 5,710 of them) decodes
|
||||
# with 17,130/17,130 geo peak counts, 22,840/22,840 frequencies and
|
||||
# 5,710/5,710 mic dB(L) values matching its Blastware ASCII export exactly.
|
||||
|
||||
from minimateplus.histogram_codec import ( # noqa: E402
|
||||
detect_multi_interval_stride,
|
||||
walk_multi_interval_blocks,
|
||||
)
|
||||
|
||||
|
||||
def _mk_multi_block(intervals, seg=0, ctr=256):
|
||||
"""Build one multi-interval block from a list of 8-tuples."""
|
||||
b = bytearray()
|
||||
b += bytes([0x00, seg])
|
||||
b += int(ctr).to_bytes(2, "little")
|
||||
b += bytes([0x0A, 0x00])
|
||||
for iv in intervals:
|
||||
for v in iv:
|
||||
b += int(v).to_bytes(2, "little")
|
||||
b += (0).to_bytes(2, "little")
|
||||
b += (5).to_bytes(2, "little")
|
||||
b += bytes(6)
|
||||
assert len(b) == 12 + 20 * len(intervals)
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def test_stride_is_twelve_plus_twenty_per_interval():
|
||||
for n in (4, 30):
|
||||
ivs = [(1, 1, 2, 2, 3, 3, 4, 4)] * n
|
||||
body = _mk_multi_block(ivs, ctr=256) + _mk_multi_block(ivs, ctr=257)
|
||||
assert detect_multi_interval_stride(body) == 12 + 20 * n
|
||||
|
||||
|
||||
def test_multi_interval_block_decodes_all_four_channels():
|
||||
ivs = [(1, 1, 2, 2, 3, 3, 4, 4), (5, 6, 7, 8, 9, 10, 11, 12)]
|
||||
body = _mk_multi_block(ivs) + _mk_multi_block(ivs, ctr=257)
|
||||
recs = walk_multi_interval_blocks(body)
|
||||
assert len(recs) == 4
|
||||
r = recs[0]
|
||||
assert (r["t_peak"], r["v_peak"], r["l_peak"], r["m_peak"]) == (1, 2, 3, 4)
|
||||
assert (r["t_halfp"], r["v_halfp"], r["l_halfp"], r["m_halfp"]) == (1, 2, 3, 4)
|
||||
assert recs[1]["t_peak"] == 5 and recs[1]["m_halfp"] == 12
|
||||
|
||||
|
||||
def test_multi_interval_values_are_little_endian():
|
||||
"""The standard 32-byte block is big-endian; this variant is not.
|
||||
|
||||
A peak of 0x0100 must decode as 256, not 1.
|
||||
"""
|
||||
ivs = [(0x0100, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1)]
|
||||
body = _mk_multi_block(ivs) + _mk_multi_block(ivs, ctr=257)
|
||||
assert walk_multi_interval_blocks(body)[0]["t_peak"] == 0x0100
|
||||
|
||||
|
||||
def test_decode_histogram_body_falls_back_to_the_variant():
|
||||
ivs = [(1, 1, 2, 2, 3, 3, 4, 4)] * 4
|
||||
body = _mk_multi_block(ivs) + _mk_multi_block(ivs, ctr=257)
|
||||
ch = decode_histogram_body(body)
|
||||
assert ch is not None
|
||||
assert len(ch["Tran"]) == 8
|
||||
assert ch["Long"][0] == 3
|
||||
|
||||
|
||||
def test_standard_blocks_still_take_precedence():
|
||||
"""A body of standard 32-byte blocks must not be re-read as the variant."""
|
||||
std = _mk_block(t_peak=7) + _mk_block(t_peak=9, ctr=257,
|
||||
tail=b"\x9c\x06\x00\x42")
|
||||
ch = decode_histogram_body(std)
|
||||
assert ch is not None and ch["Tran"] == [7, 9]
|
||||
|
||||
|
||||
# ── Ground truth for the multi-interval variant ─────────────────────────────
|
||||
# Fixture is gitignored (like the rest of tests/fixtures); skips when absent.
|
||||
|
||||
_MULTI_FIXTURE = os.path.join(
|
||||
os.path.dirname(__file__), "fixtures", "histogram-multi-interval",
|
||||
"K440L3AQ.T70H",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not os.path.exists(_MULTI_FIXTURE),
|
||||
reason="multi-interval fixture not present")
|
||||
def test_multi_interval_matches_blastware_ascii_exactly():
|
||||
"""BE9440/K440L3AQ.T70H — 5,710 intervals at 15 s, 4 per 92-byte block.
|
||||
|
||||
Every geo peak, every frequency and every mic dB(L) in the file matches
|
||||
the Blastware ASCII export: 17,130 / 22,840 / 5,710 values, zero
|
||||
mismatches. Before this decoder the file produced nothing at all.
|
||||
"""
|
||||
import math
|
||||
import re as _re
|
||||
from minimateplus import blastware_file as _bwf
|
||||
|
||||
raw = open(_MULTI_FIXTURE, "rb").read()
|
||||
bs = _bwf._WAVEFORM_HEADER_SIZE + 21
|
||||
pos, fp = bs, -1
|
||||
while True:
|
||||
pos = raw.find(b"\x0e\x08", pos)
|
||||
if pos < 0 or pos + 26 > len(raw):
|
||||
break
|
||||
if 2015 <= ((raw[pos + 4] << 8) | raw[pos + 5]) <= 2050:
|
||||
fp = pos
|
||||
break
|
||||
pos += 1
|
||||
recs = walk_multi_interval_blocks(raw[bs:fp])
|
||||
|
||||
rows = []
|
||||
for line in open(_MULTI_FIXTURE + "_ASCII.TXT", errors="replace"):
|
||||
p = [x.strip() for x in line.split("\t")]
|
||||
if len(p) >= 11 and _re.match(r"^\d{2}:\d{2}:\d{2}$", p[0]):
|
||||
rows.append(p)
|
||||
|
||||
assert len(recs) == len(rows) == 5710
|
||||
|
||||
def want_count(x):
|
||||
return round(float(x) / 0.005)
|
||||
|
||||
for rec, row in zip(recs, rows):
|
||||
assert rec["t_peak"] == want_count(row[1])
|
||||
assert rec["v_peak"] == want_count(row[3])
|
||||
assert rec["l_peak"] == want_count(row[5])
|
||||
# mic dB(L)
|
||||
assert abs((81.94 + 20 * math.log10(rec["m_peak"])) - float(row[9])) <= 0.06
|
||||
# frequency: half-period <= 5 is BW's ">100 Hz" sentinel
|
||||
for hp, cell in ((rec["t_halfp"], row[2]), (rec["v_halfp"], row[4]),
|
||||
(rec["l_halfp"], row[6]), (rec["m_halfp"], row[10])):
|
||||
hz = None if hp <= 5 else 512.0 / hp
|
||||
if cell.startswith(">"):
|
||||
assert hz is None
|
||||
elif not cell.startswith("<"):
|
||||
assert hz is not None and abs(hz - float(cell)) <= max(0.55, float(cell) * 0.02)
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event, Timestamp, PeakValues
|
||||
|
||||
|
||||
def _event(waveform_key="0111abcd"):
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex(waveform_key)
|
||||
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"
|
||||
ev.peak_values = PeakValues(tran=0.075, vert=0.220, long=0.045,
|
||||
peak_vector_sum=0.231, micl=0.01)
|
||||
return ev
|
||||
|
||||
|
||||
def test_insert_stores_shape_from_record(tmp_path: Path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
ev = _event()
|
||||
rec = {ev._waveform_key.hex(): {
|
||||
"filename": "F.CE0W", "filesize": 10,
|
||||
"shape_crest_factor": 34.0, "shape_near_peak_count": 3,
|
||||
"shape_sample_count": 1024, "shape_axis": "Long"}}
|
||||
db.insert_events([ev], serial="BE1", waveform_records=rec)
|
||||
row = db.query_events(serial="BE1")[0]
|
||||
assert row["shape_crest_factor"] == 34.0
|
||||
assert row["shape_near_peak_count"] == 3
|
||||
assert row["shape_axis"] == "Long"
|
||||
|
||||
|
||||
def test_upsert_refreshes_shape_from_record(tmp_path: Path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
ev = _event()
|
||||
rec1 = {ev._waveform_key.hex(): {
|
||||
"shape_crest_factor": 10.0, "shape_near_peak_count": 1,
|
||||
"shape_sample_count": 512, "shape_axis": "Tran"}}
|
||||
db.insert_events([ev], serial="BE1", waveform_records=rec1)
|
||||
|
||||
ev2 = _event()
|
||||
rec2 = {ev2._waveform_key.hex(): {
|
||||
"shape_crest_factor": 22.5, "shape_near_peak_count": 7,
|
||||
"shape_sample_count": 2048, "shape_axis": "Vert"}}
|
||||
db.insert_events([ev2], serial="BE1", waveform_records=rec2)
|
||||
|
||||
row = db.query_events(serial="BE1")[0]
|
||||
assert row["shape_crest_factor"] == 22.5
|
||||
assert row["shape_near_peak_count"] == 7
|
||||
assert row["shape_sample_count"] == 2048
|
||||
assert row["shape_axis"] == "Vert"
|
||||
|
||||
|
||||
def test_upsert_preserves_shape_when_record_missing(tmp_path: Path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
ev = _event()
|
||||
rec1 = {ev._waveform_key.hex(): {
|
||||
"shape_crest_factor": 10.0, "shape_near_peak_count": 1,
|
||||
"shape_sample_count": 512, "shape_axis": "Tran"}}
|
||||
db.insert_events([ev], serial="BE1", waveform_records=rec1)
|
||||
|
||||
ev2 = _event() # re-import with no waveform_records (e.g. sample missing)
|
||||
db.insert_events([ev2], serial="BE1")
|
||||
|
||||
row = db.query_events(serial="BE1")[0]
|
||||
assert row["shape_crest_factor"] == 10.0
|
||||
assert row["shape_near_peak_count"] == 1
|
||||
assert row["shape_sample_count"] == 512
|
||||
assert row["shape_axis"] == "Tran"
|
||||
@@ -0,0 +1,58 @@
|
||||
import sqlite3
|
||||
from sfm.database import SeismoDb
|
||||
def _cols(db):
|
||||
with sqlite3.connect(db.db_path) as c:
|
||||
return {r[1] for r in c.execute("PRAGMA table_info(events)")}
|
||||
def test_fresh_db_has_reviewed_real(tmp_path):
|
||||
assert "reviewed_real" in _cols(SeismoDb(tmp_path/"s.db"))
|
||||
def test_existing_db_migrates_reviewed_real(tmp_path):
|
||||
p = tmp_path/"s.db"; db = SeismoDb(p)
|
||||
with sqlite3.connect(p) as c:
|
||||
c.execute("ALTER TABLE events DROP COLUMN reviewed_real")
|
||||
assert "reviewed_real" not in _cols(db) # dropped (read via existing handle/connection)
|
||||
SeismoDb(p) # re-open migrates
|
||||
assert "reviewed_real" in _cols(SeismoDb(p))
|
||||
|
||||
def test_legacy_pre_migration1_db_rebuild_does_not_crash(tmp_path):
|
||||
# Genuinely legacy (pre-Migration-1) events table: no UNIQUE(serial, timestamp)
|
||||
# (still on the old UNIQUE(serial, waveform_key)) and columns only through
|
||||
# false_trigger/created_at — i.e. none of the columns added later by the
|
||||
# Migration-1b ADD COLUMN loop (blastware_filename, device_family,
|
||||
# tran_zc_freq, shape_*, reviewed_real, ...). Opening this DB triggers the
|
||||
# Migration-1 rebuild (`events_old` -> `events` via positional
|
||||
# `INSERT OR IGNORE INTO events SELECT * FROM events_old`), which requires
|
||||
# the rebuild's CREATE TABLE to have exactly the legacy column count.
|
||||
p = tmp_path / "legacy.db"
|
||||
with sqlite3.connect(p) as c:
|
||||
c.execute("""
|
||||
CREATE TABLE events (
|
||||
id TEXT PRIMARY KEY,
|
||||
serial TEXT NOT NULL,
|
||||
waveform_key TEXT NOT NULL,
|
||||
session_id TEXT,
|
||||
timestamp TEXT,
|
||||
tran_ppv REAL,
|
||||
vert_ppv REAL,
|
||||
long_ppv REAL,
|
||||
peak_vector_sum REAL,
|
||||
mic_ppv REAL,
|
||||
project TEXT,
|
||||
client TEXT,
|
||||
operator TEXT,
|
||||
sensor_location TEXT,
|
||||
sample_rate INTEGER,
|
||||
record_type TEXT,
|
||||
false_trigger INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
UNIQUE(serial, waveform_key)
|
||||
)
|
||||
""")
|
||||
c.execute(
|
||||
"INSERT INTO events (id, serial, waveform_key, timestamp) VALUES (?, ?, ?, ?)",
|
||||
("evt-1", "BE11529", "01110000", "2026-01-01T00:00:00"),
|
||||
)
|
||||
# Pre-fix this raised: OperationalError: table events has 19 columns but
|
||||
# 18 values were supplied (reviewed_real had leaked into the rebuild's
|
||||
# CREATE TABLE, but events_old — and the positional SELECT * — only had 18).
|
||||
db = SeismoDb(p)
|
||||
assert "reviewed_real" in _cols(db)
|
||||
@@ -0,0 +1,15 @@
|
||||
from __future__ import annotations
|
||||
import os, sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event
|
||||
|
||||
|
||||
def test_query_events_includes_reviewed_real(tmp_path: Path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex("01110000")
|
||||
db.insert_events([ev], serial="BE1")
|
||||
assert "reviewed_real" in db.query_events(serial="BE1")[0]
|
||||
@@ -0,0 +1,13 @@
|
||||
from pathlib import Path
|
||||
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
_FIX = Path(__file__).parent / "fixtures/histogram-extension-re/events-5-21-26/K558LL8B.7I0W"
|
||||
|
||||
|
||||
def test_save_imported_bw_attaches_shape(tmp_path):
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
ev, rec = store.save_imported_bw(_FIX.read_bytes(), source_path=_FIX, serial_hint="BE9558")
|
||||
assert rec.get("shape_axis") in ("Tran", "Vert", "Long")
|
||||
assert rec["shape_crest_factor"] > 0
|
||||
assert rec["shape_sample_count"] > 200
|
||||
@@ -0,0 +1,29 @@
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event
|
||||
|
||||
|
||||
def _ins(db, eid_key="01110000", serial="BE1"):
|
||||
ev = Event(index=0); ev._waveform_key = bytes.fromhex(eid_key)
|
||||
db.insert_events([ev], serial=serial)
|
||||
return db.query_events(serial=serial)[0]["id"]
|
||||
|
||||
|
||||
def test_set_false_trigger_clears_reviewed_real(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db"); eid = _ins(db)
|
||||
db.update_event_review(eid, {"reviewed_real": True})
|
||||
assert db.get_event(eid)["reviewed_real"] == 1
|
||||
|
||||
db.set_false_trigger(eid, True)
|
||||
row = db.get_event(eid)
|
||||
assert row["false_trigger"] == 1 and row["reviewed_real"] == 0
|
||||
|
||||
|
||||
def test_clearing_false_trigger_leaves_reviewed_real_untouched(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db"); eid = _ins(db)
|
||||
db.update_event_review(eid, {"false_trigger": True})
|
||||
db.set_false_trigger(eid, False)
|
||||
row = db.get_event(eid)
|
||||
assert row["false_trigger"] == 0
|
||||
# reviewed_real was never set true, so it stays 0 either way; the point
|
||||
# is set_false_trigger(False) does not touch the column at all.
|
||||
assert row["reviewed_real"] == 0
|
||||
@@ -0,0 +1,27 @@
|
||||
import sqlite3
|
||||
from sfm.database import SeismoDb
|
||||
|
||||
_SHAPE_COLS = {"shape_crest_factor", "shape_near_peak_count",
|
||||
"shape_sample_count", "shape_axis"}
|
||||
|
||||
def _cols(db):
|
||||
with sqlite3.connect(db.db_path) as c:
|
||||
return {r[1] for r in c.execute("PRAGMA table_info(events)")}
|
||||
|
||||
def test_fresh_db_has_shape_columns(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
assert _SHAPE_COLS <= _cols(db)
|
||||
|
||||
def test_existing_db_migrates_shape_columns(tmp_path):
|
||||
p = tmp_path / "s.db"
|
||||
db = SeismoDb(p)
|
||||
with sqlite3.connect(p) as c: # simulate an older DB missing the columns
|
||||
for col in _SHAPE_COLS:
|
||||
c.execute(f"ALTER TABLE events DROP COLUMN {col}")
|
||||
# sanity: dropped. Read via the already-constructed `db` (a raw PRAGMA
|
||||
# read against db.db_path) rather than a fresh SeismoDb(p) — the latter
|
||||
# would immediately re-trigger _migrate's self-healing ADD COLUMN loop
|
||||
# and mask the gap we're trying to confirm.
|
||||
assert not (_SHAPE_COLS <= _cols(db))
|
||||
SeismoDb(p) # re-open triggers _migrate
|
||||
assert _SHAPE_COLS <= _cols(SeismoDb(p))
|
||||
@@ -0,0 +1,31 @@
|
||||
import numpy as np
|
||||
from sfm.shape_metrics import channel_shape, shape_from_samples
|
||||
|
||||
def test_needle_spike_high_crest_few_near_peak():
|
||||
x = np.zeros(1024); x[500] = 1.0 # one isolated spike
|
||||
s = channel_shape(x)
|
||||
assert s["sample_count"] == 1024
|
||||
assert s["crest_factor"] > 15 # peak towers over rms
|
||||
assert s["near_peak_count"] <= 3 # almost nothing near the peak
|
||||
|
||||
def test_ringing_low_crest_many_near_peak():
|
||||
t = np.arange(1024)
|
||||
x = np.sin(2*np.pi*t/32) * np.exp(-t/4000) # decaying oscillation
|
||||
s = channel_shape(x)
|
||||
assert s["crest_factor"] < 6
|
||||
assert s["near_peak_count"] > 30 # many samples near the peak
|
||||
|
||||
def test_channel_shape_none_for_unusable():
|
||||
assert channel_shape(np.zeros(1024)) is None # flat / all-zero
|
||||
assert channel_shape(np.array([1.0])) is None # too short
|
||||
|
||||
def test_shape_from_samples_picks_max_peak_axis():
|
||||
chans = {"Tran": np.zeros(1024), "Vert": np.zeros(1024), "Long": np.zeros(1024)}
|
||||
chans["Long"][10] = 0.5
|
||||
chans["Vert"] = np.sin(np.arange(1024)/5) * 0.01
|
||||
s = shape_from_samples(chans)
|
||||
assert s["axis"] == "Long" # Long has the biggest peak
|
||||
assert s["near_peak_count"] <= 3
|
||||
|
||||
def test_shape_from_samples_none_when_no_geo():
|
||||
assert shape_from_samples({"MicL": np.ones(1024)}) is None
|
||||
@@ -0,0 +1,22 @@
|
||||
import numpy as np, h5py
|
||||
from sfm.shape_metrics import shape_from_h5
|
||||
|
||||
def _write_h5(path, chans):
|
||||
with h5py.File(path, "w") as f:
|
||||
g = f.create_group("samples")
|
||||
for k, v in chans.items():
|
||||
g.create_dataset(k, data=np.asarray(v, dtype="float32"))
|
||||
|
||||
def test_shape_from_h5_reads_dominant_axis(tmp_path):
|
||||
p = tmp_path / "ev.h5"
|
||||
long = np.zeros(1024, dtype="float32"); long[100] = 0.48
|
||||
_write_h5(p, {"Tran": np.zeros(1024), "Vert": np.zeros(1024), "Long": long,
|
||||
"MicL": np.ones(1024)})
|
||||
s = shape_from_h5(str(p))
|
||||
assert s["axis"] == "Long" and s["near_peak_count"] <= 3
|
||||
|
||||
def test_shape_from_h5_none_on_missing_or_degenerate(tmp_path):
|
||||
assert shape_from_h5(str(tmp_path / "nope.h5")) is None
|
||||
p = tmp_path / "degen.h5"
|
||||
_write_h5(p, {"Tran": np.zeros(1), "Vert": np.zeros(1), "Long": np.zeros(1)})
|
||||
assert shape_from_h5(str(p)) is None
|
||||
@@ -0,0 +1,33 @@
|
||||
import sqlite3
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event, Timestamp
|
||||
|
||||
|
||||
def _ins(db, key, serial, pvs, ts):
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex(key)
|
||||
ev.timestamp = ts
|
||||
# peak_vector_sum comes from peak_values; simplest: insert then UPDATE pvs directly
|
||||
db.insert_events([ev], serial=serial)
|
||||
row = [r for r in db.query_events(serial=serial) if r["waveform_key"] == key][0]
|
||||
with sqlite3.connect(db.db_path) as c:
|
||||
c.execute("UPDATE events SET peak_vector_sum=? WHERE id=?", (pvs, row["id"]))
|
||||
return row["id"]
|
||||
|
||||
|
||||
def test_propagate_copies_flags_to_twins(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
base = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=20, minute=19, second=5)
|
||||
twin = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=20, minute=19, second=45)
|
||||
other = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=2, day=25, hour=20, minute=19, second=44)
|
||||
|
||||
primary_id = _ins(db, "01110001", "BE1", 0.4763, base)
|
||||
twin_id = _ins(db, "01110002", "BE1", 0.4763, twin) # twin: same serial+pvs, 40s apart
|
||||
non_twin_id = _ins(db, "01110003", "BE1", 0.9999, other) # near time but different pvs
|
||||
|
||||
db.update_event_review(primary_id, {"false_trigger": True})
|
||||
moved = db.propagate_review_to_twins(primary_id)
|
||||
|
||||
assert twin_id in moved
|
||||
assert db.get_event(twin_id)["false_trigger"] == 1
|
||||
assert db.get_event(non_twin_id)["false_trigger"] == 0
|
||||
@@ -0,0 +1,25 @@
|
||||
from sfm.database import SeismoDb
|
||||
from minimateplus.models import Event
|
||||
|
||||
|
||||
def _ins(db, eid_key="01110000", serial="BE1"):
|
||||
ev = Event(index=0); ev._waveform_key = bytes.fromhex(eid_key)
|
||||
db.insert_events([ev], serial=serial)
|
||||
return db.query_events(serial=serial)[0]["id"]
|
||||
|
||||
|
||||
def test_confirm_real_sets_and_clears_ft(tmp_path):
|
||||
db = SeismoDb(tmp_path/"s.db"); eid = _ins(db)
|
||||
db.update_event_review(eid, {"false_trigger": True})
|
||||
assert db.get_event(eid)["false_trigger"] == 1
|
||||
db.update_event_review(eid, {"reviewed_real": True}) # confirming real clears FT
|
||||
row = db.get_event(eid)
|
||||
assert row["reviewed_real"] == 1 and row["false_trigger"] == 0
|
||||
|
||||
|
||||
def test_flag_ft_clears_reviewed_real(tmp_path):
|
||||
db = SeismoDb(tmp_path/"s.db"); eid = _ins(db)
|
||||
db.update_event_review(eid, {"reviewed_real": True})
|
||||
db.update_event_review(eid, {"false_trigger": True})
|
||||
row = db.get_event(eid)
|
||||
assert row["false_trigger"] == 1 and row["reviewed_real"] == 0
|
||||
@@ -14,6 +14,7 @@ import pytest
|
||||
|
||||
from minimateplus.waveform_codec import (
|
||||
WaveformBlock,
|
||||
decode_waveform_legacy,
|
||||
decode_tran_initial,
|
||||
decode_waveform_v2,
|
||||
decoded_to_adc_counts,
|
||||
@@ -210,9 +211,11 @@ def test_parse_segment_header_decodes_fields():
|
||||
)
|
||||
decoded = parse_segment_header(block)
|
||||
assert decoded is not None
|
||||
assert decoded["n_prev_deltas"] == 2
|
||||
assert decoded["prev_deltas"] == [0, 0]
|
||||
assert decoded["counter"] == 0x47 # uint32 LE
|
||||
assert decoded["fixed_pattern"] == b"\x02\x00\x00\x01"
|
||||
assert decoded["anchor_bytes"] == b"\x00\x00\x00\x00"
|
||||
assert decoded["marker"] == b"\x02\x00"
|
||||
assert decoded["anchors"] == [1, 1]
|
||||
|
||||
|
||||
def test_segment_counter_increments():
|
||||
@@ -516,3 +519,279 @@ def test_decode_a5_frames_empty():
|
||||
from minimateplus.waveform_codec import decode_a5_frames
|
||||
assert decode_a5_frames([]) is None
|
||||
assert decode_a5_frames(None) is None
|
||||
|
||||
|
||||
# ── Wide-NN RLE, wide 30 NN, and variable-width segment headers ──────────────
|
||||
#
|
||||
# Three framing cases discovered 2026-08-25 by diffing 75 production events
|
||||
# against their preserved Blastware ASCII exports. Each caused ``walk_body``
|
||||
# to hit its ``else: break`` mid-stream, truncating every channel decoded
|
||||
# after that point (see CHANGELOG v0.25.1).
|
||||
|
||||
_PREAMBLE = b"\x00\x02\x00\x00\x00\x00\x00" # magic + Tran[0]=0, Tran[1]=0
|
||||
_STOP = b"\xff\xff" # unrecognised tag → walker stops
|
||||
|
||||
|
||||
def _synth(*chunks: bytes) -> bytes:
|
||||
return _PREAMBLE + b"".join(chunks) + _STOP
|
||||
|
||||
|
||||
def test_walk_body_wide_rle_block():
|
||||
"""``0X NN`` is a 12-bit-NN RLE run (NN = ((t0 & 0x0F) << 8) | t1).
|
||||
|
||||
Observed as ``01 0c`` (NN=268) in BE9558/K558LKOF.460W and five other
|
||||
production events. A narrow ``00 NN`` maxes out at NN=0xFC, so runs
|
||||
longer than 252 samples must use the wide form.
|
||||
"""
|
||||
blocks = walk_body(_synth(b"\x01\x0c"))
|
||||
assert len(blocks) == 1
|
||||
assert (blocks[0].tag_hi, blocks[0].tag_lo) == (0x01, 0x0C)
|
||||
assert blocks[0].length == 2
|
||||
|
||||
|
||||
# NOTE (2026-08-25): the four tests below assert the SUPERSEDED tag-dispatch
|
||||
# model — `40 NN` as a variable-width segment header, tagless headers, channel
|
||||
# from rotation. The body format is really a chain of self-delimiting records
|
||||
# (see the record-chain section of waveform_codec.py), so `decode_waveform_v2`
|
||||
# no longer behaves this way. They are retargeted at `decode_waveform_legacy`,
|
||||
# which still implements the old model and is pinned by micromate/idf_file.py
|
||||
# for Thor IDFW bodies.
|
||||
|
||||
|
||||
def test_decode_wide_rle_repeats_full_run():
|
||||
"""A wide RLE run repeats the running value NN times, not NN & 0xFF."""
|
||||
decoded = decode_waveform_legacy(_synth(b"\x01\x0c"))
|
||||
# 2 preamble anchors + 268 repeats
|
||||
assert len(decoded["Tran"]) == 2 + 268
|
||||
assert set(decoded["Tran"]) == {0}
|
||||
|
||||
|
||||
def test_walk_body_30_block_nn_above_16():
|
||||
"""``30 NN`` data blocks are not capped at NN=0x10.
|
||||
|
||||
``30 18`` (NN=24) appears in BE18193/T193LQ45.NN0W; the old
|
||||
``0 < t1 <= 0x10`` guard rejected it and stopped the walk 1033 bytes
|
||||
into a 4877-byte body. Length is still NN * 1.5 + 2.
|
||||
"""
|
||||
payload = bytes(36) # 24 deltas × 1.5 bytes
|
||||
blocks = walk_body(_synth(b"\x30\x18" + payload, b"\x00\x04"))
|
||||
assert [b.length for b in blocks] == [38, 2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nn,hdr_len", [(1, 18), (2, 20), (3, 22)])
|
||||
def test_walk_body_segment_header_width_follows_tag_lo(nn, hdr_len):
|
||||
"""``40 NN``: NN is the count of previous-channel continuation deltas.
|
||||
|
||||
Header length = 2 * NN + 16. ``40 02`` (the only form previously
|
||||
handled) is the NN=2 case at 20 bytes; ``40 01`` (18) and ``40 03``
|
||||
(22) both occur in production files.
|
||||
"""
|
||||
data = bytearray(hdr_len - 2)
|
||||
data[2 * nn + 8 : 2 * nn + 10] = b"\x02\x00" # constant marker
|
||||
blocks = walk_body(_synth(bytes([0x40, nn]) + bytes(data), b"\x00\x04"))
|
||||
assert [b.length for b in blocks] == [hdr_len, 2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nn,hdr_len", [(1, 18), (2, 20), (3, 22)])
|
||||
def test_segment_header_anchors_track_header_width(nn, hdr_len):
|
||||
"""Anchor pair sits at data[2*NN+10 : 2*NN+14] regardless of width."""
|
||||
data = bytearray(hdr_len - 2)
|
||||
data[2 * nn + 8 : 2 * nn + 10] = b"\x02\x00"
|
||||
data[2 * nn + 10 : 2 * nn + 12] = (7).to_bytes(2, "big") # anchor 0
|
||||
data[2 * nn + 12 : 2 * nn + 14] = (9).to_bytes(2, "big") # anchor 1
|
||||
decoded = decode_waveform_legacy(_synth(bytes([0x40, nn]) + bytes(data)))
|
||||
assert decoded["Vert"][:2] == [7, 9]
|
||||
|
||||
|
||||
# ── Tagless segment headers ─────────────────────────────────────────────────
|
||||
#
|
||||
# A segment header can appear WITHOUT its ``40 NN`` tag: just the 14-byte tail
|
||||
# ``[field2:2][len:2][channel_id:4][marker:2][anchors:4]``. This is the NN=0
|
||||
# case — no continuation deltas for the previous channel, so no tag and no
|
||||
# delta bytes. Found 2026-08-25: it is where the walk stopped in 7 of the 8
|
||||
# remaining truncating production events.
|
||||
#
|
||||
# The channel_id field (previously mis-labelled a "monotonic counter") is
|
||||
# ``[channel][00][00][segment_index]`` with 0x46=Tran 0x47=Vert 0x48=Long
|
||||
# 0x49=MicL — verified on 1697 of 1697 segment headers across the ground-truth
|
||||
# corpus, zero disagreements.
|
||||
|
||||
def _tagless(chan_id=0x47, seg=2, marker=b"\x02\x00", a0=0, a1=0):
|
||||
return (b"\x5d\xee" + b"\x00\xd0" + bytes([chan_id, 0, 0, seg]) + marker
|
||||
+ a0.to_bytes(2, "big", signed=True) + a1.to_bytes(2, "big", signed=True))
|
||||
|
||||
|
||||
def test_walk_body_accepts_tagless_segment_header():
|
||||
"""A bare 14-byte header is walked as a segment block, not a stop."""
|
||||
blocks = walk_body(_synth(b"\x10\x04\x00\x00", _tagless(), b"\x00\x04"))
|
||||
kinds = [(b.tag_hi, b.tag_lo, b.length) for b in blocks]
|
||||
assert kinds == [(0x10, 0x04, 4), (0x40, 0x00, 14), (0x00, 0x04, 2)]
|
||||
|
||||
|
||||
def test_tagless_header_carries_full_14_bytes_as_data():
|
||||
"""The synthetic block's data includes the leading bytes (there is no tag
|
||||
to strip), so decode_waveform_v2's ``2*nd + k`` offsets line up at nd=0."""
|
||||
blocks = walk_body(_synth(_tagless()))
|
||||
hdr = next(b for b in blocks if b.tag_hi == 0x40)
|
||||
assert len(hdr.data) == 14
|
||||
assert hdr.data[8:10] == b"\x02\x00" # marker at 2*0 + 8
|
||||
|
||||
|
||||
def test_tagless_header_anchors_and_channel_id():
|
||||
"""Anchors decode from data[10:14]; the channel comes from the id byte."""
|
||||
decoded = decode_waveform_legacy(_synth(_tagless(chan_id=0x48, a0=11, a1=13)))
|
||||
assert decoded["Long"][:2] == [11, 13] # 0x48 → Long, not rotation
|
||||
assert decoded["Vert"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chan_id,name",
|
||||
[(0x46, "Tran"), (0x47, "Vert"), (0x48, "Long"), (0x49, "MicL")])
|
||||
def test_segment_channel_comes_from_id_not_rotation(chan_id, name):
|
||||
"""Channel is taken from the header's id byte. Two headers in a row for
|
||||
the SAME channel must both land on that channel — rotation-by-position
|
||||
would put the second one on the next channel and corrupt both."""
|
||||
body = _synth(_tagless(chan_id=chan_id, seg=1, a0=5, a1=6),
|
||||
_tagless(chan_id=chan_id, seg=2, a0=7, a1=8))
|
||||
decoded = decode_waveform_legacy(body)
|
||||
# Tran additionally carries the body preamble's 2 anchors (both 0 here).
|
||||
expected = [0, 0, 5, 6, 7, 8] if name == "Tran" else [5, 6, 7, 8]
|
||||
assert decoded[name] == expected
|
||||
for other in ("Tran", "Vert", "Long", "MicL"):
|
||||
if other != name:
|
||||
assert decoded[other] == ([0, 0] if other == "Tran" else [])
|
||||
|
||||
|
||||
# ── Record-chain body model (2026-08-25) ────────────────────────────────────
|
||||
#
|
||||
# The body is a chain of self-delimiting per-channel records, not a flat
|
||||
# tag-dispatch stream. Verified over 1,388 production series-3 waveform
|
||||
# binaries: the chain terminates on a 0x06 record in 1,387 of them and all
|
||||
# four channels come out at identical length in 1,388/1,388 (was 156/1,388).
|
||||
# Against the 75 events with a preserved Blastware ASCII export: sample-count
|
||||
# exact 72/75 -> 75/75, fully exact 70/75 -> 73/75.
|
||||
|
||||
from minimateplus.waveform_codec import ( # noqa: E402
|
||||
CHANNEL_IDS,
|
||||
MODE_ABSOLUTE,
|
||||
MODE_DELTA,
|
||||
MODE_RAW12,
|
||||
STREAM_END_ID,
|
||||
data_block_len,
|
||||
find_first_record,
|
||||
is_record,
|
||||
unpack12,
|
||||
walk_records,
|
||||
)
|
||||
|
||||
|
||||
def _rec(chan_id, mode, payload, seg=0, field2=b"\x00\x00", anchors=None):
|
||||
"""Build one self-delimiting record."""
|
||||
head = bytearray()
|
||||
head += bytes([chan_id, 0x00, 0x00, seg])
|
||||
head += bytes(mode)
|
||||
if anchors is not None:
|
||||
for a in anchors:
|
||||
head += int(a).to_bytes(2, "big", signed=True)
|
||||
body = bytes(head) + payload
|
||||
return field2 + (len(body) + 2).to_bytes(2, "big") + body
|
||||
|
||||
|
||||
def _terminator():
|
||||
return b"\x00\x00" + (8).to_bytes(2, "big") + bytes([STREAM_END_ID, 0, 0, 0, 0, 0])
|
||||
|
||||
|
||||
def _body(*records, preamble=b"\x00\x02\x00", seg0=b"\x00\x00\x00\x00"):
|
||||
return preamble + seg0 + b"".join(records) + _terminator()
|
||||
|
||||
|
||||
def test_forty_nn_is_a_data_block_not_a_segment_header():
|
||||
"""`40 NN` is an int16 BE data block of length 2*NN + 2.
|
||||
|
||||
The superseded model read it as a segment header of length 2*NN + 16,
|
||||
which is what made walks drift and channels come out unequal.
|
||||
"""
|
||||
assert data_block_len(b"\x40\x02\x00\x01\x00\x02", 0) == (6, 2)
|
||||
assert data_block_len(b"\x40\x08" + bytes(16), 0) == (18, 8)
|
||||
# NN > 8 is not a data block
|
||||
assert data_block_len(b"\x40\x0c" + bytes(24), 0) == (None, None)
|
||||
|
||||
|
||||
def test_record_chain_is_followed_by_length_not_by_tag_sniffing():
|
||||
payload = b"\x00\x04" # RLE hold x4
|
||||
body = _body(_rec(0x47, MODE_DELTA, payload, anchors=(3, 5)))
|
||||
recs = walk_records(body)
|
||||
assert len(recs) == 1
|
||||
assert recs[0]["channel"] == "Vert"
|
||||
assert recs[0]["mode"] == MODE_DELTA
|
||||
|
||||
|
||||
def test_chain_terminates_on_channel_id_06():
|
||||
body = _body(_rec(0x47, MODE_DELTA, b"\x00\x04", anchors=(1, 1)),
|
||||
_rec(0x48, MODE_DELTA, b"\x00\x04", anchors=(2, 2)))
|
||||
assert [r["channel"] for r in walk_records(body)] == ["Vert", "Long"]
|
||||
assert not is_record(body, len(body) - 10) # the terminator is not a record
|
||||
|
||||
|
||||
def test_mode_delta_emits_anchors_then_accumulates():
|
||||
# two anchors, then an int8 block of +1,+1,+1,+1
|
||||
body = _body(_rec(0x47, MODE_DELTA, b"\x20\x04\x01\x01\x01\x01",
|
||||
anchors=(10, 11)))
|
||||
d = decode_waveform_v2(body)
|
||||
assert d["Vert"] == [10, 11, 12, 13, 14, 15]
|
||||
|
||||
|
||||
def test_mode_absolute_replaces_rather_than_accumulates():
|
||||
"""mode `01 00`: no anchors, and block values are ABSOLUTE samples."""
|
||||
body = _body(_rec(0x48, MODE_ABSOLUTE, b"\x20\x04\x0a\x0b\x0c\x0d"))
|
||||
d = decode_waveform_v2(body)
|
||||
assert d["Long"] == [10, 11, 12, 13], "01 00 blocks are absolute, not deltas"
|
||||
|
||||
|
||||
def test_mode_absolute_rle_holds_the_previous_value():
|
||||
body = _body(_rec(0x48, MODE_ABSOLUTE, b"\x20\x04\x07\x07\x07\x07\x00\x04"))
|
||||
d = decode_waveform_v2(body)
|
||||
assert d["Long"] == [7, 7, 7, 7, 7, 7, 7, 7]
|
||||
|
||||
|
||||
def test_mode_raw12_has_no_tags_at_all():
|
||||
"""mode `00 03`: the whole data section is raw 12-bit absolute samples.
|
||||
|
||||
Decoding these matters for the time base — skipping the record would
|
||||
displace every later sample on that channel (observed on
|
||||
BE9558/K558LOF2.820W, MicL shifted by exactly 512).
|
||||
"""
|
||||
packed = bytes([0x01, 0x23, 0x04, 0x05, 0x06, 0x07]) # 4 samples
|
||||
body = _body(_rec(0x49, MODE_RAW12, packed))
|
||||
d = decode_waveform_v2(body)
|
||||
assert d["MicL"] == unpack12(packed)
|
||||
assert len(d["MicL"]) == 4
|
||||
|
||||
|
||||
def test_unpack12_sign_extends():
|
||||
assert unpack12(bytes([0x00, 0x00, 0x01, 0x02, 0x03, 0x04])) == [1, 2, 3, 4]
|
||||
# high nibble 0x8 -> negative
|
||||
assert unpack12(bytes([0x80, 0x00, 0x00, 0x00, 0x00, 0x00]))[0] == -2048
|
||||
|
||||
|
||||
def test_channel_comes_from_the_record_id():
|
||||
for cid, name in CHANNEL_IDS.items():
|
||||
body = _body(_rec(cid, MODE_ABSOLUTE, b"\x20\x04\x01\x02\x03\x04"))
|
||||
d = decode_waveform_v2(body)
|
||||
assert d[name][-4:] == [1, 2, 3, 4], f"{name} misrouted"
|
||||
|
||||
|
||||
def test_raw12_preamble_is_scanned_not_block_walked():
|
||||
"""A `00 00 03` preamble carries raw 12-bit data from body[3] with no tags,
|
||||
so find_first_record must scan rather than block-walk. One production file
|
||||
has this (BE13121/O121L4L1.KF0W); block-walking returns None on it."""
|
||||
packed = bytes([0x00, 0x00, 0x01, 0x02, 0x03, 0x04])
|
||||
body = _body(_rec(0x47, MODE_DELTA, b"\x00\x04", anchors=(1, 1)),
|
||||
preamble=b"\x00\x00\x03", seg0=packed)
|
||||
assert find_first_record(body) == 3 + len(packed)
|
||||
d = decode_waveform_v2(body)
|
||||
assert d["Tran"] == unpack12(packed)
|
||||
|
||||
|
||||
def test_returns_none_when_no_record_chain():
|
||||
assert decode_waveform_v2(b"\x00\x02\x00" + bytes(40)) is None
|
||||
assert decode_waveform_v2(b"") is None
|
||||
@@ -0,0 +1,174 @@
|
||||
from __future__ import annotations
|
||||
import os, sys, sqlite3
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from sfm.database import SeismoDb
|
||||
|
||||
ZC_COLS = ["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"]
|
||||
|
||||
|
||||
def test_fresh_db_has_zc_freq_columns(tmp_path: Path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
with sqlite3.connect(str(tmp_path / "seismo_relay.db")) as conn:
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(events)").fetchall()}
|
||||
for c in ZC_COLS:
|
||||
assert c in cols, f"missing column {c}"
|
||||
|
||||
|
||||
def test_migration_adds_zc_freq_columns_to_legacy_db(tmp_path: Path):
|
||||
db_path = tmp_path / "old.db"
|
||||
# A "modern-minus-zc" events table (has blastware_* but not the zc columns).
|
||||
with sqlite3.connect(str(db_path)) as conn:
|
||||
conn.executescript("""
|
||||
CREATE TABLE events (
|
||||
id TEXT PRIMARY KEY, serial TEXT NOT NULL, waveform_key TEXT NOT NULL,
|
||||
session_id TEXT, timestamp TEXT,
|
||||
tran_ppv REAL, vert_ppv REAL, long_ppv REAL, peak_vector_sum REAL, mic_ppv REAL,
|
||||
project TEXT, client TEXT, operator TEXT, sensor_location TEXT,
|
||||
sample_rate INTEGER, record_type TEXT,
|
||||
false_trigger INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
UNIQUE(serial, timestamp)
|
||||
);
|
||||
INSERT INTO events (id, serial, waveform_key, timestamp)
|
||||
VALUES ('legacy-id', 'BE11529', '01110000', '2026-04-01T12:00:00');
|
||||
""")
|
||||
db = SeismoDb(db_path) # triggers _migrate
|
||||
rows = db.query_events(serial="BE11529")
|
||||
assert len(rows) == 1
|
||||
for c in ZC_COLS:
|
||||
assert c in rows[0] # present
|
||||
assert rows[0][c] is None # NULL for the legacy row
|
||||
|
||||
|
||||
from minimateplus.models import PeakValues, Event
|
||||
from minimateplus import event_file_io
|
||||
from minimateplus.bw_ascii_report import BwAsciiReport, ChannelStats, MicStats
|
||||
|
||||
|
||||
def _report_with_freqs():
|
||||
r = BwAsciiReport()
|
||||
r.channels["Tran"] = ChannelStats(ppv_ips=0.075, zc_freq_hz=100.0, zc_freq_above_range=True)
|
||||
r.channels["Vert"] = ChannelStats(ppv_ips=0.220, zc_freq_hz=85.0)
|
||||
r.channels["Long"] = ChannelStats(ppv_ips=0.045, zc_freq_hz=73.0)
|
||||
r.mic = MicStats(zc_freq_hz=51.0)
|
||||
return r
|
||||
|
||||
|
||||
def test_apply_report_copies_zc_freq_onto_peakvalues():
|
||||
ev = Event(index=0)
|
||||
event_file_io.apply_report_to_event(ev, _report_with_freqs())
|
||||
pv = ev.peak_values
|
||||
assert pv.vert_zc_freq == 85.0
|
||||
assert pv.tran_zc_freq == 100.0
|
||||
assert pv.tran_zc_above_range is True
|
||||
assert pv.vert_zc_above_range is False
|
||||
assert pv.mic_zc_freq == 51.0
|
||||
|
||||
|
||||
def test_apply_bw_report_dict_copies_zc_freq():
|
||||
ev = Event(index=0)
|
||||
bw = {
|
||||
"peaks": {
|
||||
"tran": {"ppv_ips": 0.075, "zc_freq_hz": 100.0, "zc_freq_above_range": True},
|
||||
"vert": {"ppv_ips": 0.220, "zc_freq_hz": 85.0},
|
||||
"long": {"ppv_ips": 0.045, "zc_freq_hz": 73.0},
|
||||
},
|
||||
"mic": {"zc_freq_hz": 51.0, "zc_freq_above_range": False},
|
||||
}
|
||||
event_file_io.apply_bw_report_dict_to_event(ev, bw)
|
||||
pv = ev.peak_values
|
||||
assert pv.vert_zc_freq == 85.0
|
||||
assert pv.tran_zc_above_range is True
|
||||
assert pv.mic_zc_freq == 51.0
|
||||
|
||||
|
||||
def _event_with_zc(waveform_key="01110000"):
|
||||
from minimateplus.models import Event, Timestamp
|
||||
ev = Event(index=0)
|
||||
ev._waveform_key = bytes.fromhex(waveform_key)
|
||||
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"
|
||||
ev.peak_values = PeakValues(
|
||||
tran=0.075, vert=0.220, long=0.045, peak_vector_sum=0.231, micl=0.01,
|
||||
tran_zc_freq=100.0, vert_zc_freq=85.0, long_zc_freq=73.0, mic_zc_freq=51.0,
|
||||
tran_zc_above_range=True,
|
||||
)
|
||||
return ev
|
||||
|
||||
|
||||
def test_insert_events_persists_zc_freq(tmp_path: Path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
ins, _ = db.insert_events([_event_with_zc()], serial="BE11529")
|
||||
assert ins == 1
|
||||
row = db.query_events(serial="BE11529")[0]
|
||||
assert row["vert_zc_freq"] == 85.0
|
||||
assert row["tran_zc_freq"] == 100.0
|
||||
assert row["tran_zc_above_range"] == 1
|
||||
assert row["vert_zc_above_range"] == 0
|
||||
assert row["mic_zc_freq"] == 51.0
|
||||
|
||||
|
||||
def test_upsert_updates_zc_freq(tmp_path: Path):
|
||||
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||
db.insert_events([_event_with_zc()], serial="BE11529")
|
||||
ev2 = _event_with_zc()
|
||||
ev2.peak_values.vert_zc_freq = 91.0 # same (serial, timestamp) → UPSERT
|
||||
db.insert_events([ev2], serial="BE11529")
|
||||
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