Compare commits
43
Commits
No files matched your search
+1
-1
@@ -6,7 +6,7 @@
|
||||
/bridges/s3-bridge/*.bin
|
||||
/bridges/s3-bridge/*.log
|
||||
/bridges/s3-bridge/*.set
|
||||
/example-events/
|
||||
/example-events
|
||||
/tests/fixtures/
|
||||
/manuals/
|
||||
|
||||
|
||||
+319
@@ -4,6 +4,325 @@ All notable changes to seismo-relay are documented here.
|
||||
|
||||
---
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Fixed
|
||||
- **A Blastware file's geophone range comes from its setup, so Sensitive
|
||||
events no longer read 8× high.**
|
||||
- **Where it is:** in the setup's channel blocks, the byte 29 after each
|
||||
geophone label. `0x00` is Normal (10 in/s full scale), `0x01` is Sensitive
|
||||
(1.25 in/s). SFM's live 1A read has the same byte at label+33.
|
||||
- **Measured:** it matches Blastware's GeoRange on 70,042 / 70,042 DL2
|
||||
events, all three channels agreeing on every one (35 Sensitive).
|
||||
- **Before:** SFM assumed Normal, so every Sensitive event's peaks, vector
|
||||
sum and `.h5` samples read 8× high.
|
||||
- **`Event.geo_range`** is new: 0 or 1, or None when it isn't read (the
|
||||
channels disagree, an unknown value, or a missing block). None comes with
|
||||
a `decode_problems` entry, and peaks then assume Normal as before.
|
||||
- **`decode_blastware_bytes`** scales peaks and the histogram vector sum by
|
||||
the range.
|
||||
- **`event_hdf5.write_event_hdf5`:** `geo_range` now defaults to None,
|
||||
meaning the event's own range, else Normal. An explicit argument still
|
||||
wins.
|
||||
- **`waveform_store.save_imported_bw` and `scripts/backfill_sidecars.py`**
|
||||
no longer force `"normal"`. The `waveform_store` line was agreed with the
|
||||
parity session, which owns that file.
|
||||
- **Decode checker:** GeoRange 70,042 / 70,042, and geophone samples exact
|
||||
on **6,524 / 6,524** waveforms (was 6,491). PPV mismatches about halved,
|
||||
and 10 of 88 fields fully match (was 6). 70,287 comparisons fixed, 0
|
||||
regressions.
|
||||
- ⚠ **Codec change: bump `TOOL_VERSION` at the next release.** The backfill
|
||||
(`backfill_sidecars.py` then `backfill_event_shape.py`) rewrites stored
|
||||
Sensitive events' peaks and `.h5` files. No schema change.
|
||||
|
||||
### Protocol / Documentation
|
||||
- **`docs/instantel_protocol_reference.md` gains Appendix D.6:** the bytes
|
||||
and DL2 verification for every field SFM reads from a Blastware event file.
|
||||
- the record type, `STRT[18]`
|
||||
- the recording-setup block: sample rate, pre-trigger, record time and the
|
||||
four notes
|
||||
- the geophone range
|
||||
- each histogram interval's PVS²
|
||||
- the mic scale
|
||||
- **Retracted in place:**
|
||||
- `STRT[20]` as the record time: it is `00` on every DL2 file.
|
||||
- The 2026-08-26 reading of sub-minute histogram records as little-endian:
|
||||
they are big-endian from byte 5 (#47/#49), and the "2-word tail" is the
|
||||
PVS². This is corrected in CLAUDE.md too.
|
||||
- **#48 is still open.** The event file's setup block puts the pre-trigger where
|
||||
the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though, it is
|
||||
**each event's own pre-trigger**, not the unit's setting: it varies on the
|
||||
same unit on the same day, and Blastware reports it per event. So the files
|
||||
say little about whether the live 1A read loses its anchor. (Corrected the
|
||||
same day; the first version read the file's value as the setting.)
|
||||
- **CLAUDE.md "Where things stand"** now reflects the range fix.
|
||||
- Docs only: no code change, no migration.
|
||||
|
||||
## v0.33.0 — 2026-11-01
|
||||
|
||||
**SFM reads Series-3 events from the file alone, and proves it against
|
||||
Blastware.**
|
||||
|
||||
**What was broken.** A Blastware event that reached SFM without its ASCII
|
||||
report used to come in half-decoded:
|
||||
- no sample rate
|
||||
- a "70 s" record time, which was really the record-type byte
|
||||
- blank notes
|
||||
- every histogram typed as a waveform
|
||||
- a histogram vector sum built from channel peaks taken at different moments
|
||||
- a mic reading about 95× low in psi
|
||||
|
||||
That matters more now: every DL2 event from before 2025 arrives with no report,
|
||||
and SFM's own download and call-in paths never have one.
|
||||
|
||||
**What this release does.** It reads all of those from the event file itself,
|
||||
and adds the decode checker that proves it. The checker compares SFM's
|
||||
file-only decode, field by field and sample by sample, with Blastware's own
|
||||
`_XML.XML` event reports for the 70,042 DL2 events that have one (2016–2026).
|
||||
|
||||
**Where that stands now:**
|
||||
- sample rate, record time, pre-trigger, notes and event type match on every
|
||||
event
|
||||
- geophone samples are exact on 6,491 / 6,524 waveforms (the 33 others are on
|
||||
the 1.250 in/s range, which SFM cannot read from the file yet)
|
||||
- the histogram vector sum matches on 69,919
|
||||
- the mic matches on all but a few dozen
|
||||
|
||||
Events imported with an ASCII report are unchanged on prod; the report still
|
||||
overlays.
|
||||
|
||||
⚠ **This release owes prod a backfill.** It does not move stored event times;
|
||||
see *Migration* below.
|
||||
|
||||
### Fixed
|
||||
- **The mic in psi was ~95× low: one MicL count is 0.25 Pa.**
|
||||
- SFM converted mic counts with a "~0.5 psi full-scale" guess (0.0125 /
|
||||
32768 psi per count). The decoded count was always right: count 16 on
|
||||
`K441LTON.900` is Blastware's 106.0 dB.
|
||||
- Measured against 1,729,253 DL2 histogram intervals' "MicL Peak"
|
||||
columns: count × 0.25 Pa matches Blastware's psi(L) on every one.
|
||||
- `event_file_io._MIC_FS_PSI` is now `_MIC_PSI_PER_COUNT` = 0.25 / 6894.757
|
||||
(3.626e-5 psi per count).
|
||||
- The event's mic peak comes right on events with no report, and so does
|
||||
the `.h5` mic trace (`event_hdf5` derives its scale from that peak).
|
||||
- **dB offset:** `waveform_codec.mic_count_to_db` now uses 81.9384, not
|
||||
81.94. Blastware's dB sits in a measured window, [81.9383, 81.9385], a
|
||||
hair above the exact 81.93820. Any value in the window matches on
|
||||
1,729,252 / 1,729,253 intervals.
|
||||
- The checker's first run of this fix flagged 280 regressions, every one
|
||||
count 129, which exact 0.25 Pa rounds to 124.1 against Blastware's
|
||||
124.2.
|
||||
- The old 81.94 misses counts 119 and 132.
|
||||
- Decode checker, against the pre-fix baseline: 45,035 fixed, 0
|
||||
regressions.
|
||||
|
||||
| Field | Mismatches before | After |
|
||||
|---|---|---|
|
||||
| interval psi | 42,783 | 26 |
|
||||
| interval dB | 974 | 20 |
|
||||
| mic peak | 345 | 40 |
|
||||
| waveform mic samples | 1,056 | 37 |
|
||||
|
||||
- ⚠ **Codec change, covered by the same release bump.** The backfill
|
||||
rewrites stored mic values on report-less events; report-paired events
|
||||
keep the report's. No schema change.
|
||||
- **A histogram's peak vector sum is now the one the unit stores.** SFM
|
||||
computed it from each channel's interval peak, and those can come from
|
||||
different moments. So on 86% of DL2's histograms with no report it read
|
||||
high: `T004JTRF.ME0H` gave 1.782 against Blastware's 1.358.
|
||||
- Every interval carries its peak vector sum SQUARED, a uint32 BE in
|
||||
0.005 in/s units:
|
||||
- bytes [21:25] of a standard block, long documented as "constant
|
||||
`00 00`" plus "purpose unknown"
|
||||
- the last 4 bytes of a sub-minute record (the undecoded `meta_var`)
|
||||
- √stored × 0.005 is the "Geo PVS" Blastware prints. It matches on
|
||||
1,668,073 / 1,668,074 standard and 34.5 million sub-minute DL2
|
||||
intervals.
|
||||
- The event's value is the largest interval's.
|
||||
`histogram_codec.interval_pvs` returns the per-interval series, and
|
||||
records gain `pvs_sq`. Waveforms are unchanged.
|
||||
- Decode checker: `PeakVectorSum` matches on 69,919 events (was 15,097):
|
||||
54,822 fixed, 0 regressions. The 80 left are three things:
|
||||
- the 35 Sensitive-range events (8×, SFM's Normal-range assumption)
|
||||
- 27 of the 5-second histograms that decode wrongly
|
||||
- about a dozen waveforms Blastware prints `OORANGE` for when the
|
||||
vector sum alone exceeds 10 in/s — a likely carve-out, still to be
|
||||
shown
|
||||
- The per-interval series is not stored yet, so the checker still scores
|
||||
`intervals.Geo PVS` as SFM blank.
|
||||
- ⚠ **Codec change, covered by the same release bump as #44/#45 and
|
||||
#41.** The backfill rewrites stored histogram PVS, but only where no
|
||||
ASCII report overlays it. Report-paired events keep the report's value.
|
||||
No schema change.
|
||||
- **A Blastware event's record type comes from its bytes, not its filename
|
||||
(#41).**
|
||||
- STRT[18] is the record-type byte: `0x46` on every one of DL2's 6,577
|
||||
waveform files and `0x0A` on every one of its 63,535 histograms.
|
||||
- The decoder used to read the type from the filename's last letter. So an
|
||||
event with no Blastware name came out "Waveform" whatever it was: SFM's
|
||||
own downloads, the call-in path, and a manual download (`.QZ0`).
|
||||
- The filename is now only a cross-check that logs a disagreement.
|
||||
- An unknown byte gives `record_type` None and a `decode_problems` entry,
|
||||
not a guess. Manual, Event and Combo types never occur in DL2, so their
|
||||
bytes are unknown.
|
||||
- Decode checker: `EventType` matches on 70,042 / 70,042 events (was 6,524),
|
||||
0 regressions.
|
||||
- ⚠ **Codec change, covered by the same release bump as #44/#45.** The
|
||||
backfill rewrites stored `record_type`. Files named `…W` / `…H` keep their
|
||||
type. A histogram stored from a 3-character manual-download name flips
|
||||
from Waveform to Histogram, which also changes how it pairs with its
|
||||
waveform twin. No schema change.
|
||||
- **A Blastware event imported without its ASCII report now carries its
|
||||
setup and notes (#44, #45).** Until now such an event stored no sample
|
||||
rate, a record time of "70 s" (the STRT record-type byte, 0x46), a
|
||||
pre-trigger and sample count read from STRT bytes that are neither, and
|
||||
blank project / client / operator / location (the reader stopped at the
|
||||
NUL after each label). All of DL2's 2016–2024 events arrive this way.
|
||||
- The recording-setup block is found by structure (`1c 08`, the setup
|
||||
name, NUL), not by the name "Standard Recording Setup", which 37% of
|
||||
DL2's files do not use.
|
||||
- Sample rate, pre-trigger and record time come from that block; a
|
||||
waveform's sample count is the decoded count. A histogram gets a
|
||||
sample rate only: Blastware reports no record time or pre-trigger for
|
||||
one.
|
||||
- The setup name and the four notes are read by position, as the ASCII
|
||||
parser does: their labels are operator-editable.
|
||||
- Verified against Blastware's own `_XML.XML` reports for the 70,042 DL2
|
||||
events that have one (2016–2026): sample rate 70,042/70,042, record
|
||||
time 6,524/6,524, pre-trigger 6,484/6,484, notes 70,042/70,042, sample
|
||||
count 6,523/6,524. The one miss is the harness's, not the decoder's:
|
||||
`T438HGTZ.B30W`'s Tran, Vert and MicL end 3 samples before Long, in
|
||||
Blastware's own sample table too, and the harness compared Tran's
|
||||
length with the table's row count.
|
||||
- Events imported with an ASCII report are unchanged: the report still
|
||||
overlays. Not yet read: the job number (2,997 archive events carry
|
||||
one). The waveform-time estimate still finds the record time by the
|
||||
name, pending a measurement. The Micromate half of #44/#45 (SFM's own
|
||||
downloads, no report) stays with the parity branch.
|
||||
- ⚠ **Codec change: bump `TOOL_VERSION` at release** and run
|
||||
`backfill_sidecars.py` then `backfill_event_shape.py` on prod (~2 h on
|
||||
the NAS) so stored report-less events pick the fields up. No schema
|
||||
change, no migration.
|
||||
|
||||
### Added
|
||||
- **The Series 3 decode checker.** It proves SFM can produce everything
|
||||
Blastware reports from the event file alone, the first of four pieces
|
||||
toward retiring Blastware's reports.
|
||||
- `scratch/check_s3_decode.py <binaries> <xml reports>` decodes each event
|
||||
the way ingest does, from its bytes alone (no filename, no report).
|
||||
- It compares every field, waveform sample and histogram interval with
|
||||
Blastware's `_XML.XML` report of the same event. DL2's `Sent/` holds
|
||||
those reports, every sample included, for 70,042 events back to 2016;
|
||||
its ASCII reports start in 2025.
|
||||
- Each comparison gets one verdict: match, mismatch, SFM blank, accepted
|
||||
(a written carve-out with evidence), no reference, or error.
|
||||
- **Any disagreement counts as SFM's bug** unless a carve-out covers it.
|
||||
The only carve-out so far is saturation: Blastware clamps a clipped
|
||||
channel and prints `OORANGE`.
|
||||
- **Output** goes to `~/dl2-archive/checker-runs/<time>/`, outside the
|
||||
repo, because it carries customer names:
|
||||
- `summary.md`: per-field counts and how many fields fully match
|
||||
- `details.json`: failures grouped by what the failing events share,
|
||||
with example events and one-event re-run commands
|
||||
- `changes.md`: regressions against the last run of the same scope
|
||||
- **Running it:** a full run takes ~22 min at `--jobs 4`. `--file NAME`
|
||||
checks one event in seconds. Partial runs: `--serial`, `--year`,
|
||||
`--type`, `--field`, `--sample`.
|
||||
- **Code:** the comparison is pure codec-library code that ingest can
|
||||
call later: `minimateplus/bw_xml_report.py`,
|
||||
`minimateplus/decode_check.py`,
|
||||
`minimateplus/decode_check_carveouts.py`. The runner and reports are
|
||||
lab tools in `scratch/`. Design and plan are in `docs/superpowers/`.
|
||||
- **First full run (70,112 files; 70 have no report):** 5 of 88 fields
|
||||
fully match: sample rate, record time, pre-trigger, notes and waveform
|
||||
event date.
|
||||
- Geophone samples are exact on 6,491 / 6,524 waveforms in every year.
|
||||
The 33 others are on the 1.250 in/s range, read 8× by SFM's
|
||||
Normal-range assumption.
|
||||
- Every histogram reads as a waveform without its filename (#41).
|
||||
- Histogram start times are 1 s early (#51).
|
||||
- Open findings:
|
||||
- histogram PVS: SFM takes the vector magnitude of each channel's
|
||||
interval peak; Blastware takes the per-interval vector sum
|
||||
- mic psi conversion
|
||||
- mic dB on ~1,000 events
|
||||
- 35 sub-minute histograms plus 2 one-minute no-mic ones
|
||||
- 26 histogram start dates
|
||||
- job number, ZC frequency, acceleration, displacement, time of peak,
|
||||
sensor check, battery, calibration, range, units and monitor log
|
||||
are not read yet
|
||||
- Later in this release, the record type (#41), the histogram vector sum
|
||||
and the mic conversion were fixed. See their entries above; each was
|
||||
proven by a full checker run with 0 regressions.
|
||||
- It replaces `scratch/verify_bw_fields_against_xml.py`, added and
|
||||
removed within this release.
|
||||
- **Operational consequence: none.** Nothing on the ingest path changes.
|
||||
No schema change, no migration, `TOOL_VERSION` unchanged by this item.
|
||||
- **README roadmap:** a bulk event importer, parked.
|
||||
|
||||
### Changed
|
||||
- **`CLAUDE.md`:** the 14,338 ASCII-report pairs were said to reach "back
|
||||
to 2018"; they are all 2025–26 events. Corrected in place. A "Where
|
||||
things stand" entry records the decode checker and its first run.
|
||||
- **`docs/instantel_protocol_reference.md`:** the #53 note is corrected in
|
||||
place. `K440I4LG.JK0W`, `K888HW07.7K0W` and `R349KPNU.FK0W` do not decode
|
||||
as histograms. They decode as waveforms with Blastware's full sample
|
||||
count; only their time falls back to the footer start, 3–4 s late, with
|
||||
no `decode_problems` entry.
|
||||
- **The SFM / SDM tier model in `CLAUDE.md` is marked superseded** by
|
||||
Terra-View's ADR 0003 (`docs/adr/0003-stack-components-and-names.md`).
|
||||
- SFM is the whole seismograph module, and "SDM" is retired as a name.
|
||||
- The codec library stays pure.
|
||||
- Lab tools (`bridges/` bench tools, `scratch/`, `seismo_lab.py`) are to
|
||||
leave the production image, and are ported into `sfm/` when they become
|
||||
production tools.
|
||||
- The call-in server becomes SFM's front door after a staged proof.
|
||||
- The repo becomes `sfm` after `feat/series4-sfm-parity` merges.
|
||||
|
||||
The old section stays below the banner as history.
|
||||
Docs only: no code or schema change, no migration, `TOOL_VERSION` unchanged.
|
||||
|
||||
### Migration
|
||||
|
||||
⚠ **This release owes prod a backfill.** It does not move stored event times.
|
||||
|
||||
**Before you start:**
|
||||
- `TOOL_VERSION` is bumped to **0.33.0**, which gates the regeneration, so no
|
||||
`--force` is needed.
|
||||
- No parser change, so no `--reparse-txt` is needed.
|
||||
- No schema change.
|
||||
- **Back up `seismo_relay.db` first.**
|
||||
|
||||
**Then, in the `sfm` container, in this order** (the scripts default to
|
||||
`bridges/captures/seismo_relay.db` and its `waveforms/`):
|
||||
|
||||
1. `python scripts/backfill_sidecars.py` re-decodes every Series-3 event file
|
||||
whose sidecar predates 0.33.0. Sidecars and `.h5` files regenerate, and each
|
||||
DB row refreshes in place (id and review kept). ⚠ **~2 h on the NAS.**
|
||||
- **Report-less events** pick up the new values: sample rate, record time,
|
||||
pre-trigger, notes, record type, histogram vector sum, mic.
|
||||
- **Report-paired events** keep the report's values.
|
||||
- **The record type** stays the same for every ACH file (`…W` / `…H`). Only a
|
||||
histogram stored under a 3-character manual-download name flips from
|
||||
Waveform to Histogram.
|
||||
2. `python scripts/backfill_event_shape.py --db-path bridges/captures/seismo_relay.db
|
||||
--store-root bridges/captures/waveforms` recomputes the shape and offset
|
||||
metrics from the regenerated files.
|
||||
|
||||
Series-4 (Thor) events are untouched; nothing in their decode changed.
|
||||
|
||||
**Not rehearsed on a prod snapshot** (v0.32.0 was). The risk is lower:
|
||||
- Event times do not move, so every row is matched in place.
|
||||
- No row is created or removed.
|
||||
- The full decode checker ran clean against all 70,112 DL2 event files before
|
||||
release.
|
||||
|
||||
**Afterwards**, the DL2 watcher can be widened for the 2016–2024 backfill:
|
||||
`MAX_EVENT_AGE_DAYS = 2130` reaches 2021. Set it back to 365 when done,
|
||||
because the same setting widens the heartbeat's scan.
|
||||
|
||||
---
|
||||
|
||||
## v0.32.0 — 2026-10-27
|
||||
|
||||
**Event times you can trust, and Series 4 mapped end to end.** Two threads.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
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.32.0**.
|
||||
(Sierra Wireless RV50 / RV55). Current version: **v0.33.0**.
|
||||
|
||||
Stack-level context — which repo owns what, and how the three project versions
|
||||
pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as
|
||||
@@ -10,10 +10,49 @@ pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as
|
||||
|
||||
---
|
||||
|
||||
## Where things stand (updated 2026-10-19)
|
||||
## Where things stand (updated 2026-11-02)
|
||||
|
||||
Read this first when picking the project back up.
|
||||
|
||||
- **🔑 The Series-3 decode checker (2026-10-29; v0.33.0).**
|
||||
- **Goal:** SFM produces everything Blastware reports, from the event file
|
||||
alone (spec and plan in `docs/superpowers/`).
|
||||
- **Running it:** `scratch/check_s3_decode.py ~/dl2-archive/files
|
||||
~/dl2-archive/xml` decodes each event from its bytes only (no filename, no
|
||||
report). It compares every field, sample and interval with Blastware's
|
||||
`_XML.XML`: 70,042 events, 2016–2026, ~22 min at `--jobs 4`.
|
||||
- **Output** (`summary.md`, `details.json`, `changes.md`) goes to
|
||||
`~/dl2-archive/checker-runs/` and is never committed.
|
||||
- **The rule:** every mismatch is SFM's bug unless a carve-out with evidence
|
||||
covers it.
|
||||
- **Byte layouts** of every field read from the file:
|
||||
`docs/instantel_protocol_reference.md` Appendix **D.6**.
|
||||
|
||||
**As of v0.33.0, plus the range fix on `dev` (`057df47`, 2026-11-02):**
|
||||
- ✅ **Match on every event:** sample rate, record time, pre-trigger, notes,
|
||||
event type (#41, from STRT[18]), and geophone range (`dev`).
|
||||
- ✅ **Geophone samples** are exact on **6,524 / 6,524** waveforms in every
|
||||
year (`dev`). v0.33.0 had 6,491: the 33 others were on the 1.250 in/s
|
||||
range, 8× high under SFM's old Normal-range assumption.
|
||||
- ✅ **Histogram PVS** = the stored per-interval PVS²: 69,952 / 70,042.
|
||||
- ✅ **Mic: one count = 0.25 Pa,** with Blastware's dB offset at 81.9384. It
|
||||
fails on only a few dozen events.
|
||||
- ❌ **Open:**
|
||||
- histogram start times are 1 s early (#51)
|
||||
- 35 sub-minute (5 s / 2 s) histograms decode wrongly, plus 2 one-minute
|
||||
no-mic histograms (`R352HFZ7`-shaped, likely a separate cause)
|
||||
- 26 histogram start dates are a day off
|
||||
- the per-interval PVS is not stored
|
||||
- Blastware prints `OORANGE` when the vector sum alone exceeds the range
|
||||
(a carve-out to prove)
|
||||
- ⬜ **Not read yet:** job number, ZC frequency, acceleration, displacement,
|
||||
time of peak, sensor check, battery, calibration, units, monitor log.
|
||||
- 🔶 **#48 is still open.** The event file's setup block puts the pre-trigger
|
||||
where the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though,
|
||||
it is **each event's own pre-trigger**, not the setting: 253–256 samples at
|
||||
1024 sps, alternating on the same unit on the same day, and reported that
|
||||
way by Blastware. So the files say little about whether the live 1A read
|
||||
loses its anchor (reference D.6.2).
|
||||
- **The Series-4 LIVE wire protocol is reverse-engineered end to end
|
||||
(2026-09-25).** `docs/micromate_protocol_reference.md` is the Series-4
|
||||
Rosetta Stone, sibling to `instantel_protocol_reference.md`. **A Micromate
|
||||
@@ -129,7 +168,13 @@ Read this first when picking the project back up.
|
||||
- **Series-3 decode is verified per-sample at scale (v0.27.0).** The full DL2
|
||||
archive decodes **14,338 / 14,338** paired files exactly against their
|
||||
preserved Blastware ASCII exports — 1,249 waveform + 13,089 histogram, 45
|
||||
units, files back to 2018. That is 11x the ground truth the prod store
|
||||
units, files back to 2018. ⚠ **Corrected 2026-10-29:** the 14,338 pairs
|
||||
are all events from 2025–26 (five more carry a 1995 clock); DL2 kept ASCII
|
||||
reports only from 2025. 🔑 Its `Sent/<stem>_<ext>_XML.XML` files are
|
||||
Blastware's full event report — every report field plus every sample —
|
||||
for **70,042 events back to 2016**, local copy `~/dl2-archive/xml`.
|
||||
`scratch/verify_bw_fields_against_xml.py` checks file-only fields against
|
||||
them. That is 11x the ground truth the prod store
|
||||
carried, and it supersedes the old "per-sample on 11%, peak-only on 89%"
|
||||
caveat. Harness: `scratch/verify_against_ascii.py` (note its saturation
|
||||
carve-out — BW clamps clipped events, the decoder reports true counts).
|
||||
@@ -191,8 +236,9 @@ Read this first when picking the project back up.
|
||||
over) needs a BW capture of a spanning event first. Do not ship layer one
|
||||
alone without a loud truncation warning — a silently short event is the
|
||||
failure mode this codec has been bitten by repeatedly.
|
||||
- **Open, not blocking:** 14 sensitive-range files show an exact 8x
|
||||
(= 10.0/1.25) units discrepancy; `scripts/backfill_sidecars.py --force` also
|
||||
- **Open, not blocking:** ~~14 sensitive-range files show an exact 8x
|
||||
(= 10.0/1.25) units discrepancy~~ (**resolved on `dev` 2026-11-02:** the
|
||||
range is read from the file, reference D.6.4); `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`
|
||||
@@ -276,6 +322,26 @@ dedicated release commit when you are ready to ship to `main`.**
|
||||
|
||||
## Architecture: three-tier conceptual model
|
||||
|
||||
> ⚠ **SUPERSEDED 2026-10-27 by Terra-View's
|
||||
> [`docs/adr/0003-stack-components-and-names.md`](../terra-view/docs/adr/0003-stack-components-and-names.md).**
|
||||
> The SFM / SDM split below is retired.
|
||||
> - **SFM is the whole seismograph module:** the call-in server, the adapters,
|
||||
> decoding, the store, per-event measurements and the API. "SDM" is not
|
||||
> used as a name any more.
|
||||
> - **The codec library stays pure**, as described in tier 3. That rule
|
||||
> survives unchanged.
|
||||
> - **Lab tools** (`bridges/` bench tools, `scratch/`, `seismo_lab.py`) are
|
||||
> experimental and are to leave the production image. One that becomes a
|
||||
> real production tool is *ported* into `sfm/`, rebuilt on
|
||||
> `sfm/device_access`.
|
||||
> - **The call-in server** (today's `bridges/ach_server.py` and
|
||||
> `bridges/mm_ach_server.py`) becomes SFM's front door, after the staged
|
||||
> proof in the ADR.
|
||||
> - **The repo becomes `sfm`** after `feat/series4-sfm-parity` merges.
|
||||
>
|
||||
> The text below is history, kept in place per this repo's retraction
|
||||
> convention.
|
||||
|
||||
seismo-relay is a **suite of cooperating components**, not a single app.
|
||||
The three tiers below are the canonical mental model — the current
|
||||
directory layout doesn't fully reflect them yet (some of what is
|
||||
@@ -582,6 +648,14 @@ block still covers exactly one minute:
|
||||
| 15 s | 4 | 92 |
|
||||
| 2 s | 30 | 612 |
|
||||
|
||||
> ⚠ **CORRECTED in v0.32.0 (#47/#49), recorded here 2026-11-02.** The
|
||||
> records are **big-endian, starting at byte 5**. Each holds a uint16 peak
|
||||
> and a uint16 half-period per channel, then the interval's **PVS² as a
|
||||
> uint32 BE**. Record = 4 × channels + 4 bytes: 20 with the mic, 16
|
||||
> without. `stride = 12 + n × record`. The little-endian reading below was
|
||||
> the same words shifted by one byte. Its "2-word tail" is the PVS²
|
||||
> (reference D.6.5).
|
||||
|
||||
`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`)
|
||||
@@ -589,6 +663,7 @@ 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.
|
||||
*(Retracted: both are big-endian; see the box above.)*
|
||||
|
||||
Recovers **415 files** (216 on BE18193, 199 on BE9440) that decoded to
|
||||
nothing. Ground truth `BE9440/K440L3AQ.T70H` matches its BW ASCII export
|
||||
@@ -616,6 +691,9 @@ block has its own tail signature. Two long-standing errors:
|
||||
`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.
|
||||
- **`[21:25]` is the interval's PVS² as a uint32 BE** (v0.33.0, reference
|
||||
D.6.5). The "arbitrary bytes" above are probably its high half
|
||||
(inferred).
|
||||
|
||||
Verified against 1211 production histograms paired with their BW ASCII
|
||||
exports: **1211/1211 decode exactly** (interval count plus every
|
||||
@@ -624,11 +702,13 @@ with zero mismatches. Before: 1 of 1196.
|
||||
|
||||
### What's NOT solved
|
||||
|
||||
- **MicL channel conversion to dB(L)** — the codec emits MicL as
|
||||
- ~~**MicL channel conversion to dB(L)** — the codec emits MicL as
|
||||
raw ADC counts (same format as geo channels), but BW's ASCII export
|
||||
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.
|
||||
`dB = 20*log10(|counts|) + offset` or similar.~~ **Solved in v0.33.0.**
|
||||
One count = 0.25 Pa, and dB(L) = 81.9384 + 20·log10(|count|), an offset
|
||||
measured from Blastware's printed values (reference D.6.6).
|
||||
- **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
|
||||
@@ -1287,7 +1367,7 @@ Do NOT use fixed absolute offsets for sample_rate or record_time.
|
||||
| trigger_level_geo | float32 BE, located in channel block |
|
||||
| alarm_level_geo | float32 BE, adjacent to trigger_level_geo |
|
||||
| geo_hardware_constant (adc_scale_factor) | float32 BE at **channel_label+28** in both read (E5) and write (SUB 71) payloads — reads **6.206053** on BOTH tested units (BE11529 and BE18189); identical across all geo channels (Tran/Vert/Long) and all captures. **Confirmed 2026-04-17 from Interface Handbook §4.5**: this is the **ADC-to-velocity scale factor** = 1/sensitivity = (in/s per V). Firmware uses it as: `PPV (in/s) = ADC_voltage × 6.206053`. Cross-check: `1.61133 V (ADC full-scale) × 6.206053 = 10.000 in/s` (Normal range ✅). Do NOT write this field — it is a hardware/firmware constant. |
|
||||
| geo_range (sensitivity selector) | **uint8 at channel_label+33** in both read (E5) and write (SUB 71) payloads — **CONFIRMED 2026-04-20** from 4-20-26 geo sensitivity captures: `0x00` = Normal 10.000 in/s (standard gain), `0x01` = Sensitive 1.250 in/s (high gain). Present in all three geo channel blocks (Tran, Vert, Long). **NOTE: `channel_label+20` reads `0x01` on ALL captures regardless of range setting — it is NOT this field.** Note: the "SUB 71 write offset = +29" that appears in earlier analysis was an artifact of incorrect BW-style destuffing applied to write frame data — write frame data is RAW, so the literal `0x10` bytes in the channel block header are preserved, and the offset is the same as in the E5 read payload. |
|
||||
| geo_range (sensitivity selector) | **uint8 at channel_label+33** in both read (E5) and write (SUB 71) payloads (an event file's setup copy has it at label+29: reference D.6.4) — **CONFIRMED 2026-04-20** from 4-20-26 geo sensitivity captures: `0x00` = Normal 10.000 in/s (standard gain), `0x01` = Sensitive 1.250 in/s (high gain). Present in all three geo channel blocks (Tran, Vert, Long). **NOTE: `channel_label+20` reads `0x01` on ALL captures regardless of range setting — it is NOT this field.** Note: the "SUB 71 write offset = +29" that appears in earlier analysis was an artifact of incorrect BW-style destuffing applied to write frame data — write frame data is RAW, so the literal `0x10` bytes in the channel block header are preserved, and the offset is the same as in the E5 read payload. |
|
||||
| setup_name | ASCII, null-padded, in cfg body |
|
||||
| project / client / operator / sensor_location | ASCII, label-value pairs |
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# seismo-relay `v0.32.0`
|
||||
# seismo-relay `v0.33.0`
|
||||
|
||||
A ground-up replacement for **Blastware** — Instantel's aging Windows-only
|
||||
software for managing seismographs. Supports both the **MiniMate Plus
|
||||
@@ -74,6 +74,27 @@ over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55).
|
||||
>
|
||||
> ⚠ The deploy owes a backfill and moves stored waveform times; see the
|
||||
> changelog's *Migration*.
|
||||
>
|
||||
> **v0.33.0 (2026-11-01)** reads Series-III events from the file alone, and
|
||||
> proves it.
|
||||
> - **Fields now read from the event file** when no Blastware report comes with
|
||||
> the event:
|
||||
> - sample rate, record time, pre-trigger and the four notes (#44/#45)
|
||||
> - the event type (#41)
|
||||
> - a histogram's peak vector sum, which the unit stores per interval
|
||||
> - the mic, at one count = 0.25 Pa (it read ~95× low in psi)
|
||||
>
|
||||
> This matters for every DL2 event from before 2025, and for SFM's own
|
||||
> download and call-in paths, none of which have a report.
|
||||
> - **The decode checker** (`scratch/check_s3_decode.py`) compares SFM's
|
||||
> file-only decode with Blastware's `_XML.XML` event reports, field by field
|
||||
> and sample by sample, for 70,042 DL2 events back to 2016:
|
||||
> - every setup field, the notes and the event type match on every event
|
||||
> - geophone samples are exact on 6,491 / 6,524 waveforms
|
||||
> - the histogram vector sum matches on 69,919
|
||||
>
|
||||
> ⚠ The deploy owes a backfill; it does not move event times. See the
|
||||
> changelog's *Migration*.
|
||||
> See [CHANGELOG.md](CHANGELOG.md) for full version history.
|
||||
|
||||
---
|
||||
@@ -600,7 +621,16 @@ Implementation steps (concrete):
|
||||
|
||||
### 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.
|
||||
- [x] **Series III waveform body codec reverse-engineering.** ✅ The body codec is fully decoded (`minimateplus/waveform_codec.py`, `histogram_codec.py`), and verified per-sample against Blastware's own exports. As of v0.33.0, geophone samples are exact on 6,491 / 6,524 DL2 waveforms against their `_XML.XML` reports, across 2016–2026.
|
||||
- [ ] **SFM produces everything Blastware reports, from the event file alone.** The four-piece plan:
|
||||
1. the decode checker ✅ v0.33.0
|
||||
2. complete the file-only decode, one field group at a time, each proven by the checker
|
||||
3. flip ingest so reports are kept only for checking
|
||||
4. stop the watchers forwarding reports
|
||||
|
||||
**Done so far:** setup fields, notes, event type, histogram PVS, mic.
|
||||
|
||||
**Next:** histogram start times (#51), the 37 histograms that decode wrongly, the job number, the geophone range (Sensitive-range events read 8×), and the values Blastware computes itself (ZC frequency, acceleration, displacement, time of peak), plus the sensor check, battery, calibration and monitor log. Design: `docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`.
|
||||
- [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).
|
||||
@@ -616,6 +646,8 @@ Implementation steps (concrete):
|
||||
|
||||
### Ingestion gaps
|
||||
|
||||
- [ ] **Event importer (parked 2026-10-29).** A way to load a folder of event files from disk into SFM in bulk — a historical archive, a laptop's Blastware folder, a backup — without routing them through a watcher. It is one of the four ways events should reach SFM (watcher forward, upload from disk, SFM's own serial/modem download, SFM's future call-in server). Prompted by DL2's 2016–2024 backfill, which the watcher could only drip-feed at 500 events a pass.
|
||||
|
||||
- [ ] **MLG forwarding.** `series3-watcher` forwards event binaries + their `_ASCII.TXT` reports, but skips `.MLG` per-unit monitor log files entirely. Adding an `POST /db/import/mlg_file` endpoint + watcher scan path would populate `monitor_log` for non-ACH-routed units (coverage queries, "was this unit monitoring on date X" lookups).
|
||||
- [ ] **0C-record raw bytes persistence in the sidecar.** Currently on branch `claude/codec-re-cBGNe` as commit `a187124`; cherry-pick if useful as a standalone fix. Preserves the 210-byte 0C record under `extensions.raw_records.waveform_record_b64` so future field-offset analysis (Peak Acceleration / Time of Peak / etc. — the fields BW computes client-side from samples) can run offline.
|
||||
|
||||
|
||||
@@ -11,9 +11,10 @@
|
||||
|
||||
| Date | Section | Change |
|
||||
|---|---|---|
|
||||
| 2026-11-02 | Appendix D.3.1, D.6 (NEW), §15 | ✅ **Event fields SFM reads from the file alone (v0.33.0, plus the range on `dev`).** New D.6 records the bytes and the DL2 verification for each field: the record type `STRT[18]`, the recording-setup block (sample rate, pre-trigger, record time, the four notes), the geophone range (label + 29 in the setup's channel blocks), each histogram interval's PVS², and the mic scale (one count = 0.25 Pa). **Retracted in place:** D.3.1's `STRT[20]` = record time (it is `00` on every DL2 file; the "70 s" SFM used to report was `STRT[18]`, the record-type byte), and the 2026-08-26 reading of sub-minute histogram records as little-endian (big-endian from byte 5 since v0.32.0, #47/#49). **For #48:** the file's copy of the block puts the pre-trigger where the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though, it is each event's own pre-trigger, which varies on the same unit on the same day (253–256 samples at 1024 sps), and Blastware reports it per event. So the file says little about whether the live 1A loses its anchor, and #48 stays open. |
|
||||
| 2026-10-26 (5) | §7.8.9 | ✅ **The embedded event record: the instrument's trigger time, inside the 5A stream.** Every Blastware waveform file carries `00 28 05 00 ?? ?? fe 80 [trigger 8 B][stop 8 B]`, times as `dd mm yyyy(BE) 00 hh mm ss`. The trigger equals Blastware's report 1,320/1,320, the filename 7,935/7,935 and the unit's 0C record 10/10. It occurs once in the unit's own A5 payloads (8/8 events) and in SFM-only downloads (2/2): instrument data, not Blastware's. The footer's `ts2 - record time` is only an estimate, a second off on ~19%. Decoder rule, validation and an open case (3 waveform-named files the codec does not recognise) in §7.8.9. 🔶 The §7.5 `0C` "sub_code" timestamp variants look like the same 8-byte form read with its escapes. |
|
||||
| 2026-10-17 | §7.6.1 | 🔶 **OPEN — the 6-byte "stable anchor" may be two settings at their defaults, not a constant.** Series IV's `0x1A` has the same field order as the S3 compliance block, and a keypad diff pass on a Micromate (UM20147) measured the bytes in the anchor's position: `[f32 BE pre-trigger, negative seconds][record stop mode, 00 00 = Fixed]`. `be 80 00 00` is exactly −0.25 s. If S3 matches — **inferred, not measured on S3** — then any S3 unit set to Record Stop Mode = Auto (a basic Blastware Compliance Setup option) or a non-default pre-trigger loses the anchor, and `client.py` silently decodes no recording mode / sample rate / interval / record time and skips them on write. No S3 capture has ever been taken in Auto stop mode (see the 2026-03-09 Auto Window rows), which would explain why the anchor never broke. To settle: one BW capture with Record Stop Mode = Auto. See `docs/micromate_protocol_reference.md` → *The `0x1A` field map from a keypad pass*. |
|
||||
| 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-26 | S7.6.2, S15 | **MULTI-INTERVAL HISTOGRAM BLOCKS - sub-minute intervals pack several per block.** ⚠ *Corrected 2026-11-02: the records are big-endian from byte 5, not little-endian (v0.32.0, #47/#49), and the "2-word tail" is the interval's PVS². See D.6.5.* 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. |
|
||||
@@ -2309,6 +2310,14 @@ The early captures were all in April (month `04`, sent as `10 04`). Not changed
|
||||
codec. They are decoded as histograms and stamped with the footer start, 4 s off; `dev`
|
||||
behaves the same. Prod's store has none. Tracked in #53.
|
||||
|
||||
⚠ **Corrected 2026-10-29 (measured against their Blastware `_XML.XML` reports):** they
|
||||
do **not** decode as histograms. All three decode as waveforms with Blastware's full
|
||||
sample count (4,352 / 4,352 / 13,280 rows), and their record time and sample rate are
|
||||
read. Only the time is wrong: no footer stop time (`ts2`) is read, so the decoder falls
|
||||
back to the footer start -- 11:14:12 / 11:14:12 / 16:14:11 against Blastware's
|
||||
11:14:08 / 11:14:08 / 16:14:08 -- and records no `decode_problems` entry. 🔶 Inferred,
|
||||
from the decode-checker design review: the decoder takes an earlier, false footer.
|
||||
|
||||
## 7.9 Compliance Config Field Inventory (Blastware UI, 2026-04-08) ✅
|
||||
|
||||
Fields visible in the Blastware "Compliance Setup" dialog. ✅ = byte offset confirmed in code. ❓ = not yet located in raw bytes.
|
||||
@@ -3162,7 +3171,7 @@ The `.bin` files produced by `s3_bridge` are **not raw wire bytes**. The logger
|
||||
| **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 |
|
||||
| ~~**Unmapped histogram block variant (415 files, 2 units)**~~ - **RESOLVED 2026-08-26.** ⚠ *Corrected 2026-11-02: the records are big-endian from byte 5, not little-endian (v0.32.0, #47/#49), and the "2-word tail" is the interval's PVS². See D.6.5.* 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 |
|
||||
|
||||
@@ -3389,8 +3398,16 @@ The STRT record immediately follows the 22-byte header.
|
||||
| 4 | 2 | `ff fe` | Fixed |
|
||||
| 6 | 4 | event key (key4) | 4-byte waveform key |
|
||||
| 10 | 4 | device-specific | NOT a repeat of key4 — device-internal field |
|
||||
| 14 | 6 | device-specific | NOT zero-padded — device-internal fields |
|
||||
| 20 | 1 | rectime | uint8 seconds |
|
||||
| 14 | 4 | device-specific | not identified (see the retraction below) |
|
||||
| 18 | 1 | **record type** ✅ | `0x46` waveform, `0x0A` histogram: 6,541 / 6,541 `…W` and 63,500 / 63,500 `…H` DL2 files (2026-11-02). See D.6.1 |
|
||||
| 19 | 2 | `00 00` | zero on 70,041 / 70,041 DL2 files |
|
||||
|
||||
> ⚠ **RETRACTED 2026-11-02.** This table used to end `| 14 | 6 | device-specific |` and
|
||||
> `| 20 | 1 | rectime | uint8 seconds |`. `STRT[20]` is `0x00` on every DL2 file, so it is not
|
||||
> the record time. Until v0.33.0, SFM read a record time from `STRT[18]`, the record-type byte,
|
||||
> which is why every waveform reported "70 s" (`0x46`). It also read pre-trigger and sample count
|
||||
> from `[16:18]`; both were wrong (#45). The record time and pre-trigger live in the
|
||||
> recording-setup block (D.6.2).
|
||||
|
||||
**Critical:** The STRT record must be copied verbatim from A5[0].data[7+strt_pos:] — bytes [10:20] contain device-specific values that cannot be reconstructed from protocol-level Event fields alone.
|
||||
|
||||
@@ -3568,6 +3585,10 @@ observed) and does NOT follow the AB0T formula.
|
||||
|
||||
**DLE-shift offset note for reading recording_mode from N00/9T0 body:**
|
||||
|
||||
> ⚠ **2026-11-02:** this note finds the block by the 6-byte anchor. In an event file that anchor
|
||||
> exists only when the event's own pre-trigger is exactly −0.25 s: 3,886 / 6,541 DL2 waveforms,
|
||||
> and no histogram. Find the block by its setup name instead (D.6.2).
|
||||
|
||||
The compliance block in the file body has been through `_strip_inner_frame_dles`. The 0x10 constant at logical `anchor−7` (between recording_mode and sample_rate_HI) gets stripped when sample_rate_HI = `0x04` (1024 sps), because `0x10` precedes `0x04 ∈ {0x02,0x03,0x04}`. After stripping, the anchor shifts left by 1, so:
|
||||
|
||||
| 1024 sps (strip occurs) | 2048 or 4096 sps (no strip) |
|
||||
@@ -3586,6 +3607,155 @@ file[anc−4]: histogram_interval_HI
|
||||
file[anc−3]: histogram_interval_LO
|
||||
```
|
||||
|
||||
### D.6 Event fields read from the file alone ✅ 2026-10-29 → 2026-11-02
|
||||
|
||||
Since v0.33.0, SFM decodes the fields below from an event file's bytes alone: no filename, no
|
||||
Blastware report. The code is in `minimateplus/event_file_io.py`, `histogram_codec.py` and
|
||||
`waveform_codec.py`.
|
||||
|
||||
Each field was proven by the decode checker, `scratch/check_s3_decode.py`. It compares SFM's
|
||||
decode with Blastware's `_XML.XML` report for every DL2 event: 70,042 events, 2016–2026, local
|
||||
copy in `~/dl2-archive`. Counts below are from that archive unless stated otherwise.
|
||||
|
||||
#### D.6.1 Record type — `STRT[18]` ✅
|
||||
|
||||
| `STRT[18]` | Type | DL2 |
|
||||
|---|---|---|
|
||||
| `0x46` | Waveform | 6,541 / 6,541 `…W` files |
|
||||
| `0x0A` | Histogram | 63,500 / 63,500 `…H` files |
|
||||
|
||||
- The 5A stream shows the same byte after the STRT keys (§7.8.5, `data[35]`).
|
||||
- The filename's `W` / `H` is only a cross-check. On a disagreement SFM logs it and keeps the
|
||||
byte (#41).
|
||||
- Checker, event type: 70,042 / 70,042.
|
||||
|
||||
#### D.6.2 Recording-setup block — sample rate, pre-trigger, record time ✅
|
||||
|
||||
**Find the block by structure:** `1c 08`, then the setup name (1–40 printable ASCII), then `00`.
|
||||
That pattern occurs exactly once in every DL2 file. Do not search for the name "Standard
|
||||
Recording Setup": 37% of DL2 files use another name.
|
||||
|
||||
Offsets are from `k`, the first byte of the setup name:
|
||||
|
||||
| Offset | Type | Field | Notes |
|
||||
|---|---|---|---|
|
||||
| `k − 42` | uint16 BE | sample rate | 1024 / 2048 / 4096 |
|
||||
| `k − 36` | float32 BE | pre-trigger | seconds, ≤ 0: `−0.25` is a quarter second before the trigger. **This event's own length, not the unit's setting** (below) |
|
||||
| `k − 32` | 2 bytes | — | `00 00` on 70,041 / 70,041 files |
|
||||
| `k − 30` | float32 BE | record time | seconds |
|
||||
|
||||
- Pre-trigger samples = `round(−pre-trigger × sample rate)`.
|
||||
- A histogram carries the block too, with pre-trigger `0.0` (63,500 / 63,500). Blastware reports
|
||||
no record time or pre-trigger for a histogram, and SFM reports none.
|
||||
- Sample rate, record time and pre-trigger match Blastware on every DL2 event that reports them
|
||||
(#44, #45).
|
||||
|
||||
⚠ **The file's pre-trigger is the event's, not the setting (measured 2026-11-02).**
|
||||
- **It varies from event to event on the same unit, often on the same day.** BE18193 has both
|
||||
−0.25 and −0.248 on 2026-08-21.
|
||||
- At 1024 sps the common values −0.25, −0.249, −0.248 and −0.2471 are 256, 255, 254 and 253
|
||||
samples.
|
||||
- At 4096 sps, BE18193's events range from −0.002 to −0.249 s.
|
||||
- **Blastware reports the same per-event value** as `Pre-triggerLength`, for example
|
||||
`-0.094 sec` for `T193KMX5.4Z0W`.
|
||||
- 🔶 Inferred: the unit's setting stays fixed while the captured length falls short of it. Why it
|
||||
falls short is unknown.
|
||||
|
||||
**What this means for #48 (the 1A "stable anchor"):**
|
||||
- This is the 1A compliance layout. Sample rate at anchor − 6 and record time at anchor + 6
|
||||
(§7.6.1) put the anchor at `k − 36`, so the 6-byte `be 80 00 00 00 00` is a pre-trigger of
|
||||
−0.25 s followed by the `00 00` at `k − 32`.
|
||||
- **In a file**, the anchor bytes appear only when that event's pre-trigger is exactly −0.25 s:
|
||||
3,886 / 6,541 waveforms, and no histogram (histogram files store 0.0). A file parser that
|
||||
searches for the anchor breaks on the rest. SFM's file decoder finds the block by its setup
|
||||
name instead.
|
||||
- **The live 1A read holds the setting, not an event's length.** So these files say little about
|
||||
whether the live read loses its anchor; #48 is still unsettled.
|
||||
- `k − 32 : k − 30` is `00 00` on all 70,041 files. 🔶 If `[17]` is the stop mode, as on
|
||||
Series IV, no DL2 event was recorded in Auto stop mode, so the archive cannot test that case.
|
||||
- The two blocks differ in at least one field. A live 1A in Histogram mode showed the anchor
|
||||
(−0.25 s), but histogram files store 0.0.
|
||||
|
||||
#### D.6.3 Notes — four label/value pairs after the name ✅
|
||||
|
||||
- After the name's `00`, NUL-terminated `label`, `value` pairs fill four slots, in order:
|
||||
project, client, operator ("User Name") and sensor location ("Seis Loc").
|
||||
- **Read them by position, never by label.** Blastware lets the operator relabel the slots
|
||||
("Seis. Loc:", "Location:", "Project: ").
|
||||
- An empty value means none.
|
||||
- They match Blastware on every DL2 event.
|
||||
- Not read yet: extended notes, job number.
|
||||
|
||||
#### D.6.4 Geophone range — the setup's channel blocks ✅ 2026-11-01
|
||||
|
||||
The channel blocks follow the notes, within 2,000 bytes of the name: `00 00 01` then `Tran` /
|
||||
`Vert` / `Long`. The range is the byte at label + 29, where label is the first byte of
|
||||
`Tran` / `Vert` / `Long`:
|
||||
|
||||
| label + 29 | Range | Full scale |
|
||||
|---|---|---|
|
||||
| `0x00` | Normal | 10.000 in/s |
|
||||
| `0x01` | Sensitive | 1.250 in/s |
|
||||
|
||||
- It matches the report's `GeoRange` on 70,042 / 70,042 events. The three channels agree on
|
||||
every event, and 35 are Sensitive.
|
||||
- The live 1A carries the same byte at label + 33 (§7.6, confirmed 2026-04-20).
|
||||
- Full scale is 32,000 counts at either range, so a Sensitive count is 8× smaller.
|
||||
- Until `dev` `057df47` (2026-11-02), SFM assumed Normal and read every Sensitive event 8× high.
|
||||
- If the channels disagree, a value is unknown or a block is missing, SFM reports no range, logs
|
||||
a decode problem and assumes Normal.
|
||||
|
||||
#### D.6.5 Histogram interval peak vector sum ✅ 2026-10-30
|
||||
|
||||
Each interval stores its peak vector sum **squared**:
|
||||
|
||||
| Block | Where | Type |
|
||||
|---|---|---|
|
||||
| Standard 32-byte block (intervals of a minute or more) | `[21:25]` | uint32 BE |
|
||||
| Sub-minute record | the record's last 4 bytes | uint32 BE |
|
||||
|
||||
- `PVS = √value × unit`. The unit is 16 counts: 0.005 in/s at Normal, 0.000625 in/s at
|
||||
Sensitive.
|
||||
- **The event's PVS is the largest interval's.** Combining the three channel peaks instead read
|
||||
high on 86% of DL2 histograms, because the peaks can come from different moments.
|
||||
- **Verified:** √value matches Blastware's "Geo PVS" on 34.5 M DL2 sub-minute intervals, and the
|
||||
event PVS matches on 69,952 / 70,042 events. The rest are the open histogram cases in D.6.7.
|
||||
- 🔶 On the stream's last block, the "arbitrary bytes at [21:23]" in the 2026-08-25 note are
|
||||
probably the high half of this field (inferred from the layout, not measured).
|
||||
|
||||
**Sub-minute records (corrected in v0.32.0, #47/#49):**
|
||||
- They are **big-endian, starting at byte 5** of the block.
|
||||
- Each holds, per channel, a uint16 peak and a uint16 half-period (Tran, Vert, Long, and MicL
|
||||
when the mic is on), then the uint32 PVS².
|
||||
- Record = 4 × channels + 4 bytes: 20 with the mic, 16 without. `stride = 12 + n × record`.
|
||||
|
||||
> ⚠ **RETRACTED:** the 2026-08-26 notes (Changelog, §15) read these records as 8 × uint16
|
||||
> little-endian after a 6-byte header. That was the same big-endian words shifted by one byte.
|
||||
> Their "2-word tail whose first word is 0000" is the PVS², whose high word reads `0000`.
|
||||
|
||||
#### D.6.6 Mic ✅ v0.33.0
|
||||
|
||||
- One count = **0.25 Pa**, so psi = count × 0.25 / 6894.757.
|
||||
- dB(L) = **81.9384** + 20·log10(|count|).
|
||||
- The exact value, 20·log10(0.25 Pa / 20 µPa), is 81.9382. Blastware's printed values pin the
|
||||
offset in [81.9383, 81.9385] instead.
|
||||
- With the exact value, 280 events mismatched, all at count 129.
|
||||
- float32 rounding does not explain the difference.
|
||||
- **Verified:** interval psi mismatches fell from 42,783 to 26, and mic peak mismatches from 345
|
||||
to 40.
|
||||
|
||||
#### D.6.7 Not read from the file yet
|
||||
|
||||
- **Fields:** job number, extended notes, ZC frequency, acceleration, displacement, time of
|
||||
peak, sensor check results, battery, calibration, units, monitor log.
|
||||
- **Open cases:**
|
||||
- histogram start times are 1 s early (#51)
|
||||
- 35 sub-minute histograms and 2 one-minute mic-off histograms decode wrongly
|
||||
- 26 histogram start dates are a day off
|
||||
- the per-interval PVS is not stored
|
||||
- Blastware prints `OORANGE` when the vector sum alone exceeds the range (a carve-out still to
|
||||
prove)
|
||||
|
||||
---
|
||||
|
||||
*All findings reverse-engineered from live RS-232 bridge captures.*
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
# Series 3 Decode Checker 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:** A repeatable check that decodes every DL2 Series 3 event file the way SFM ingest does, with no report and no filename, and compares every field, sample and histogram interval with Blastware's `_XML.XML` report. It reports matches, mismatches and gaps, grouped for diagnosis, run after run.
|
||||
|
||||
**Architecture:** There are four pieces. Two are pure codec-library modules:
|
||||
- `bw_xml_report.py` parses the reference.
|
||||
- `decode_check.py` builds SFM's side from the bytes and compares the two.
|
||||
|
||||
A carve-out list sits beside the comparison. Two lab-tool scripts in
|
||||
`scratch/` do the rest: one runs the corpus in parallel and writes a
|
||||
results file, the other turns results into the summary, the detailed
|
||||
report and the run-to-run changes.
|
||||
|
||||
**Tech Stack:** Python 3.10, standard library only (`xml.etree.ElementTree`, `concurrent.futures`, `gzip`, `json`), pytest.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Work on branch `feat/s3-decode-checker`, worktree `~/seismo-relay-checker`.
|
||||
Never commit to `main` or `dev`. **Do not touch `CHANGELOG.md`**: it is
|
||||
written on dev at merge.
|
||||
- **Standard library only.** `lxml` is not installed; do not add dependencies.
|
||||
- **Codec-library modules never import `sfm/`.** These are
|
||||
`minimateplus/bw_xml_report.py`, `minimateplus/decode_check.py` and
|
||||
`minimateplus/decode_check_carveouts.py`. Only `scratch/` may import `sfm/`.
|
||||
- **SFM's side comes only from the event bytes:**
|
||||
`decode_blastware_bytes(raw, name=None)`. No filename, no report overlay,
|
||||
and nothing from the XML ever reaches it.
|
||||
- **SFM's own assumptions are kept:**
|
||||
- geophone counts become in/s at the Normal range, `10.0 / 32000` per count
|
||||
(`event_file_io._GEO_NORMAL_FS_INS / _GEO_INT16_FS`)
|
||||
- mic counts become dB with `waveform_codec.mic_count_to_db`, or psi with
|
||||
`event_file_io._MIC_FS_PSI`
|
||||
- the range is never taken from the reference
|
||||
- **Precision rule:** a number matches when
|
||||
`|sfm − printed| ≤ 0.5·10^(−decimals in the printed text) + 1e-9`.
|
||||
Blastware rounds halves away from zero.
|
||||
- **Verdicts are exactly** `match`, `mismatch`, `sfm_blank`, `accepted`,
|
||||
`no_reference`, `error`.
|
||||
- **Series 3 only:** skip `UM…` XMLs. Dedupe binaries by upper-cased basename
|
||||
(`Sent/` mirrors the root).
|
||||
- **Run output goes outside the repo.** Default
|
||||
`~/dl2-archive/checker-runs/<YYYYmmdd-HHMMSS>/`; it contains customer
|
||||
names, so never commit it.
|
||||
- **Speed:** a full run (70,042 events, `--jobs 4`) in under 1 h; `--sample
|
||||
2000` in a few minutes.
|
||||
- **Tests:** run with `/home/serversdown/seismo-relay/.venv/bin/python -m
|
||||
pytest`.
|
||||
- The full suite has 18 known failures in this worktree, and they also fail
|
||||
on unchanged dev: 15 in `tests/test_bw_ascii_report.py`,
|
||||
`tests/test_event_file_io.py::test_save_imported_bw_without_report_works_unchanged`,
|
||||
and 2 in `tests/test_idf_binary_codec.py` (three-channel).
|
||||
- A task may add **no new** failures.
|
||||
- **Fixtures:** `tests/fixtures/` is gitignored. Add new fixtures with
|
||||
`git add -f`.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. **Ragged sample rows.** Channels can end at different lengths: in
|
||||
`T438HGTZ.B30W`, Tran/Vert/MicL stop 3 samples before Long. Blastware's
|
||||
own table then prints rows with fewer cells, holding the channels still
|
||||
running, in order. Cells must be attributed by SFM's per-channel lengths,
|
||||
not by position. That file must come out `match`. A row whose cell count
|
||||
disagrees with SFM's running channels is a `mismatch` with
|
||||
`row_length_disagreements` in `detail`; never a silent zip. Tests in Task 3.
|
||||
2. **The Sensitive range: a clipped 1.250 in/s event** (`M007HVWF.K30W`,
|
||||
`OORANGE`). SFM's Normal-range values (8× high) must stay `mismatch`; the
|
||||
saturation carve-out must not swallow them. Test in Task 4.
|
||||
3. **An event that fails to decode, or an XML that is truncated or
|
||||
malformed.** That event gets one `error` row and the run continues. Test in
|
||||
Task 5.
|
||||
4. **Non-numeric reference text where numbers are expected:** `>100`, `N/A`,
|
||||
`Check`, `OORANGE`, and units inside the text (`6.7 Volts`, `3.0 sec.`).
|
||||
These parse without exceptions and map to the rules in Task 3. Tests in
|
||||
Tasks 1 and 3.
|
||||
5. **Mic units: `dB(L)` vs `psi(L)` vs none** (`in/s` only, 3 channels, 7
|
||||
interval columns). The comparison picks SFM's conversion by the reference's
|
||||
units, and a no-mic event has no MicL rows at all. Tests in Tasks 1 and 3.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Fixtures and the XML report parser
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/fixtures/decode-checker-10-29-26/` holding these binaries
|
||||
plus each one's `<stem>_<ext>_XML.XML`, copied from `~/dl2-archive/files/`
|
||||
and `~/dl2-archive/xml/`:
|
||||
- `R352HIUI.F40W`: waveform, setup `BE16352.set`
|
||||
- `M529L4XQ.R30H`: histogram, relabelled notes
|
||||
- `T1905KDW.5F0W`: waveform, job number, `>100`, `N/A`, `Check`
|
||||
- `M007HVWF.K30W`: waveform, range 1.250, `OORANGE`
|
||||
- `T004JTRF.ME0H`: histogram, `psi(L)`
|
||||
- `R352HFZ7.530H`: histogram, no mic
|
||||
- `T438HGTZ.B30W`: waveform, ragged rows, `OORANGE` at range 10.000
|
||||
- Create: `minimateplus/bw_xml_report.py`
|
||||
- Test: `tests/test_bw_xml_report.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
```python
|
||||
@dataclass
|
||||
class XmlReport:
|
||||
scalars: dict[str, str] # tag -> text: top-level simple elements, and
|
||||
# <Tag><Value>v</Value><Units>u</Units></Tag> -> v
|
||||
units: dict[str, str] # tag -> the nested <Units> text
|
||||
event_units: Optional[str] # top-level <Units>, e.g. "in/s and dB(L)"
|
||||
channels: list[str] # <Channels>/<Channel> in order
|
||||
job_number: Optional[str]
|
||||
notes: list[tuple[str, str]] # (tag, value), non-empty, in order, between
|
||||
# top-level </Units> and <GeoRange>, JobNumber excluded
|
||||
sample_rows: Optional[list[list[str]]] # waveform: printed cells per row, as-is;
|
||||
# a row holds only the channels still running
|
||||
interval_columns: Optional[list[str]] # histogram: ColumnTitle, whitespace collapsed
|
||||
intervals: Optional[list[tuple[str, list[str]]]] # histogram: (Time, cells)
|
||||
def parse_xml_report(data: bytes) -> XmlReport
|
||||
def parse_xml_report_file(path: Union[str, Path]) -> XmlReport
|
||||
```
|
||||
|
||||
- [ ] **Step 1: Copy the seven pairs into the fixture folder** (`cp` from the two dl2 folders; XML names keep the `_XML.XML` form).
|
||||
|
||||
- [ ] **Step 2: Write the failing tests** (literal values read from the XMLs):
|
||||
|
||||
```python
|
||||
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
|
||||
|
||||
def test_scalars_units_and_special_text():
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert r.scalars["SampleRate"] == "1024 sps"
|
||||
assert r.scalars["RecordTime"] == "1.0 sec."
|
||||
assert r.scalars["TranPPV"] == "0.005" and r.units["TranPPV"] == "in/s"
|
||||
assert r.scalars["VertZCFreq"] == ">100" # entity unescaped
|
||||
assert r.scalars["TranZCFreq"] == "N/A"
|
||||
assert r.scalars["TranTestResults"] == "Check"
|
||||
assert r.scalars["BatteryLevel"] == "6.7 Volts"
|
||||
assert r.job_number == "1" and r.notes == []
|
||||
assert r.channels == ["Tran", "Vert", "Long", "MicL"]
|
||||
|
||||
def test_waveform_sample_rows():
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert len(r.sample_rows) == 1024
|
||||
assert r.sample_rows[0] == ["-0.005", "0.000", "0.000", "81.94"]
|
||||
assert r.intervals is None
|
||||
|
||||
def test_ragged_rows_are_kept_as_printed():
|
||||
r = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML")
|
||||
assert len(r.sample_rows) == 2304
|
||||
assert r.sample_rows[-4] == ["-0.185", "0.235", "-0.255", "-87.96"]
|
||||
assert r.sample_rows[-1] == ["-0.245"] # only Long still running
|
||||
|
||||
def test_relabelled_notes_keep_their_tags_in_order():
|
||||
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
|
||||
assert r.notes == [("Location", "Test Loc")]
|
||||
r = parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML")
|
||||
assert r.notes[1] == ("Client", "Mele & Mele & Sons, Inc.")
|
||||
assert r.event_units == "in/s and psi(L)"
|
||||
|
||||
def test_histogram_intervals_and_columns():
|
||||
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
|
||||
assert r.interval_columns[0] == "Tran Peak in/s" and len(r.interval_columns) == 10
|
||||
assert r.intervals == [("2025-07-02 14:55:08",
|
||||
["2.430", "13", "0.940", ">100", "1.900", "5.8", "3.095", "0.001", "106.0", "51"])]
|
||||
assert r.samples is None
|
||||
|
||||
def test_no_mic_histogram_has_seven_columns():
|
||||
r = parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML")
|
||||
assert r.event_units == "in/s"
|
||||
assert r.channels == ["Tran", "Vert", "Long"]
|
||||
assert len(r.interval_columns) == 7 and len(r.intervals[0][1]) == 7
|
||||
|
||||
def test_oorange_and_range_values():
|
||||
r = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML")
|
||||
assert r.scalars["TranPPV"] == "OORANGE"
|
||||
assert r.scalars["GeoRange"] == "1.250" and r.units["GeoRange"] == "in/s"
|
||||
|
||||
def test_truncated_xml_raises_valueerror():
|
||||
data = (FIX / "M529L4XQ_R30H_XML.XML").read_bytes()
|
||||
with pytest.raises(ValueError):
|
||||
parse_xml_report(data[: len(data) // 2])
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run them to watch them fail.**
|
||||
Run: `…/python -m pytest tests/test_bw_xml_report.py -v`. Expected: FAIL on import.
|
||||
|
||||
- [ ] **Step 4: Implement `bw_xml_report.py`.**
|
||||
- Parse with `xml.etree.ElementTree.fromstring`; wrap `ParseError` in `ValueError`.
|
||||
- Walk the root's children in order.
|
||||
- A child with a `<Value>` child goes in `scalars` and `units`.
|
||||
- The notes are the simple children after the top-level `Units` and before
|
||||
`GeoRange`.
|
||||
- Waveform cells: `WaveformDataChannels/Data/Row/Cell`, one list per row,
|
||||
unaltered.
|
||||
- Histogram: `HistogramData/HistogramDataColumnTitle/ColumnTitle` and
|
||||
`HistogramDataIntervals`, which interleaves `Time` and `Row`.
|
||||
|
||||
- [ ] **Step 5: Run the tests.** Expected: PASS.
|
||||
|
||||
- [ ] **Step 6: Commit** (fixtures with `git add -f`):
|
||||
`feat(codec): parse Blastware's _XML.XML event report`
|
||||
|
||||
---
|
||||
|
||||
### Task 2: SFM's side, from the bytes alone
|
||||
|
||||
**Files:**
|
||||
- Create: `minimateplus/decode_check.py`
|
||||
- Test: `tests/test_decode_check.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `minimateplus.event_file_io.decode_blastware_bytes`, `_GEO_NORMAL_FS_INS`, `_GEO_INT16_FS`, `_MIC_FS_PSI`; `minimateplus.waveform_codec.mic_count_to_db`.
|
||||
- Produces:
|
||||
```python
|
||||
GEO_IPS_PER_COUNT: float = 10.0 / 32000 # from the event_file_io constants
|
||||
@dataclass
|
||||
class SfmSide:
|
||||
event: Event
|
||||
values: dict[str, object] # reference tag -> SFM's value, or absent/None = blank
|
||||
notes: list[str] # non-empty project_info slots, in order
|
||||
job_number: Optional[str] # None until the decoder reads it
|
||||
channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order
|
||||
counts: dict[str, list[int]] # waveform samples or histogram interval peaks, per channel
|
||||
def sfm_side(raw: bytes) -> SfmSide
|
||||
```
|
||||
The `values` keys, and the only ones SFM fills today:
|
||||
- `EventType`: `"Full Waveform"` / `"Full Histogram"` from `record_type`
|
||||
- `SampleRate` (int), `RecordTime` (float)
|
||||
- `Pre-triggerLength`: `-pretrig_samples / sample_rate`
|
||||
- `EventDate` and `EventTime` for a waveform, or `HistogramStartDate` and
|
||||
`HistogramStartTime` for a histogram: `YYYY-MM-DD` and `HH:MM:SS` from
|
||||
`event.timestamp`
|
||||
- `TranPPV`, `VertPPV`, `LongPPV`, `PeakVectorSum` from `peak_values`
|
||||
- `MicLPSPL dB(L)`: `mic_count_to_db` of the largest |MicL count|
|
||||
- `MicLPSPL psi(L)`: `peak_values.micl`
|
||||
- `NumberofIntervals` for a histogram: the interval count
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
|
||||
```python
|
||||
def test_waveform_side_from_bytes():
|
||||
s = sfm_side((FIX / "R352HIUI.F40W").read_bytes())
|
||||
assert s.values["SampleRate"] == 1024 and s.values["RecordTime"] == pytest.approx(1.0)
|
||||
assert s.values["Pre-triggerLength"] == pytest.approx(-253 / 1024)
|
||||
assert (s.values["EventDate"], s.values["EventTime"]) == ("2018-07-30", "16:13:52")
|
||||
assert s.notes == ["JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV",
|
||||
"Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"]
|
||||
assert len(s.counts["Tran"]) == 1277 and s.job_number is None
|
||||
|
||||
def test_histogram_interval_peak_in_counts():
|
||||
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
|
||||
# Blastware: Tran interval peak 2.430 in/s = 7776 counts at 10/32000 in/s per count
|
||||
assert s.counts["Tran"] == [7776] and s.values["NumberofIntervals"] == 1
|
||||
|
||||
def test_no_filename_reaches_the_decoder():
|
||||
# the type must come from bytes; today they can't tell (#41), so a histogram reads Waveform
|
||||
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
|
||||
assert s.values["EventType"] == "Full Waveform"
|
||||
|
||||
def test_report_fields_stay_blank():
|
||||
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
|
||||
for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"):
|
||||
assert s.values.get(tag) is None
|
||||
```
|
||||
|
||||
When #41 is fixed, `test_no_filename_reaches_the_decoder` is updated to
|
||||
`"Full Histogram"`. Until then it pins that no name is passed.
|
||||
|
||||
- [ ] **Step 2: Run them; expect a FAIL on import.**
|
||||
- [ ] **Step 3: Implement `sfm_side`** in `minimateplus/decode_check.py`, per the Interfaces block.
|
||||
- [ ] **Step 4: Run them; expect PASS.**
|
||||
- [ ] **Step 5: Commit:** `feat(codec): SFM's side of the decode check, from the event bytes alone`
|
||||
|
||||
---
|
||||
|
||||
### Task 3: The comparison
|
||||
|
||||
**Files:**
|
||||
- Modify: `minimateplus/decode_check.py`
|
||||
- Test: `tests/test_decode_check.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `XmlReport` (Task 1), `SfmSide` (Task 2), `Carveout` (Task 4,
|
||||
passed in; default `()` so this task stands alone).
|
||||
- Produces:
|
||||
```python
|
||||
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
|
||||
@dataclass
|
||||
class FieldResult:
|
||||
field: str # reference tag, or "notes", "JobNumber", "Channels",
|
||||
# "samples.<ch>", "intervals.<column title>"
|
||||
verdict: str
|
||||
bw: Optional[str] # printed text, or "<n> cells" for a series
|
||||
sfm: Optional[str] # SFM's value rendered at the printed precision
|
||||
detail: str = "" # series: "rows=… differing=… row_length_disagreements=… first_diff=… max_abs=…"
|
||||
carveout: Optional[str] = None
|
||||
def matches_printed(value: float, printed: str) -> bool
|
||||
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]
|
||||
```
|
||||
|
||||
**Rules** (exact; the tests pin each):
|
||||
|
||||
- **Which fields:** every tag in `ref.scalars` is compared except
|
||||
`FileVersion` and `FileName`. So a field the XML carries and SFM doesn't is
|
||||
automatically `sfm_blank`.
|
||||
- **The reference says `N/A`:** the verdict is `no_reference`.
|
||||
- **SFM has nothing (`None`):** `sfm_blank`.
|
||||
- **Numbers:** for a value whose printed text begins with a number
|
||||
(`-?\d+(\.\d+)?`, units after it ignored), the verdict is `match` when
|
||||
`matches_printed` holds, else `mismatch`.
|
||||
- **`>100`:** matches only when SFM's matching `*_zc_above_range` flag is True.
|
||||
- **`OORANGE`:** a `mismatch` unless a carve-out applies.
|
||||
- **Text:** anything else is compared exactly after whitespace collapse.
|
||||
- **`MicLPSPL`:** compared against SFM's `MicLPSPL dB(L)` when `event_units`
|
||||
contains `dB(L)`, `MicLPSPL psi(L)` when it contains `psi(L)`, otherwise
|
||||
`sfm_blank`.
|
||||
- **`notes`:** the list of note values vs `sfm.notes`. **`JobNumber`:**
|
||||
`ref.job_number` vs `sfm.job_number` (skipped when the reference has none).
|
||||
**`Channels`:** `ref.channels` vs `sfm.channels`.
|
||||
- **`samples.<ch>`, one result per reference channel:**
|
||||
- SFM's cells are geophone `count × GEO_IPS_PER_COUNT`; MicL uses
|
||||
`mic_count_to_db(count)` for `dB(L)` or `count × _MIC_FS_PSI` for
|
||||
`psi(L)`.
|
||||
- For row *j*, SFM's running channels are the reference channels (in
|
||||
order) with `len(sfm.counts[ch]) > j`. Their cells pair up, in order,
|
||||
with the reference row's cells.
|
||||
- A row whose cell count differs from SFM's running count is a row-length
|
||||
disagreement for every channel in it. So are reference rows past SFM's
|
||||
longest channel.
|
||||
- A channel is `match` only with no row-length disagreements and every
|
||||
paired cell `matches_printed`.
|
||||
- `detail` always carries `rows=`, `differing=`,
|
||||
`row_length_disagreements=`, `first_diff=` and `max_abs=`.
|
||||
- **`intervals.<column>`, one row per column title:**
|
||||
- The peak columns compare like samples: geophone `Peak in/s`, MicL
|
||||
`Peak psi(L)` and `Peak dB(L)`.
|
||||
- The `Freq` and `Geo PVS` columns are `sfm_blank` (SFM drops them).
|
||||
- `intervals.Time` is `sfm_blank`.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
|
||||
```python
|
||||
def test_matches_printed_rounds_half_away():
|
||||
assert matches_printed(-0.0625, "-0.063") and matches_printed(0.0015, "0.002")
|
||||
assert not matches_printed(0.0026, "0.002")
|
||||
|
||||
def test_full_waveform_row_verdicts():
|
||||
raw = (FIX / "R352HIUI.F40W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "R352HIUI_F40W_XML.XML"))}
|
||||
for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime",
|
||||
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
|
||||
assert res["BatteryLevel"].verdict == "sfm_blank"
|
||||
assert "FileName" not in res
|
||||
|
||||
def test_ragged_rows_match_by_running_channels():
|
||||
# Tran/Vert/MicL end 3 samples before Long, in SFM and in Blastware's table alike
|
||||
raw = (FIX / "T438HGTZ.B30W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML"))}
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
assert res[f"samples.{ch}"].verdict == "match", res[f"samples.{ch}"]
|
||||
|
||||
def test_an_extra_reference_row_is_a_mismatch_with_detail():
|
||||
raw = (FIX / "T1905KDW.5F0W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
ref.sample_rows.append(["0.000", "0.000", "0.000", "0.000"])
|
||||
res = {r.field: r for r in compare(sfm_side(raw), ref)}
|
||||
assert res["samples.Tran"].verdict == "mismatch"
|
||||
assert "row_length_disagreements=1" in res["samples.Tran"].detail
|
||||
|
||||
def test_job_number_na_and_above_range():
|
||||
raw = (FIX / "T1905KDW.5F0W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML"))}
|
||||
assert res["JobNumber"].verdict == "sfm_blank"
|
||||
assert res["TranZCFreq"].verdict == "no_reference" # N/A
|
||||
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
|
||||
|
||||
def test_mic_units_pick_the_conversion():
|
||||
raw = (FIX / "T004JTRF.ME0H").read_bytes() # psi(L)
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML"))}
|
||||
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
|
||||
assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank"
|
||||
raw = (FIX / "R352HFZ7.530H").read_bytes() # no mic
|
||||
fields = {r.field for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML"))}
|
||||
assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them; expect a FAIL** (no `compare`).
|
||||
- [ ] **Step 3: Implement `matches_printed` and `compare`**, per the rules.
|
||||
- [ ] **Step 4: Run them; expect PASS.** If a `match` assertion fails, report
|
||||
the `FieldResult` and stop. Do not loosen a rule to make it pass.
|
||||
- [ ] **Step 5: Commit:** `feat(codec): compare SFM's file-only decode with Blastware's XML, field by field`
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Carve-outs
|
||||
|
||||
**Files:**
|
||||
- Create: `minimateplus/decode_check_carveouts.py`
|
||||
- Modify: `minimateplus/decode_check.py` (apply carve-outs in `compare`)
|
||||
- Test: `tests/test_decode_check.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
```python
|
||||
@dataclass(frozen=True)
|
||||
class Carveout:
|
||||
id: str
|
||||
fields: tuple[str, ...] # exact names, or prefixes ending in "." ("samples.")
|
||||
evidence: str # why Blastware is the one that differs, and the source
|
||||
applies: Callable[[SfmSide, XmlReport, FieldResult], bool]
|
||||
SATURATION: Carveout
|
||||
CARVEOUTS: tuple[Carveout, ...] = (SATURATION,)
|
||||
```
|
||||
- **How `compare` uses them:** a `mismatch` whose field a carve-out covers and
|
||||
whose `applies` returns True becomes `accepted`, with `carveout=<id>`.
|
||||
- **`SATURATION`:**
|
||||
- Covers `TranPPV`, `VertPPV`, `LongPPV`, `PeakVectorSum`,
|
||||
`samples.Tran/Vert/Long` and the `intervals.* Peak in/s` columns.
|
||||
- `r = float(ref.scalars["GeoRange"])`. A cell or value Blastware printed as
|
||||
`OORANGE`, or with `|bw| ≥ r − 0.0006`, is "clamped".
|
||||
- It applies when every differing cell/value is clamped and SFM's is the
|
||||
same sign with `r − 0.0006 ≤ |sfm| ≤ r × 1.01`.
|
||||
- The upper bound keeps an 8× Sensitive-range value a mismatch.
|
||||
- **`PeakVectorSum`** is a vector sum, so it can exceed the range (11.55
|
||||
on `T438HGTZ`). It is accepted when Blastware printed `OORANGE` and at
|
||||
least one of SFM's three PPVs sits in that ceiling band.
|
||||
- Evidence text: *"Blastware clamps a clipped channel to the range maximum
|
||||
and prints OORANGE; the file holds counts past full scale (32016 counts =
|
||||
10.005 in/s observed). scratch/verify_against_ascii.py, 2026-08-28."*
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
|
||||
```python
|
||||
def test_clipped_normal_range_is_accepted():
|
||||
# Blastware: Tran 5.445, Vert 6.310, Long OORANGE, PVS OORANGE; SFM Long 10.005, PVS 11.55
|
||||
raw = (FIX / "T438HGTZ.B30W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML"), CARVEOUTS)}
|
||||
assert res["TranPPV"].verdict == "match" and res["VertPPV"].verdict == "match"
|
||||
for f in ("LongPPV", "PeakVectorSum"):
|
||||
assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation")
|
||||
|
||||
def test_sensitive_range_8x_stays_a_mismatch():
|
||||
raw = (FIX / "M007HVWF.K30W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML"), CARVEOUTS)}
|
||||
assert res["TranPPV"].verdict == "mismatch" and res["samples.Tran"].verdict == "mismatch"
|
||||
|
||||
def test_every_carveout_has_evidence():
|
||||
assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them; expect a FAIL.**
|
||||
- [ ] **Step 3: Implement the module and the hook in `compare`.**
|
||||
- [ ] **Step 4: Run all `tests/test_decode_check.py`; expect PASS.**
|
||||
- [ ] **Step 5: Commit:** `feat(codec): carve-outs for proven Blastware differences -- saturation first`
|
||||
|
||||
---
|
||||
|
||||
### Task 5: The runner
|
||||
|
||||
**Files:**
|
||||
- Create: `scratch/check_s3_decode.py`
|
||||
- Test: `tests/test_check_s3_decode.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `parse_xml_report_file`, `sfm_side`, `compare`, `CARVEOUTS`.
|
||||
- Produces:
|
||||
```python
|
||||
def find_pairs(bin_dir: Path, xml_dir: Path) -> list[tuple[str, Path, Optional[Path]]]
|
||||
# (basename, binary, xml or None); Series 3 binaries only (^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$),
|
||||
# deduped by upper-case basename; xml = <stem>_<ext>_XML.XML in xml_dir
|
||||
def event_attrs(name: str, ref: XmlReport, raw: bytes) -> dict[str, str]
|
||||
# grouping keys, all from the reference or the file:
|
||||
# model ("MiniMate Plus" / "BlastMate III" from Version), serial (SerialNumber),
|
||||
# type (EventType), year (EventDate or HistogramStartDate), sample_rate, range (GeoRange),
|
||||
# mic_units (event_units), interval (IntervalSize or "-"),
|
||||
# setup_standard ("yes" if b"Standard Recording Setup" in raw else "no")
|
||||
def check_event(name: str, bin_path: str, xml_path: Optional[str]) -> dict
|
||||
# {"file", "attrs", "results": [[field, verdict, bw, sfm, detail, carveout], ...]}
|
||||
# no xml -> one ["event","no_reference",…] row; any exception -> one ["event","error",None,None,repr(exc),None] row
|
||||
def main(argv: Optional[list[str]] = None) -> int
|
||||
```
|
||||
- **CLI:** `bin_dir xml_dir [--out DIR] [--serial S]... [--year Y]...
|
||||
[--type W|H] [--field PREFIX]... [--sample N] [--seed K] [--jobs N]
|
||||
[--file NAME] [--compare-to DIR]`.
|
||||
- `--field` keeps only result rows whose field starts with a given prefix
|
||||
(the spec's "field group" partial run).
|
||||
- `--file` and `--compare-to` are wired in Task 7; here they are only
|
||||
accepted.
|
||||
- The spec's "decoder path" grouping key is omitted: the decoder does not
|
||||
expose it today.
|
||||
- **Output:** writes `<out>/results.jsonl.gz` (one line per event) and
|
||||
`<out>/run.json`.
|
||||
- `run.json` holds the args, the `git rev-parse HEAD`, the event count and
|
||||
the wall time.
|
||||
- It prints the run folder.
|
||||
- Parallelism: `ProcessPoolExecutor(jobs).map(…, chunksize=64)`.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests** (on the fixture folder, which holds
|
||||
binaries and XMLs together):
|
||||
|
||||
```python
|
||||
def test_find_pairs_dedupes_and_pairs(tmp_path):
|
||||
(tmp_path / "Sent").mkdir()
|
||||
for n in ("R352HIUI.F40W", "Sent/R352HIUI.F40W", "UM11719_20240404193109.IDFH"):
|
||||
(tmp_path / n).write_bytes(b"x")
|
||||
pairs = find_pairs(tmp_path, FIX)
|
||||
assert [p[0] for p in pairs] == ["R352HIUI.F40W"] and pairs[0][2].name == "R352HIUI_F40W_XML.XML"
|
||||
|
||||
def test_check_event_rows_and_attrs():
|
||||
out = check_event("M007HVWF.K30W", str(FIX / "M007HVWF.K30W"), str(FIX / "M007HVWF_K30W_XML.XML"))
|
||||
assert out["attrs"]["range"] == "1.250" and out["attrs"]["model"] == "MiniMate Plus"
|
||||
assert any(r[0] == "TranPPV" and r[1] == "mismatch" for r in out["results"])
|
||||
|
||||
def test_bad_input_is_one_error_row(tmp_path):
|
||||
bad = tmp_path / "R352HIUI.F40W"; bad.write_bytes(b"not a blastware file")
|
||||
out = check_event(bad.name, str(bad), str(FIX / "R352HIUI_F40W_XML.XML"))
|
||||
assert out["results"] == [["event", "error", None, None, out["results"][0][4], None]]
|
||||
|
||||
def test_cli_writes_results(tmp_path):
|
||||
assert main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1"]) == 0
|
||||
lines = gzip.open(tmp_path / "run/results.jsonl.gz", "rt").read().splitlines()
|
||||
assert len(lines) == 7 and json.loads((tmp_path / "run/run.json").read_text())["events"] == 7
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them; expect a FAIL.**
|
||||
- [ ] **Step 3: Implement**, per the Interfaces block.
|
||||
- [ ] **Step 4: Run them; expect PASS.**
|
||||
- [ ] **Step 5: Time a sample.** Run `scratch/check_s3_decode.py
|
||||
~/dl2-archive/files ~/dl2-archive/xml --sample 2000 --jobs 4`. Expected: a
|
||||
few minutes. Note the time in the commit body.
|
||||
- [ ] **Step 6: Commit:** `tooling(scratch): run the decode check over the archive in parallel`
|
||||
|
||||
---
|
||||
|
||||
### Task 6: The summary and the detailed report
|
||||
|
||||
**Files:**
|
||||
- Create: `scratch/decode_check_report.py`
|
||||
- Modify: `scratch/check_s3_decode.py` (write both reports at the end of a run)
|
||||
- Test: `tests/test_check_s3_decode.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
```python
|
||||
def aggregate(results_path: Path) -> dict
|
||||
def write_summary(agg: dict, path: Path) -> None # <out>/summary.md, for Brian
|
||||
def write_details(agg: dict, path: Path) -> None # <out>/details.json, for Claude
|
||||
```
|
||||
- **`summary.md`** has four parts:
|
||||
- a per-field table with one column per verdict (in `VERDICTS` order),
|
||||
sorted by non-match count
|
||||
- a line `N of M fields fully matching`
|
||||
- the non-match counts per event year
|
||||
- the carve-out counts
|
||||
- **`details.json`** has one entry per `(field, verdict)` with verdict ≠
|
||||
`match`. Each entry holds:
|
||||
- `total`
|
||||
- `groups`: for each attribute, the values whose failing count is ≥ 10% of
|
||||
`total`. Each value carries `{value, failing, compared, rate}`, where
|
||||
`compared` counts events where the field's verdict was not
|
||||
`no_reference`. Sorted by `failing` descending; `concentrated: true` when
|
||||
`rate ≥ 0.95`.
|
||||
- `examples`: up to 8, taking one per top group value first. Each gives
|
||||
`{file, bw, sfm, detail, rerun}` with `rerun = "python
|
||||
scratch/check_s3_decode.py <bin_dir> <xml_dir> --file <name>"`.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:** build a small `results.jsonl.gz` by
|
||||
hand with literal rows: 3 events, one field `SampleRate`, two `mismatch` on
|
||||
`sample_rate=2048`, one `match` on `1024`. Assert:
|
||||
- `details.json["SampleRate|mismatch"]["groups"]["sample_rate"]` is
|
||||
`[{"value": "2048", "failing": 2, "compared": 2, "rate": 1.0,
|
||||
"concentrated": True}]`
|
||||
- `summary.md` contains `0 of 1 fields fully matching`
|
||||
- every example carries a `rerun` with `--file`
|
||||
- [ ] **Step 2: Run them; expect a FAIL.**
|
||||
- [ ] **Step 3: Implement**, streaming the results file line by line and
|
||||
holding only counters plus a capped example list.
|
||||
- [ ] **Step 4: Run them; expect PASS.**
|
||||
- [ ] **Step 5: Commit:** `tooling(scratch): decode-check summary and grouped detail report`
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Run-to-run changes and the single-event view
|
||||
|
||||
**Files:**
|
||||
- Modify: `scratch/decode_check_report.py`, `scratch/check_s3_decode.py`
|
||||
- Test: `tests/test_check_s3_decode.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
```python
|
||||
def compare_runs(prev_results: Path, cur_results: Path) -> dict
|
||||
# {"fields": {field: {verdict: [before, after]}},
|
||||
# "regressions": [{"file", "field", "before", "after"}], # before == "match", after != "match"
|
||||
# "fixed": int} # before != "match", after == "match"
|
||||
def write_changes(chg: dict, path: Path) -> None # <out>/changes.md, regressions first
|
||||
```
|
||||
- **`--compare-to DIR`:** defaults to the newest other folder in the runs
|
||||
folder. `summary.md` starts with a regressions line (`0 regressions` or the
|
||||
count plus a pointer to `changes.md`).
|
||||
- **`--file NAME`:** finds that one event, runs `check_event` and prints a
|
||||
table `field | verdict | Blastware | SFM | detail` to stdout. No run folder
|
||||
is written.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
- Two hand-built results files where one `(file, field)` goes from `match`
|
||||
to `mismatch` and another from `sfm_blank` to `match`: assert one
|
||||
regression and `fixed == 1`.
|
||||
- `main([FIX, FIX, "--file", "M007HVWF.K30W"])` prints a line containing
|
||||
`TranPPV` and `mismatch`, and returns 0.
|
||||
- [ ] **Step 2: Run them; expect a FAIL.**
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run them; expect PASS.**
|
||||
- [ ] **Step 5: Commit:** `tooling(scratch): decode-check run-to-run changes and a one-event view`
|
||||
|
||||
---
|
||||
|
||||
### Task 8: The first full run, checked against what we know
|
||||
|
||||
**Files:**
|
||||
- Delete: `scratch/verify_bw_fields_against_xml.py` (the checker replaces it)
|
||||
- Modify: `CLAUDE.md` ("Where things stand": one short bullet with the first
|
||||
run's headline numbers and the command)
|
||||
- Modify: `docs/instantel_protocol_reference.md`. Correct the `#53` note in
|
||||
place, per the retraction convention: the three files pick an earlier,
|
||||
false footer, get the right sample count and a time 4 s off, and log no
|
||||
`decode_problems`. ⚠ The file is CRLF, so edit it with the Edit tool, not a
|
||||
Python text-mode rewrite.
|
||||
|
||||
- [ ] **Step 1: Full run.** `scratch/check_s3_decode.py ~/dl2-archive/files
|
||||
~/dl2-archive/xml --jobs 4`. Expected: it finishes in under an hour and
|
||||
writes `summary.md`, `details.json` and `results.jsonl.gz`.
|
||||
- [ ] **Step 2: Check the first-run expectations from the spec's "What success
|
||||
looks like"**, one by one, against `summary.md` and `details.json`:
|
||||
- `SampleRate`, `RecordTime`, `Pre-triggerLength` and `notes` all `match`
|
||||
- `samples.*` mismatch only on the range-1.250 events (8×) among 2025–26
|
||||
events; `T438HGTZ.B30W` matches
|
||||
- `EventType` mismatches exactly on the histograms
|
||||
- `JobNumber` and the calculated fields are `sfm_blank`
|
||||
- the three `#53` files show as time mismatches
|
||||
Any other non-match is a finding. Write it into the report's notes for
|
||||
Brian; **do not change a rule to hide it.** If an expectation fails because
|
||||
the checker is wrong, fix the checker with a test first.
|
||||
- [ ] **Step 3: Full suite.** Expected: no new failures beyond the 18 known.
|
||||
- [ ] **Step 4: Docs, per Files above.**
|
||||
- [ ] **Step 5: Commit:** `docs: the decode checker's first full run; correct the #53 note`
|
||||
@@ -0,0 +1,268 @@
|
||||
# Series 3 decode checker — design
|
||||
|
||||
**Date:** 2026-10-29 · **Branch:** `feat/s3-decode-checker` · **Status:** design
|
||||
|
||||
## Why this exists
|
||||
|
||||
SFM is meant to replace Blastware. Today, when a Series 3 event arrives with
|
||||
Blastware's ASCII report, SFM takes many of its values from the report: ZC
|
||||
frequency, acceleration, the sensor check and so on. Two of the four ways
|
||||
events will reach SFM, its own serial/modem download and its future call-in
|
||||
server, never have a report. So SFM must produce **everything Blastware
|
||||
reports, from the event file alone**, and we need proof that it does.
|
||||
|
||||
The checker is that proof, and the to-do list for getting there. It decodes
|
||||
each event file the way SFM ingest does, with no report, and compares every
|
||||
field with Blastware's own report of the same event. Then it says what
|
||||
matches, what doesn't, and what SFM can't produce yet.
|
||||
|
||||
It is the first of four pieces, agreed with Brian on 2026-10-29:
|
||||
|
||||
1. **This checker.**
|
||||
2. Completing SFM's file-only decode, one field group at a time, each slice
|
||||
done when the checker shows it matching. Slice 1, the setup fields and
|
||||
notes (#44/#45), merged to dev as `42fe35f`.
|
||||
3. Flipping ingest to file-only. Reports are kept for checking only. This
|
||||
happens only when piece 2 leaves no blanks and the checker proves it.
|
||||
Prod keeps its current behaviour until then.
|
||||
4. The watcher: it forwards the XML report while we verify, then stops
|
||||
forwarding reports.
|
||||
|
||||
## The reference: Blastware's XML event reports
|
||||
|
||||
Every Blastware ACH machine keeps, in `Sent/`, a full XML event report for each
|
||||
event: `<stem>_<ext>_XML.XML` next to the binary `<stem>.<ext>`. DL2's backup
|
||||
holds **70,042 of them for Series 3 events, from 2016 to 2026**. Its ASCII
|
||||
reports, by contrast, cover only 2025–26.
|
||||
|
||||
Local copies on the dev box (`tmi-dev`, 10.0.0.44):
|
||||
|
||||
| what | where | count |
|
||||
|---|---|---|
|
||||
| event binaries (Series 3) | `~/dl2-archive/files/` (root + `Sent/` mirror, dedupe by basename) | 70,112 distinct |
|
||||
| XML reports | `~/dl2-archive/xml/` (flat) | 75,958 = 70,042 Series 3 + 5,916 Micromate (`UM…_IDF?_XML.XML`) |
|
||||
| ASCII reports | `~/dl2-archive/files/` | 14,338 (2025–26 only) |
|
||||
|
||||
What the Series 3 XML contains (surveyed across all 75,958 on 2026-10-29):
|
||||
|
||||
- **Identity:** `EventType` (`Full Waveform` 6,524, `Full Histogram`
|
||||
63,518), `SerialNumber`, `Version` (`V 10.72-8.17 MiniMate Plus` or
|
||||
`… BlastMate III`), `FileName`.
|
||||
- **Time:** waveform `EventDate`/`EventTime`; histogram
|
||||
`HistogramStart*`/`HistogramStop*`.
|
||||
- **Setup:** `Channels`, `Trigger`, `GeoTriggerLevel`, `MicTriggerLevel`,
|
||||
`Pre-triggerLength`, `RecordTime`, `RecordStopMode` (only `Fixed` occurs),
|
||||
`SampleRate`, `IntervalSize` (2 s / 5 s / 15 s / 1 min / 5 min),
|
||||
`NumberofIntervals`, `GeoRange` (10.000: 75,923; 1.250: 35), `Units` (`in/s
|
||||
and dB(L)` / `psi(L)` / `dB(A)` / `in/s`), `Microphone` (weighting).
|
||||
- **Unit:** `BatteryLevel`, `Calibration` (date + by whom), `MicCalibration`.
|
||||
- **Notes:** `JobNumber`, then up to four user notes. Each is tagged with its
|
||||
operator-editable label (`Project`, `Location`, `Seis.Loc`, `SeisLocation`,
|
||||
`SeismographLoc`, `Company`, `General`, …), and empty notes are omitted.
|
||||
They sit between the top-level `</Units>` and `<GeoRange>`.
|
||||
- **Results:** per channel `PPV`, `ZCFreq`, `TimeofPeak`, `PeakAcceleration`,
|
||||
`PeakDisplacement` (waveform) or `PeakDate`/`PeakTime` (histogram);
|
||||
`PeakVectorSum` with its time; mic `PSPL`, time, `ZCFreq` (dB(A)
|
||||
histograms carry `MicA*` fields instead).
|
||||
- **Sensor check:** per geophone `TestFreq`, `TestRatio`, `TestResults`; mic
|
||||
`TestFreq`, `TestAmplitude`, `TestResults`.
|
||||
- **`MonitorLog`:** the session's start, stop and status text.
|
||||
- **Data:** waveform `WaveformDataChannels/Data/Row/Cell` (4 cells per
|
||||
sample: Tran, Vert, Long in in/s, MicL in the event's mic units); histogram
|
||||
`HistogramDataIntervals` (a `Time` and a 10-cell `Row` per interval:
|
||||
Tran/Vert/Long peak + freq, geo PVS, MicL psi, dB and freq).
|
||||
|
||||
Value forms the parser must handle: numbers with units in the text (`6.7
|
||||
Volts`, `7.6 Hz.`, `3.0 sec.`, `-0.250 sec`); `>100` (ZC frequency above
|
||||
range; 71,823 files), `N/A` (37,293 files), `OORANGE` (59 files: the channel
|
||||
clipped), `Check` (2,193 files), and XML entities. Two `_XML.XML` details
|
||||
matter:
|
||||
|
||||
- Blastware prints each number to a fixed number of decimals and **rounds
|
||||
halves away from zero** (−0.0625 s prints as −0.063).
|
||||
- The small `<stem>_<ext>.XML` summary next to it uses **decimal commas**.
|
||||
It is not the reference; the `_XML.XML` is.
|
||||
|
||||
## Goals
|
||||
|
||||
- For every Series 3 event file with an XML report, compare **every field the
|
||||
XML carries**, plus every waveform sample and every histogram interval,
|
||||
against SFM's file-only decode.
|
||||
- Give each comparison one verdict: **match**, **mismatch**, **SFM blank**
|
||||
(SFM produced nothing), **accepted difference** (covered by a written
|
||||
carve-out), **no reference** (the XML lacks the field), or **error** (the
|
||||
decode or parse failed).
|
||||
- Produce two outputs:
|
||||
- **A short summary for Brian:** per field, the counts of each verdict and
|
||||
how far we are from done.
|
||||
- **A detailed report for Claude** that groups failures by what the failing
|
||||
events share, so 17,000 mismatches read as "one bug on 2048 sps
|
||||
histograms". It gives example files with Blastware's value and SFM's, and
|
||||
a one-line command to re-run a single event.
|
||||
- **Run again and again.** Each run is compared with the previous one, so a
|
||||
fix shows as numbers moving, and anything that used to match and stops is
|
||||
called out.
|
||||
- Keep the comparison as library code, so ingest can later run it on one
|
||||
event as it arrives (piece 3/4).
|
||||
|
||||
## What counts as "SFM's side"
|
||||
|
||||
The SFM side is **what SFM produces from the event's bytes alone**:
|
||||
|
||||
- **The `Event` that `decode_blastware_bytes` returns when given the bytes and
|
||||
no filename.**
|
||||
- SFM's own download and call-in paths never have a Blastware name.
|
||||
- Today the event type comes only from the filename's extension, so every
|
||||
histogram decodes as "Waveform". The checker reports that as it is: a
|
||||
mismatch until the decoder reads the type from the file (#41). It must
|
||||
not borrow the name to make it match.
|
||||
- **Anything else SFM reads from those bytes outside the decoder**, such as the
|
||||
serial.
|
||||
- Ingest's `sfm/waveform_store._serial_from_bw_bytes` uses the filename to
|
||||
validate what it finds.
|
||||
- Whatever SFM can't get from the bytes alone is "SFM blank".
|
||||
- **Values the codec computes but never puts on the `Event`** count as SFM
|
||||
blank until they are wired through (piece 2). For example, histogram
|
||||
half-periods in `histogram_codec.decode_histogram_body_full` give the
|
||||
per-interval frequency.
|
||||
- **SFM's assumptions included.**
|
||||
- SFM cannot yet read the geophone range from the file, and assumes Normal
|
||||
(10 in/s): `_peaks_from_samples` does, and ingest writes `.h5` with
|
||||
`geo_range="normal"`.
|
||||
- The checker compares what SFM actually produces under that assumption.
|
||||
The range field itself is SFM blank.
|
||||
- So the 35 events recorded on the 1.250 in/s range show as 8× mismatches,
|
||||
not blanks. Example: `T438L713.QP0W` gives PPV 0.015/0.02/0.015 against
|
||||
Blastware's 0.002.
|
||||
- The range is never taken from the reference.
|
||||
|
||||
So the comparison takes an SFM-side record plus the parsed reference. The
|
||||
runner assembles that record from the decoder and any SFM helpers. The
|
||||
comparison itself stays pure codec-library code; only the runner (a lab tool)
|
||||
may import from `sfm/`.
|
||||
|
||||
## The rule for disagreements (decided by Brian)
|
||||
|
||||
**Every mismatch is an SFM bug until shown otherwise.** A mismatch becomes an
|
||||
"accepted difference" only through a written carve-out that names the fields
|
||||
it covers and the rule it applies. Its evidence must not rest on SFM's own
|
||||
output: Blastware contradicting itself, the instrument's own data (counts
|
||||
in the file, the unit's embedded record), a third source (another instrument,
|
||||
a known signal), or Instantel documentation. Each run reports how many events
|
||||
each carve-out covers.
|
||||
|
||||
The carve-out list starts with one entry, already proven in
|
||||
`scratch/verify_against_ascii.py`: **saturation**. On a clipped channel,
|
||||
Blastware clamps its numbers to the range maximum and writes `OORANGE`, while
|
||||
the file holds counts past full scale. Rounding to Blastware's printed
|
||||
precision is a comparison rule, not a carve-out.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **Series 4 / Micromate.** Thor's IDF decode has its own CSV-based check, and
|
||||
the 5,916 Micromate XMLs are noted for a later Series 4 checker.
|
||||
- **Changing what SFM decodes.** The checker reports gaps; filling them is
|
||||
piece 2.
|
||||
- **Wiring the check into ingest, the watcher or Terra-View.** That's pieces
|
||||
3/4. Nothing on prod changes.
|
||||
- **ASCII reports as a reference.** The XML covers every year, including the
|
||||
2025–26 events that have ASCII. The reference is parsed into a shape another
|
||||
report format could fill later, but no ASCII adapter is built now.
|
||||
|
||||
## Anti-goals (would make it a failure even if it runs)
|
||||
|
||||
- **Comparing SFM with Blastware's own numbers.** The SFM side must come only
|
||||
from the event file, through `decode_blastware_bytes` with no report
|
||||
overlay. Nothing from the XML or ASCII report may reach the SFM side.
|
||||
- **Hiding mismatches:** a carve-out without evidence, a tolerance looser
|
||||
than Blastware's printed precision, or blanks counted as matches.
|
||||
- **Wrong conversions:** counts converted to in/s with a range or scale that
|
||||
came from the reference rather than the file. If SFM can't read the range
|
||||
from the file yet, that is a gap to report, not something to borrow.
|
||||
- **A report that only says "N mismatches"** without grouping and examples.
|
||||
It must be usable to find the cause.
|
||||
- **A full run so slow it isn't run after every fix.**
|
||||
|
||||
## Constraints
|
||||
|
||||
- **Hardware:** runs on the dev box (4 cores, ~17 GB free disk after the
|
||||
22 GB XML copy; Brian can add space).
|
||||
- **Read-only:** it never writes to the corpus folders and needs no network.
|
||||
- **Speed:** a full run over all 70,042 events in **under an hour**. A
|
||||
partial run (by serial, year, event type or field group, or a random sample)
|
||||
in **a few minutes**. The setup/notes harness covering ~6 fields took ~4
|
||||
minutes with 4 processes. Samples and intervals add parsing 22 GB of XML.
|
||||
The standard library parses at ~45 MB/s per core (`lxml` is not
|
||||
installed), which fits the budget.
|
||||
- **Codec library purity (ADR 0003):** the codec library stays pure. Bench and
|
||||
lab tools stay out of the production image.
|
||||
- **Results contain customer project names**, so run output is kept outside
|
||||
the repo and never committed.
|
||||
|
||||
## What's decided, and by whom
|
||||
|
||||
**Brian:**
|
||||
- SFM's data comes only from the binary; reports are for checking.
|
||||
- The disagreement rule and carve-outs above.
|
||||
- The two outputs: a summary for him, a detailed report for Claude to diagnose.
|
||||
- Repeated runs with run-to-run comparison.
|
||||
- It lives in seismo-relay, and the comparison is library code.
|
||||
- Series 3 only. Nothing on prod or in Terra-View changes.
|
||||
|
||||
**Claude's calls (correct if wrong):**
|
||||
- The XML is the single reference.
|
||||
- **Placement:**
|
||||
- The XML report parser belongs in the codec library, a sibling of
|
||||
`minimateplus/bw_ascii_report.py`.
|
||||
- The comparison (one decoded `Event` + one parsed report → verdicts per
|
||||
field) is pure and belongs in the codec library too.
|
||||
- The batch runner is a lab tool (`scratch/`), per ADR 0003.
|
||||
- The carve-out list lives in the repo next to the comparison, as code or
|
||||
data the comparison reads, with each entry's evidence written beside it.
|
||||
- **Grouping attributes for the detailed report:**
|
||||
- device model (from `Version`), serial
|
||||
- event type, event year
|
||||
- sample rate, geophone range, mic units/weighting, interval size
|
||||
- whether the setup is named "Standard Recording Setup"
|
||||
- which decoder path produced the samples, where the decoder exposes it
|
||||
- `scratch/verify_bw_fields_against_xml.py` (committed `f46afaf`) is the
|
||||
starting point. It already handles the notes/job-number layout and the
|
||||
rounding rule. The checker replaces it.
|
||||
|
||||
**Left to the builder:**
|
||||
- module, function and file names; the output file formats
|
||||
- how runs are stored and compared
|
||||
- parallelism and any caching of decode or parse results
|
||||
- the CLI shape, as long as the partial-run filters and single-event re-run
|
||||
exist
|
||||
|
||||
## What success looks like
|
||||
|
||||
- **One command** produces the summary and the detailed report for all 70,042
|
||||
events within the time budget.
|
||||
- **The first run reproduces what is known**, which is how we tell the
|
||||
checker is honest:
|
||||
- sample rate, record time, pre-trigger and notes match everywhere
|
||||
- `T438HGTZ.B30W` matches. Its Tran, Vert and MicL end 3 samples before
|
||||
Long, and Blastware's own table does the same: its last rows carry only
|
||||
the Long cell. An earlier harness that compared one channel's length with
|
||||
the table's row count called this a decoder truncation; it was not.
|
||||
- samples and histogram intervals match on the 2025–26 events, as
|
||||
`verify_against_ascii.py` showed, **except the events on the 1.250 in/s
|
||||
range**, which are 8× high (5 of them in 2025–26, 35 in all)
|
||||
- event type mismatches on every histogram, because no filename is given
|
||||
(#41)
|
||||
- job number and the calculated values (ZC frequency, acceleration,
|
||||
displacement, time of peak, sensor check, battery, calibration, trigger
|
||||
levels, range, units, monitor log) show up as SFM blank
|
||||
- the three `#53` files fail loudly as waveform time mismatches, 4 s off.
|
||||
The decoder picks an earlier, false footer and records no
|
||||
`decode_problems`. The `#53` description in
|
||||
`docs/instantel_protocol_reference.md`, which says they decode as
|
||||
histograms, is out of date.
|
||||
- Every non-match group in the detailed report carries example files and a
|
||||
re-run command.
|
||||
- Tests cover the XML parser on real fixture reports with literal expected
|
||||
values, every comparison rule (rounding, `>100`, `N/A`, `OORANGE`,
|
||||
units), carve-out accounting, and a guard that the SFM side never sees the
|
||||
reference.
|
||||
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
minimateplus/bw_xml_report.py — parse Blastware's `_XML.XML` event report.
|
||||
|
||||
Blastware's ACH keeps, in `Sent/`, a full XML report beside each event binary:
|
||||
`<stem>_<ext>_XML.XML` for `<stem>.<ext>`. It carries every field of the event
|
||||
report plus every waveform sample or histogram interval, and DL2's backup holds
|
||||
one for 70,042 Series 3 events back to 2016 (its ASCII reports start in 2025).
|
||||
SFM uses it only to check its own decode, never as data.
|
||||
|
||||
The small `<stem>_<ext>.XML` summary beside it writes decimal commas and is not
|
||||
this file.
|
||||
|
||||
Layout (FileVersion 8.0), as the parser reads it:
|
||||
|
||||
- top-level simple elements, e.g. ``<SampleRate>1024 sps</SampleRate>``
|
||||
- value elements, e.g. ``<TranPPV><Value>0.015</Value><Units>in/s</Units></TranPPV>``
|
||||
- ``<Channels><Channel>Tran</Channel>...</Channels>``
|
||||
- the job number and up to four user notes, between the top-level
|
||||
``<Units>`` and ``<GeoRange>``; each note is tagged with its
|
||||
operator-editable label (``Project``, ``Location``, ``Seis.Loc`` ...) and
|
||||
an empty note is omitted
|
||||
- waveform: ``WaveformDataChannels/Data/Row/Cell``. A row holds only the
|
||||
channels still running: where channels end at different lengths, the last
|
||||
rows have fewer cells
|
||||
- histogram: ``HistogramData`` with ``HistogramDataColumnTitle/ColumnTitle``
|
||||
and ``HistogramDataIntervals``, alternating ``Time`` and ``Row``
|
||||
|
||||
Cell and value text is kept exactly as printed (``">100"``, ``"N/A"``,
|
||||
``"OORANGE"``, ``"6.7 Volts"``); interpreting it is the comparison's job.
|
||||
|
||||
Pure: no I/O beyond reading the file passed to `parse_xml_report_file`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import xml.etree.ElementTree as ET
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
|
||||
|
||||
@dataclass
|
||||
class XmlReport:
|
||||
scalars: dict[str, str]
|
||||
units: dict[str, str]
|
||||
event_units: Optional[str]
|
||||
channels: list[str]
|
||||
job_number: Optional[str]
|
||||
notes: list[tuple[str, str]]
|
||||
sample_rows: Optional[list[list[str]]]
|
||||
interval_columns: Optional[list[str]]
|
||||
intervals: Optional[list[tuple[str, list[str]]]]
|
||||
|
||||
|
||||
def _text(el: ET.Element) -> str:
|
||||
return (el.text or "").strip()
|
||||
|
||||
|
||||
def _cells(row: ET.Element) -> list[str]:
|
||||
return [_text(c) for c in row.findall("Cell")]
|
||||
|
||||
|
||||
def parse_xml_report(data: bytes) -> XmlReport:
|
||||
"""Parse the bytes of an `_XML.XML` event report. Raises ValueError when
|
||||
they are not well-formed XML (a truncated file, for one)."""
|
||||
try:
|
||||
root = ET.fromstring(data)
|
||||
except ET.ParseError as exc:
|
||||
raise ValueError(f"not a well-formed XML report: {exc}") from exc
|
||||
|
||||
scalars: dict[str, str] = {}
|
||||
units: dict[str, str] = {}
|
||||
event_units: Optional[str] = None
|
||||
channels: list[str] = []
|
||||
job_number: Optional[str] = None
|
||||
notes: list[tuple[str, str]] = []
|
||||
sample_rows: Optional[list[list[str]]] = None
|
||||
interval_columns: Optional[list[str]] = None
|
||||
intervals: Optional[list[tuple[str, list[str]]]] = None
|
||||
|
||||
in_notes = False
|
||||
for el in root:
|
||||
tag = el.tag
|
||||
if tag == "Units" and len(el) == 0:
|
||||
event_units = _text(el)
|
||||
scalars[tag] = event_units
|
||||
in_notes = True
|
||||
continue
|
||||
if tag == "GeoRange":
|
||||
in_notes = False
|
||||
if in_notes and len(el) == 0:
|
||||
# Job number and user notes: never scalars, so the comparison
|
||||
# scores each once.
|
||||
if tag == "JobNumber":
|
||||
job_number = _text(el)
|
||||
elif _text(el):
|
||||
notes.append((tag, _text(el)))
|
||||
continue
|
||||
if tag == "Channels":
|
||||
channels = [_text(c) for c in el.findall("Channel")]
|
||||
elif tag == "WaveformDataChannels":
|
||||
data_el = el.find("Data")
|
||||
if data_el is not None:
|
||||
sample_rows = [_cells(r) for r in data_el.findall("Row")]
|
||||
elif tag == "HistogramData":
|
||||
titles = el.find("HistogramDataColumnTitle")
|
||||
interval_columns = ([" ".join(_text(t).split()) for t in titles.findall("ColumnTitle")]
|
||||
if titles is not None else [])
|
||||
body = el.find("HistogramDataIntervals")
|
||||
intervals = []
|
||||
time: Optional[str] = None
|
||||
for child in (body if body is not None else []):
|
||||
if child.tag == "Time":
|
||||
time = _text(child)
|
||||
elif child.tag == "Row":
|
||||
intervals.append((time or "", _cells(child)))
|
||||
time = None
|
||||
elif el.find("Value") is not None:
|
||||
scalars[tag] = _text(el.find("Value"))
|
||||
u = el.find("Units")
|
||||
if u is not None:
|
||||
units[tag] = _text(u)
|
||||
elif len(el) == 0:
|
||||
scalars[tag] = _text(el)
|
||||
|
||||
return XmlReport(
|
||||
scalars=scalars, units=units, event_units=event_units, channels=channels,
|
||||
job_number=job_number, notes=notes, sample_rows=sample_rows,
|
||||
interval_columns=interval_columns, intervals=intervals,
|
||||
)
|
||||
|
||||
|
||||
def parse_xml_report_file(path: Union[str, Path]) -> XmlReport:
|
||||
return parse_xml_report(Path(path).read_bytes())
|
||||
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
minimateplus/decode_check.py — SFM's file-only decode, set beside Blastware's
|
||||
report of the same event, field by field.
|
||||
|
||||
The decode checker's core (`docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`).
|
||||
SFM's side comes from the event bytes alone, through
|
||||
`decode_blastware_bytes(raw, name=None)`: no filename, because SFM's own
|
||||
download and call-in paths have none, and no report overlay. Nothing from the
|
||||
reference reaches it. SFM's own assumptions stay in -- geophone counts become
|
||||
in/s at the Normal range -- because the point is to judge what SFM produces.
|
||||
|
||||
Pure: no I/O, and no import from `sfm/`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Optional, Sequence
|
||||
|
||||
from .bw_xml_report import XmlReport
|
||||
from .event_file_io import (_GEO_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT,
|
||||
decode_blastware_bytes)
|
||||
from .models import Event
|
||||
from .waveform_codec import mic_count_to_db
|
||||
|
||||
# SFM's conversion at the Normal range (10 in/s full scale = 32000 counts),
|
||||
# which SFM assumes when it cannot read the event's range from the file.
|
||||
GEO_IPS_PER_COUNT: float = _GEO_NORMAL_FS_INS / _GEO_INT16_FS
|
||||
|
||||
_CHANNELS = ("Tran", "Vert", "Long", "MicL")
|
||||
_EVENT_TYPE = {"Waveform": "Full Waveform", "Histogram": "Full Histogram"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class SfmSide:
|
||||
event: Event
|
||||
values: dict[str, object] # reference tag -> SFM's value; absent or None = blank
|
||||
notes: list[str] # non-empty user-note slots, in order
|
||||
job_number: Optional[str] # None until the decoder reads it
|
||||
channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order
|
||||
counts: dict[str, list[int]] # waveform samples or histogram interval peaks
|
||||
geo_ips_per_count: float = GEO_IPS_PER_COUNT # at the event's range, as SFM read it
|
||||
|
||||
|
||||
def sfm_side(raw: bytes) -> SfmSide:
|
||||
"""What SFM makes of an event from its bytes alone."""
|
||||
ev = decode_blastware_bytes(raw, name=None)
|
||||
counts = {ch: list((ev.raw_samples or {}).get(ch) or []) for ch in _CHANNELS}
|
||||
pv, pi, ts = ev.peak_values, ev.project_info, ev.timestamp
|
||||
|
||||
values: dict[str, object] = {
|
||||
"EventType": _EVENT_TYPE.get(ev.record_type, ev.record_type),
|
||||
"SampleRate": ev.sample_rate,
|
||||
"RecordTime": ev.rectime_seconds,
|
||||
"Pre-triggerLength": (-ev.pretrig_samples / ev.sample_rate
|
||||
if ev.pretrig_samples is not None and ev.sample_rate else None),
|
||||
# SFM's interval count is its decoded entry count; the reference
|
||||
# carries this field for histograms only.
|
||||
"NumberofIntervals": len(counts["Tran"]) or None,
|
||||
"GeoRange": _GEO_FS_BY_RANGE.get(ev.geo_range),
|
||||
}
|
||||
if ts is not None:
|
||||
date = f"{ts.year:04d}-{ts.month:02d}-{ts.day:02d}"
|
||||
time = f"{ts.hour:02d}:{ts.minute:02d}:{ts.second:02d}"
|
||||
# The event's time, under both of Blastware's names for it, so a time
|
||||
# is judged as a time even while the type is wrong (#41).
|
||||
values.update(EventDate=date, EventTime=time,
|
||||
HistogramStartDate=date, HistogramStartTime=time)
|
||||
if pv is not None:
|
||||
values.update(TranPPV=pv.tran, VertPPV=pv.vert, LongPPV=pv.long,
|
||||
PeakVectorSum=pv.peak_vector_sum)
|
||||
if counts["MicL"]:
|
||||
values["MicLPSPL dB(L)"] = mic_count_to_db(max(abs(c) for c in counts["MicL"]))
|
||||
values["MicLPSPL psi(L)"] = pv.micl if pv is not None else None
|
||||
|
||||
return SfmSide(
|
||||
event=ev,
|
||||
values=values,
|
||||
notes=[v for v in (pi.project, pi.client, pi.operator, pi.sensor_location) if v]
|
||||
if pi is not None else [],
|
||||
job_number=None,
|
||||
channels=[ch for ch in _CHANNELS if counts[ch]],
|
||||
counts=counts,
|
||||
geo_ips_per_count=_GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) / _GEO_INT16_FS,
|
||||
)
|
||||
|
||||
|
||||
# ── The comparison ──────────────────────────────────────────────────────────
|
||||
|
||||
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
|
||||
|
||||
# Not event data: the report's own format version and Blastware's file name.
|
||||
_NOT_COMPARED = {"FileVersion", "FileName"}
|
||||
_NUMBER = re.compile(r"^\s*(-?\d+(?:\.\d+)?)")
|
||||
_GEO = ("Tran", "Vert", "Long")
|
||||
|
||||
|
||||
@dataclass
|
||||
class FieldResult:
|
||||
field: str
|
||||
verdict: str
|
||||
bw: Optional[str]
|
||||
sfm: Optional[str]
|
||||
detail: str = ""
|
||||
carveout: Optional[str] = None
|
||||
|
||||
|
||||
def _printed_number(printed: str) -> Optional[tuple[float, int]]:
|
||||
m = _NUMBER.match(printed)
|
||||
if not m:
|
||||
return None
|
||||
num = m.group(1)
|
||||
return float(num), (len(num) - num.index(".") - 1 if "." in num else 0)
|
||||
|
||||
|
||||
def matches_printed(value: float, printed: str) -> bool:
|
||||
"""True when `value` prints as `printed` at Blastware's precision. Blastware
|
||||
rounds halves away from zero (-0.0625 s -> -0.063), so half a unit of the last
|
||||
printed decimal either way is a match."""
|
||||
p = _printed_number(printed)
|
||||
return p is not None and abs(value - p[0]) <= 0.5 * 10 ** -p[1] + 1e-9
|
||||
|
||||
|
||||
def _render(value: object, printed: str) -> str:
|
||||
p = _printed_number(printed)
|
||||
if p is not None and isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
return f"{value:.{p[1]}f}"
|
||||
return str(value)
|
||||
|
||||
|
||||
def _same_text(a: object, b: str) -> bool:
|
||||
return " ".join(str(a).split()) == " ".join(b.split())
|
||||
|
||||
|
||||
def _mic_converter(ref: XmlReport) -> Optional[Callable[[int], float]]:
|
||||
units = ref.event_units or ""
|
||||
if "dB(L)" in units:
|
||||
return mic_count_to_db
|
||||
if "psi(L)" in units:
|
||||
return lambda c: c * _MIC_PSI_PER_COUNT
|
||||
return None
|
||||
|
||||
|
||||
def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> FieldResult:
|
||||
if not printed.strip() or printed.strip() == "N/A":
|
||||
return FieldResult(tag, "no_reference", printed, None)
|
||||
if tag == "MicLPSPL":
|
||||
units = ref.event_units or ""
|
||||
key = ("MicLPSPL dB(L)" if "dB(L)" in units else
|
||||
"MicLPSPL psi(L)" if "psi(L)" in units else None)
|
||||
value = sfm.values.get(key) if key else None
|
||||
else:
|
||||
value = sfm.values.get(tag)
|
||||
if value is None:
|
||||
return FieldResult(tag, "sfm_blank", printed, None)
|
||||
if printed.startswith(">"):
|
||||
# ZC frequency above range: SFM agrees only by setting its flag.
|
||||
flag = getattr(sfm.event.peak_values, tag[:-len("ZCFreq")].lower() + "_zc_above_range", False)
|
||||
return FieldResult(tag, "match" if flag else "mismatch", printed, str(value))
|
||||
if printed == "OORANGE":
|
||||
return FieldResult(tag, "mismatch", printed, str(value))
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool) and _printed_number(printed):
|
||||
ok = matches_printed(float(value), printed)
|
||||
else:
|
||||
ok = _same_text(value, printed)
|
||||
return FieldResult(tag, "match" if ok else "mismatch", printed, _render(value, printed))
|
||||
|
||||
|
||||
def _cell_diff(value: float, printed: str) -> Optional[float]:
|
||||
"""|value - printed| when the cell disagrees, else None; inf for a cell that
|
||||
is not a number."""
|
||||
p = _printed_number(printed)
|
||||
if p is None:
|
||||
return float("inf")
|
||||
d = abs(value - p[0])
|
||||
return d if d > 0.5 * 10 ** -p[1] + 1e-9 else None
|
||||
|
||||
|
||||
def _series_result(field: str, n_bw: int, n_sfm: int, diffs: list[tuple[int, float]],
|
||||
row_len: int) -> FieldResult:
|
||||
first = diffs[0][0] if diffs else None
|
||||
max_abs = max((d for _, d in diffs), default=0.0)
|
||||
ok = not diffs and not row_len
|
||||
return FieldResult(
|
||||
field, "match" if ok else "mismatch", f"{n_bw} rows", f"{n_sfm} values",
|
||||
f"rows={n_bw} sfm={n_sfm} differing={len(diffs)} row_length_disagreements={row_len} "
|
||||
f"first_diff={first} max_abs={max_abs:.4g}",
|
||||
)
|
||||
|
||||
|
||||
def _sample_converters(sfm: SfmSide, ref: XmlReport) -> dict[str, Callable[[int], float]]:
|
||||
k = sfm.geo_ips_per_count
|
||||
convert: dict[str, Callable[[int], float]] = {ch: (lambda c: c * k) for ch in _GEO}
|
||||
mic = _mic_converter(ref)
|
||||
if mic is not None:
|
||||
convert["MicL"] = mic
|
||||
return convert
|
||||
|
||||
|
||||
def _interval_converter(title: str, sfm: SfmSide) -> Optional[Callable[[int], float]]:
|
||||
"""SFM keeps each interval's peaks; it drops their frequencies and geo PVS."""
|
||||
ch, _, rest = title.partition(" ")
|
||||
if rest.startswith("Peak") and ch in _GEO:
|
||||
return lambda c: c * sfm.geo_ips_per_count
|
||||
if ch == "MicL" and rest == "Peak dB(L)":
|
||||
return mic_count_to_db
|
||||
if ch == "MicL" and rest == "Peak psi(L)":
|
||||
return lambda c: c * _MIC_PSI_PER_COUNT
|
||||
return None
|
||||
|
||||
|
||||
def series_pairs(sfm: SfmSide, ref: XmlReport,
|
||||
field: str) -> Optional[tuple[list[tuple[int, str, float]], int]]:
|
||||
"""For a `samples.<ch>` or `intervals.<column>` field: the (index, printed
|
||||
cell, SFM value) pairs and the count of row-length disagreements, or None
|
||||
when SFM has no conversion or no data for it.
|
||||
|
||||
A waveform row holds only the channels still running, so row j's cells
|
||||
pair, in order, with the reference channels SFM has more than j samples of;
|
||||
a row whose cell count differs is a disagreement for every channel."""
|
||||
if field.startswith("samples."):
|
||||
ch = field[len("samples."):]
|
||||
convert = _sample_converters(sfm, ref).get(ch)
|
||||
counts = sfm.counts.get(ch, [])
|
||||
if convert is None or not counts:
|
||||
return None
|
||||
rows = ref.sample_rows or []
|
||||
lens = {c: len(sfm.counts.get(c, [])) for c in ref.channels}
|
||||
pairs, row_len = [], 0
|
||||
for j, row in enumerate(rows):
|
||||
running = [c for c in ref.channels if lens[c] > j]
|
||||
if len(running) != len(row):
|
||||
row_len += 1
|
||||
elif ch in running:
|
||||
pairs.append((j, row[running.index(ch)], convert(counts[j])))
|
||||
return pairs, row_len + max(0, len(counts) - len(rows))
|
||||
if field.startswith("intervals."):
|
||||
title = field[len("intervals."):]
|
||||
columns = ref.interval_columns or []
|
||||
convert = _interval_converter(title, sfm)
|
||||
counts = sfm.counts.get(title.partition(" ")[0], [])
|
||||
if convert is None or not counts or title not in columns:
|
||||
return None
|
||||
i = columns.index(title)
|
||||
cells = [row[i] if i < len(row) else "" for _, row in (ref.intervals or [])]
|
||||
pairs = [(j, cell, convert(c)) for j, (cell, c) in enumerate(zip(cells, counts))]
|
||||
return pairs, abs(len(cells) - len(counts))
|
||||
return None
|
||||
|
||||
|
||||
def _compare_series(field: str, n_bw: int, sfm: SfmSide, ref: XmlReport) -> FieldResult:
|
||||
got = series_pairs(sfm, ref, field)
|
||||
if got is None:
|
||||
return FieldResult(field, "sfm_blank", f"{n_bw} rows", None)
|
||||
pairs, row_len = got
|
||||
diffs = [(j, d) for j, cell, v in pairs if (d := _cell_diff(v, cell)) is not None]
|
||||
n_sfm = len(sfm.counts.get(field.split(".", 1)[1].partition(" ")[0], []))
|
||||
return _series_result(field, n_bw, n_sfm, diffs, row_len)
|
||||
|
||||
|
||||
def _compare_samples(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
||||
"""One result per reference channel."""
|
||||
n = len(ref.sample_rows or [])
|
||||
return [_compare_series(f"samples.{ch}", n, sfm, ref) for ch in ref.channels]
|
||||
|
||||
|
||||
def _compare_intervals(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
||||
"""One result per column, plus the interval times, which SFM does not keep."""
|
||||
n = len(ref.intervals or [])
|
||||
return ([FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)]
|
||||
+ [_compare_series(f"intervals.{t}", n, sfm, ref) for t in ref.interval_columns or []])
|
||||
|
||||
|
||||
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]:
|
||||
"""Every field Blastware's report carries, set against what SFM produced.
|
||||
A mismatch a carve-out covers and applies to becomes `accepted`."""
|
||||
out = [_compare_scalar(tag, text, sfm, ref)
|
||||
for tag, text in ref.scalars.items() if tag not in _NOT_COMPARED]
|
||||
|
||||
ref_notes = [v for _, v in ref.notes]
|
||||
if ref_notes and not sfm.notes:
|
||||
out.append(FieldResult("notes", "sfm_blank", " | ".join(ref_notes), None))
|
||||
else:
|
||||
ok = [" ".join(v.split()) for v in ref_notes] == [" ".join(v.split()) for v in sfm.notes]
|
||||
out.append(FieldResult("notes", "match" if ok else "mismatch",
|
||||
" | ".join(ref_notes), " | ".join(sfm.notes)))
|
||||
if ref.job_number is not None:
|
||||
out.append(FieldResult("JobNumber", "sfm_blank", ref.job_number, None)
|
||||
if sfm.job_number is None else
|
||||
FieldResult("JobNumber", "match" if _same_text(sfm.job_number, ref.job_number)
|
||||
else "mismatch", ref.job_number, sfm.job_number))
|
||||
out.append(FieldResult("Channels", "match" if ref.channels == sfm.channels else "mismatch",
|
||||
" ".join(ref.channels), " ".join(sfm.channels)))
|
||||
if ref.sample_rows is not None:
|
||||
out.extend(_compare_samples(sfm, ref))
|
||||
if ref.intervals is not None:
|
||||
out.extend(_compare_intervals(sfm, ref))
|
||||
|
||||
for r in out:
|
||||
if r.verdict != "mismatch":
|
||||
continue
|
||||
for co in carveouts:
|
||||
covered = any(r.field == f or (f.endswith(".") and r.field.startswith(f)) for f in co.fields)
|
||||
if covered and co.applies(sfm, ref, r):
|
||||
r.verdict, r.carveout = "accepted", co.id
|
||||
break
|
||||
return out
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
minimateplus/decode_check_carveouts.py — the proven ways Blastware's report
|
||||
differs from the instrument's data.
|
||||
|
||||
Every disagreement between SFM and Blastware is SFM's bug until shown otherwise.
|
||||
A carve-out is that showing: the fields it covers, the rule it applies, and
|
||||
evidence that does not rest on SFM's own output -- Blastware contradicting
|
||||
itself, the instrument's own data, a third source, or Instantel documentation.
|
||||
`compare` turns a covered mismatch into `accepted` only when the rule holds,
|
||||
and every run counts the events each carve-out covers.
|
||||
|
||||
Pure: no I/O, and no import from `sfm/`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
from .bw_xml_report import XmlReport
|
||||
from .decode_check import FieldResult, SfmSide, _printed_number, series_pairs, matches_printed
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Carveout:
|
||||
id: str
|
||||
fields: tuple[str, ...] # exact names, or prefixes ending in "."
|
||||
evidence: str
|
||||
applies: Callable[[SfmSide, XmlReport, FieldResult], bool]
|
||||
|
||||
|
||||
_TOL = 0.0006
|
||||
|
||||
|
||||
def _at_ceiling(value: float, r: float) -> bool:
|
||||
"""SFM's value sits at the range ceiling: a decoder unit or two past nominal
|
||||
full scale is the clipped count itself (32016 = 10.005 in/s). An 8x
|
||||
Sensitive-range value is far above the band and does not qualify."""
|
||||
return r - _TOL <= abs(value) <= r * 1.01
|
||||
|
||||
|
||||
def _clamped(printed: str, r: float) -> bool:
|
||||
if printed.strip() == "OORANGE":
|
||||
return True
|
||||
p = _printed_number(printed)
|
||||
return p is not None and abs(p[0]) >= r - _TOL
|
||||
|
||||
|
||||
def _saturation(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
|
||||
try:
|
||||
r = float(ref.scalars["GeoRange"])
|
||||
except (KeyError, ValueError):
|
||||
return False
|
||||
if res.field in ("TranPPV", "VertPPV", "LongPPV"):
|
||||
v = sfm.values.get(res.field)
|
||||
return v is not None and _clamped(res.bw or "", r) and _at_ceiling(float(v), r)
|
||||
if res.field == "PeakVectorSum":
|
||||
# A vector sum can exceed the range without any clipping, so only
|
||||
# Blastware's OORANGE counts. SFM's sum is bounded by three channels at
|
||||
# the ceiling (11.55 on T438HGTZ.B30W), and a channel Blastware itself
|
||||
# clamped must be the one SFM has at the ceiling -- an unclipped channel
|
||||
# read 8x high on the Sensitive range does not qualify.
|
||||
pvs = sfm.values.get("PeakVectorSum")
|
||||
return ((res.bw or "").strip() == "OORANGE" and pvs is not None
|
||||
and r - _TOL <= float(pvs) <= 3 ** 0.5 * r * 1.01
|
||||
and any(_clamped(ref.scalars.get(f, ""), r) and sfm.values.get(f) is not None
|
||||
and _at_ceiling(float(sfm.values[f]), r)
|
||||
for f in ("TranPPV", "VertPPV", "LongPPV")))
|
||||
got = series_pairs(sfm, ref, res.field)
|
||||
if got is None or got[1]:
|
||||
return False
|
||||
differing = [(cell, v) for _, cell, v in got[0] if not matches_printed(v, cell)]
|
||||
return bool(differing) and all(
|
||||
_clamped(cell, r) and _at_ceiling(v, r)
|
||||
and (cell.strip() == "OORANGE" or (v >= 0) == (_printed_number(cell)[0] >= 0))
|
||||
for cell, v in differing)
|
||||
|
||||
|
||||
SATURATION = Carveout(
|
||||
id="saturation",
|
||||
fields=("TranPPV", "VertPPV", "LongPPV", "PeakVectorSum",
|
||||
"samples.Tran", "samples.Vert", "samples.Long",
|
||||
"intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s"),
|
||||
evidence=("Blastware clamps a clipped channel to the range maximum and prints OORANGE; "
|
||||
"the file holds counts past full scale (32016 counts = 10.005 in/s observed). "
|
||||
"scratch/verify_against_ascii.py, 2026-08-28."),
|
||||
applies=_saturation,
|
||||
)
|
||||
|
||||
CARVEOUTS: tuple[Carveout, ...] = (SATURATION,)
|
||||
+178
-61
@@ -20,6 +20,7 @@ import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
@@ -29,7 +30,7 @@ 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
|
||||
from .histogram_codec import decode_histogram_body, interval_pvs
|
||||
|
||||
# Reference pressure for dB(L) → psi conversion (20 µPa expressed in psi).
|
||||
# Same constant as sfm/sfm_webapp.html so server-side and browser-side
|
||||
@@ -50,7 +51,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.32.0" # waveform times from the event record, report dates, histogram reader; gates the backfill regen
|
||||
TOOL_VERSION = "0.33.0" # setup + notes, record type, histogram PVS and mic from the file; gates the backfill regen
|
||||
|
||||
try:
|
||||
# Best-effort: prefer the installed metadata when it's NEWER than the
|
||||
@@ -703,44 +704,32 @@ _INT16_FS = 32768.0
|
||||
# sfm.event_hdf5._GEO_INT16_FS or sidecar peaks disagree with the plotted
|
||||
# waveform by 2.3%. Confirmed 2026-08-25 against the BW ASCII corpus.
|
||||
_GEO_INT16_FS = 32000.0
|
||||
# Full scale per geo_range: 0 Normal, 1 Sensitive.
|
||||
_GEO_FS_BY_RANGE = {0: _GEO_NORMAL_FS_INS, 1: _GEO_SENSITIVE_FS_INS}
|
||||
# A histogram's geo values are decoder units of 16 counts: 0.005 in/s at the
|
||||
# Normal range, scaled by the range's full scale like the samples above.
|
||||
_HIST_GEO_COUNTS_PER_UNIT = 16
|
||||
|
||||
# Microphone scale factor, psi per ADC count. Approximate — exact factor
|
||||
# depends on the geophone-vs-mic ADC scaling and the firmware reference.
|
||||
# We mark mic_psi as "computed approximate" in the sidecar.
|
||||
_MIC_FS_PSI = 0.0125 / _INT16_FS # ~0.5 psi full-scale assumption
|
||||
# Microphone scale factor, psi per MicL count: one count is 0.25 Pa
|
||||
# (waveform_codec.MIC_PA_PER_COUNT, measured against Blastware's psi(L) on
|
||||
# 1,729,253 DL2 intervals). It replaces a "~0.5 psi full-scale" guess,
|
||||
# 0.0125 / 32768, that read every mic peak ~95x low (2026-10-31).
|
||||
_PA_PER_PSI = 6894.757
|
||||
_MIC_PSI_PER_COUNT = _wc.MIC_PA_PER_COUNT / _PA_PER_PSI
|
||||
|
||||
|
||||
def _decode_strt(strt: bytes) -> dict:
|
||||
"""
|
||||
Decode the 21-byte STRT record from a BW file.
|
||||
Decode the 21-byte STRT record from a BW file: the waveform key (4B).
|
||||
|
||||
Returns dict with waveform_key (4B), total_samples, pretrig_samples,
|
||||
rectime_seconds. Falls back to None on truncated/missing fields.
|
||||
The record holds no setup fields. It was once read as total samples
|
||||
([8:10]), pre-trigger samples ([16:18]) and record time ([18]), but [18] is
|
||||
the record-type marker (0x46 waveform, 0x0A histogram) and the others
|
||||
matched nothing (#44/#45); those come from the recording-setup block.
|
||||
"""
|
||||
if len(strt) < 21 or strt[0:4] != b"STRT":
|
||||
return {}
|
||||
return {
|
||||
"waveform_key": strt[6:10].hex(),
|
||||
"total_samples": struct.unpack_from(">H", strt, 8)[0],
|
||||
"pretrig_samples": struct.unpack_from(">H", strt, 16)[0],
|
||||
"rectime_seconds": strt[18],
|
||||
}
|
||||
|
||||
|
||||
def _find_first_string(buf: bytes, label: bytes, max_len: int = 256) -> Optional[str]:
|
||||
"""
|
||||
Search `buf` for `label` (e.g. b"Project:") and return the
|
||||
null-terminated ASCII string that follows, stripped.
|
||||
"""
|
||||
pos = buf.find(label)
|
||||
if pos < 0:
|
||||
return None
|
||||
start = pos + len(label)
|
||||
end = buf.find(b"\x00", start, start + max_len)
|
||||
if end < 0:
|
||||
end = start + max_len
|
||||
text = buf[start:end].decode("ascii", errors="replace").strip()
|
||||
return text or None
|
||||
return {"waveform_key": strt[6:10].hex()}
|
||||
|
||||
|
||||
def _decode_samples_4ch_int16_le(stream: bytes) -> dict[str, list[int]]:
|
||||
@@ -762,31 +751,33 @@ def _decode_samples_4ch_int16_le(stream: bytes) -> dict[str, list[int]]:
|
||||
}
|
||||
|
||||
|
||||
def _peaks_from_samples(samples: dict[str, list[int]]) -> PeakValues:
|
||||
def _peaks_from_samples(samples: dict[str, list[int]],
|
||||
geo_fs_ins: float = _GEO_NORMAL_FS_INS) -> PeakValues:
|
||||
"""
|
||||
Compute approximate peaks from raw int16 samples assuming Normal-range
|
||||
geophone sensitivity. Used by the BW-importer when the 0C waveform
|
||||
record (the device's authoritative peaks) is unavailable.
|
||||
Compute peaks from raw int16 samples at the given geophone full scale
|
||||
(Normal, 10 in/s, unless the file's range says otherwise). Used by the
|
||||
BW-importer when the 0C waveform record (the device's authoritative peaks)
|
||||
is unavailable.
|
||||
"""
|
||||
def _peak_ins(ch: list[int]) -> float:
|
||||
if not ch:
|
||||
return 0.0
|
||||
m = max(abs(int(v)) for v in ch)
|
||||
return m / _GEO_INT16_FS * _GEO_NORMAL_FS_INS
|
||||
return m / _GEO_INT16_FS * geo_fs_ins
|
||||
|
||||
tran = _peak_ins(samples.get("Tran", []))
|
||||
vert = _peak_ins(samples.get("Vert", []))
|
||||
long_ = _peak_ins(samples.get("Long", []))
|
||||
|
||||
# Mic in psi (approximate)
|
||||
# Mic in psi: one count = 0.25 Pa
|
||||
mic_ch = samples.get("MicL", []) or []
|
||||
mic = max((abs(int(v)) for v in mic_ch), default=0) * _MIC_FS_PSI
|
||||
mic = max((abs(int(v)) for v in mic_ch), default=0) * _MIC_PSI_PER_COUNT
|
||||
|
||||
# Peak vector sum: max over time of sqrt(T^2 + V^2 + L^2)
|
||||
pvs = 0.0
|
||||
n = min(len(samples.get("Tran", [])), len(samples.get("Vert", [])), len(samples.get("Long", [])))
|
||||
if n:
|
||||
scale = _GEO_NORMAL_FS_INS / _GEO_INT16_FS
|
||||
scale = geo_fs_ins / _GEO_INT16_FS
|
||||
T = samples["Tran"]; V = samples["Vert"]; L = samples["Long"]
|
||||
for i in range(n):
|
||||
t = T[i] * scale
|
||||
@@ -802,6 +793,12 @@ def _peaks_from_samples(samples: dict[str, list[int]]) -> PeakValues:
|
||||
)
|
||||
|
||||
|
||||
# STRT[18], the record-type byte (#41): 0x46 on every one of DL2's 6,577
|
||||
# waveform files and 0x0A on every one of its 63,535 histograms (measured
|
||||
# 2026-10-29). Manual / Event / Combo never occur there, so their bytes are
|
||||
# unknown and decode as None, not as a guess.
|
||||
_RECORD_TYPE_BY_STRT = {0x46: "Waveform", 0x0A: "Histogram"}
|
||||
|
||||
_RECORD_TYPE_BY_EXT_SUFFIX = {
|
||||
'H': 'Histogram',
|
||||
'W': 'Waveform',
|
||||
@@ -855,6 +852,21 @@ def derive_record_type_from_filename(filename, default: str = "Waveform") -> str
|
||||
_RECSETUP_MARKER = b"Standard Recording Setup"
|
||||
_RECTIME_OFFSET_BEFORE_MARKER = 30
|
||||
|
||||
# The recording-setup block, found by its structure rather than by name
|
||||
# (#44/#45). It ends in the setup's name -- whatever the operator saved it as
|
||||
# ("Standard Recording Setup", "BE16352.set", ...), NUL-terminated, right after
|
||||
# the bytes 1c 08 -- and the four user notes follow the name as label/value
|
||||
# string pairs. 37% of the DL2 archive's files name the setup something other
|
||||
# than "Standard Recording Setup", which _RECSETUP_MARKER cannot see; the 1c 08
|
||||
# form matches exactly once in every one of its 70,041 files (measured
|
||||
# 2026-10-29). Offsets are from the first byte of the name.
|
||||
_SETUP_NAME_RE = re.compile(rb"\x1c\x08([\x20-\x7e]{1,40})\x00")
|
||||
_SAMPLE_RATE_BEFORE_NAME = 42 # uint16 BE, samples per second
|
||||
_PRETRIG_BEFORE_NAME = 36 # float32 BE, seconds, negative (-0.25, -0.0625 ...)
|
||||
_RECTIME_BEFORE_NAME = 30 # float32 BE, seconds (the marker's offset above)
|
||||
_SAMPLE_RATES = (1024, 2048, 4096)
|
||||
_NOTE_SLOTS = 4 # project, client, operator, sensor location
|
||||
|
||||
# The instrument's own event record, which the unit sends in its 5A stream and
|
||||
# Blastware therefore copies into every waveform file (measured 2026-10-26; see
|
||||
# the Series-III reference, "The embedded event record"):
|
||||
@@ -934,6 +946,86 @@ def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
|
||||
return rt if 0.05 <= rt <= 600.0 else None
|
||||
|
||||
|
||||
def _setup_name_at(raw: bytes) -> Optional[int]:
|
||||
"""Offset of the recording setup's name, or None unless exactly one
|
||||
candidate is found -- two would mean the anchor is not what it seems."""
|
||||
found = [m.start(1) for m in _SETUP_NAME_RE.finditer(raw)]
|
||||
return found[0] if len(found) == 1 else None
|
||||
|
||||
|
||||
def _setup_sample_rate(raw: bytes) -> Optional[int]:
|
||||
"""The configured sample rate (samples/s) from the recording-setup block."""
|
||||
k = _setup_name_at(raw)
|
||||
if k is None or k < _SAMPLE_RATE_BEFORE_NAME:
|
||||
return None
|
||||
sr = struct.unpack_from(">H", raw, k - _SAMPLE_RATE_BEFORE_NAME)[0]
|
||||
return sr if sr in _SAMPLE_RATES else None
|
||||
|
||||
|
||||
def _setup_record_time(raw: bytes) -> Optional[float]:
|
||||
"""The configured post-trigger record time (s) from the recording-setup
|
||||
block. A histogram's block carries a stale value here: callers use it
|
||||
for waveforms only."""
|
||||
k = _setup_name_at(raw)
|
||||
if k is None or k < _RECTIME_BEFORE_NAME:
|
||||
return None
|
||||
rt = struct.unpack_from(">f", raw, k - _RECTIME_BEFORE_NAME)[0]
|
||||
return rt if 0.05 <= rt <= 600.0 else None
|
||||
|
||||
|
||||
def _setup_pretrigger(raw: bytes) -> Optional[float]:
|
||||
"""The pre-trigger (s, negative) from the recording-setup block -- the
|
||||
value Blastware prints, -0.247 s as well as -0.25 s (6,453 of 6,453 DL2
|
||||
waveforms, measured 2026-10-29). A histogram's block holds 0.0."""
|
||||
k = _setup_name_at(raw)
|
||||
if k is None or k < _PRETRIG_BEFORE_NAME:
|
||||
return None
|
||||
pre = struct.unpack_from(">f", raw, k - _PRETRIG_BEFORE_NAME)[0]
|
||||
return pre if -2.0 <= pre <= 0.0 else None
|
||||
|
||||
|
||||
def _setup_notes(raw: bytes) -> ProjectInfo:
|
||||
"""The setup name and the four user notes. Blastware lets the operator
|
||||
relabel the note slots ("Seis. Loc:", "Location:", "Project: " ...), so the
|
||||
labels are not searched for: slot n is the nth label/value pair after the
|
||||
name, as in bw_ascii_report. An empty value is None."""
|
||||
k = _setup_name_at(raw)
|
||||
if k is None:
|
||||
return ProjectInfo()
|
||||
parts = raw[k:].split(b"\x00", 1 + 2 * _NOTE_SLOTS)
|
||||
text = [p.decode("ascii", errors="replace").strip() or None for p in parts]
|
||||
text += [None] * (2 + 2 * _NOTE_SLOTS - len(text))
|
||||
project, client, operator, location = text[2:2 + 2 * _NOTE_SLOTS:2]
|
||||
return ProjectInfo(setup_name=text[0], project=project, client=client,
|
||||
operator=operator, sensor_location=location)
|
||||
|
||||
|
||||
# The geophone range sits in the setup's channel blocks, which follow the
|
||||
# notes: the byte 29 after each geophone label (`00 00 01 Tran ...`). 0x00 is
|
||||
# Normal, 0x01 Sensitive -- Blastware's GeoRange on 70,042 / 70,042 DL2 events,
|
||||
# all three channels agreeing on every one (measured 2026-11-01). SFM's live
|
||||
# 1A read has the same byte at label+33.
|
||||
_RANGE_AFTER_LABEL = 29
|
||||
_CHANNEL_BLOCK_SPAN = 2000 # how far past the setup name the blocks may sit
|
||||
|
||||
|
||||
def _setup_geo_range(raw: bytes) -> tuple[Optional[int], Optional[str]]:
|
||||
"""(geo_range, problem): 0 Normal or 1 Sensitive when all three geophone
|
||||
channels say the same, else None and why."""
|
||||
k = _setup_name_at(raw)
|
||||
if k is None:
|
||||
return None, "no recording-setup block to read the geophone range from"
|
||||
found = {}
|
||||
for label in (b"Tran", b"Vert", b"Long"):
|
||||
i = raw.find(b"\x00\x00\x01" + label, k, k + _CHANNEL_BLOCK_SPAN)
|
||||
p = i + 3 + _RANGE_AFTER_LABEL
|
||||
found[label.decode()] = raw[p] if i >= 0 and p < len(raw) else None
|
||||
values = set(found.values())
|
||||
if len(values) == 1 and values <= {0, 1}:
|
||||
return values.pop(), None
|
||||
return None, f"geophone range not read: channel range bytes {found}"
|
||||
|
||||
|
||||
def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event:
|
||||
"""Parse a Blastware event file into an Event: `decode_blastware_bytes` on its
|
||||
bytes, `name` defaulting to the file's own (see there -- never a time source)."""
|
||||
@@ -950,13 +1042,15 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
receives straight from a unit has no Blastware name.
|
||||
|
||||
Recovers:
|
||||
- waveform_key, rectime_seconds, total_samples, pretrig_samples
|
||||
(from the STRT record)
|
||||
- waveform_key (from the STRT record)
|
||||
- sample_rate; for a waveform also rectime_seconds, total_samples and
|
||||
pretrig_samples (from the recording-setup block and the decoded
|
||||
sample count)
|
||||
- timestamp: a waveform's from the instrument's embedded event record
|
||||
(`timestamp_source` "event_record"); without a validated one, an
|
||||
estimate from the footer with a `decode_problems` entry; a histogram's
|
||||
from the footer start ("footer")
|
||||
- project_info (from ASCII labels embedded in the body)
|
||||
- project_info: setup name and the four user notes, by position
|
||||
- raw_samples (Tran/Vert/Long/MicL int16 lists)
|
||||
- peak_values (computed from raw_samples; approximate — see notes
|
||||
on _peaks_from_samples about Normal-range assumption)
|
||||
@@ -1071,25 +1165,40 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
else:
|
||||
samples = decoded_to_adc_counts(decoded)
|
||||
|
||||
# Metadata strings (label-anchored search across the body).
|
||||
project = _find_first_string(body, b"Project:")
|
||||
client = _find_first_string(body, b"Client:")
|
||||
user = _find_first_string(body, b"User Name:")
|
||||
seisloc = _find_first_string(body, b"Seis Loc:")
|
||||
|
||||
# Build the Event.
|
||||
ev = Event(index=-1)
|
||||
if strt_fields.get("waveform_key"):
|
||||
ev._waveform_key = bytes.fromhex(strt_fields["waveform_key"])
|
||||
# Derive record_type from the filename's extension suffix (H/W/M/E/C).
|
||||
# When called from save_imported_bw the path here is a tmp file with a
|
||||
# ".bw" suffix, so the derivation falls back to "Waveform" and the
|
||||
# caller overrides ev.record_type using the original filename — see
|
||||
# waveform_store.save_imported_bw.
|
||||
ev.record_type = derive_record_type_from_filename(name)
|
||||
ev.rectime_seconds = strt_fields.get("rectime_seconds")
|
||||
ev.total_samples = strt_fields.get("total_samples")
|
||||
ev.pretrig_samples = strt_fields.get("pretrig_samples")
|
||||
# The record type comes from the bytes: STRT[18] (#41). The filename's
|
||||
# last letter is only a cross-check -- SFM's own downloads have no name,
|
||||
# and a manual download's (".QZ0") carries no type at all.
|
||||
type_byte = strt_raw[18]
|
||||
ev.record_type = _RECORD_TYPE_BY_STRT.get(type_byte)
|
||||
if ev.record_type is None:
|
||||
ev.decode_problems.append(f"unknown record type byte 0x{type_byte:02x} at STRT[18]")
|
||||
named_type = derive_record_type_from_filename(name, default=None) if name else None
|
||||
if named_type is not None and ev.record_type is not None and named_type != ev.record_type:
|
||||
log.warning("%s: record type %s from the file disagrees with the filename's %s; "
|
||||
"the file's is kept", label, ev.record_type, named_type)
|
||||
|
||||
# Setup fields come from the recording-setup block (#44/#45), not the STRT
|
||||
# record: STRT[18] is the record-type marker (0x46 / 0x0A), which is why
|
||||
# every waveform used to read "70 s". A histogram has no record time or
|
||||
# pre-trigger -- Blastware reports neither.
|
||||
ev.sample_rate = _setup_sample_rate(raw)
|
||||
ev.geo_range, range_problem = _setup_geo_range(raw)
|
||||
if range_problem:
|
||||
ev.decode_problems.append(range_problem + "; peaks assume the Normal range")
|
||||
if is_waveform_body:
|
||||
ev.rectime_seconds = _setup_record_time(raw)
|
||||
ev.total_samples = len(samples["Tran"]) or None
|
||||
pre = _setup_pretrigger(raw)
|
||||
if pre is not None and ev.sample_rate:
|
||||
ev.pretrig_samples = round(-pre * ev.sample_rate)
|
||||
if None in (ev.sample_rate, ev.rectime_seconds, ev.pretrig_samples):
|
||||
ev.decode_problems.append(
|
||||
f"recording-setup block incomplete: sample rate {ev.sample_rate}, "
|
||||
f"record time {ev.rectime_seconds}, pre-trigger {pre}")
|
||||
|
||||
# Event timestamp. The footer's two timestamps mean different things by
|
||||
# record type:
|
||||
@@ -1150,9 +1259,7 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
)
|
||||
ev.timestamp_source = "footer"
|
||||
|
||||
ev.project_info = ProjectInfo(
|
||||
project=project, client=client, operator=user, sensor_location=seisloc,
|
||||
)
|
||||
ev.project_info = _setup_notes(raw)
|
||||
ev.raw_samples = samples
|
||||
# Sensor self-check traces from the binary's trailing block (waveform
|
||||
# events only; returns {} for histograms / when absent). Carried on the
|
||||
@@ -1170,7 +1277,17 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
||||
# 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
|
||||
# The geophone full scale is the file's range; Normal when it wasn't read.
|
||||
geo_fs = _GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS)
|
||||
ev.peak_values = _peaks_from_samples(samples, geo_fs) if has_samples else None
|
||||
if not is_waveform_body and ev.peak_values is not None:
|
||||
# A histogram stores each interval's vector sum (squared); the event's
|
||||
# is the largest. Combining the channel peaks instead read high on 86%
|
||||
# of DL2's histograms -- they can come from different moments.
|
||||
pvs = interval_pvs(body)
|
||||
if pvs:
|
||||
ev.peak_values.peak_vector_sum = (
|
||||
max(pvs) * _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS)
|
||||
ev._a5_frames = None # not recoverable from BW file
|
||||
|
||||
return ev
|
||||
@@ -40,6 +40,13 @@ iterate 32-stride and stop before the tail.
|
||||
[24:28] 4-byte variable purpose unknown (possibly CRC or timestamp delta)
|
||||
[28:32] block-end signature see "Two block tails" below
|
||||
|
||||
⚠ CORRECTED 2026-10-30 (measured): [21:25] is the interval's peak vector sum
|
||||
SQUARED, uint32 BE in 0.005 in/s units. sqrt([21:25]) x 0.005 is the "Geo PVS"
|
||||
Blastware prints for the interval, on 1,668,073 / 1,668,074 standard DL2
|
||||
intervals checked against the _XML.XML reports. [21:23] is zero only while the
|
||||
square is below 65,536 (PVS < 1.28 in/s), which is why it looked constant; only
|
||||
[25:28] is still unexplained. `interval_pvs` reads it.
|
||||
|
||||
**Every per-channel field is uint16 BIG-endian** (confirmed 2026-08-25).
|
||||
Only ``block_ctr`` at [2:4] is little-endian.
|
||||
|
||||
@@ -124,6 +131,7 @@ record list.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import struct
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
@@ -216,6 +224,7 @@ def _decode_block(block: bytes) -> Optional[dict]:
|
||||
"m_peak": m_peak,
|
||||
"m_halfp": m_halfp,
|
||||
"meta_var": var_meta,
|
||||
"pvs_sq": int.from_bytes(block[21:25], "big"),
|
||||
"is_terminal": block[28:32] == _BLOCK_TAIL_TERMINAL,
|
||||
}
|
||||
|
||||
@@ -319,6 +328,16 @@ def decode_histogram_body_full(body: bytes) -> Optional[List[dict]]:
|
||||
return records if records else None
|
||||
|
||||
|
||||
def interval_pvs(body: bytes) -> Optional[List[float]]:
|
||||
"""Each interval's peak vector sum, in the geo peak units (0.005 in/s at
|
||||
Normal range): the square root of the square the device stores with every
|
||||
interval. This is the vector sum at an instant, as Blastware prints it --
|
||||
not the magnitude of the three channel peaks, which can come from
|
||||
different moments. None when the body has no valid blocks."""
|
||||
records = _walk_auto(body)
|
||||
return [math.sqrt(r["pvs_sq"]) for r in records] if records else None
|
||||
|
||||
|
||||
def half_period_to_hz(halfp: int) -> Optional[float]:
|
||||
"""Convert a half-period in samples to frequency in Hz.
|
||||
|
||||
@@ -356,7 +375,10 @@ def geo_count_to_ins(count: int) -> float:
|
||||
# [4] 0x0a
|
||||
# [5 ...] one record per interval: per channel a BIG-endian uint16 peak and
|
||||
# half-period (Tran, Vert, Long[, MicL]), then 0x0000, then one more
|
||||
# word ("meta_var" keeps those 4 bytes)
|
||||
# word ("meta_var" keeps those 4 bytes). Measured 2026-10-30: those
|
||||
# 4 bytes are the interval's peak vector sum SQUARED, uint32 BE in
|
||||
# 0.005 in/s units -- sqrt matches Blastware's "Geo PVS" on 34.5 M
|
||||
# DL2 sub-minute intervals; the 0x0000 is its high word
|
||||
# [-7:] trailer: 3 bytes, then the 4-byte tail -- 9c 06 00 42 on the
|
||||
# stream's LAST block
|
||||
#
|
||||
@@ -486,6 +508,7 @@ def _decode_record(body: bytes, q: int, rec: int, off: int) -> dict:
|
||||
"m_peak": be16(q + 12) if mic else None,
|
||||
"m_halfp": be16(q + 14) if mic else None,
|
||||
"meta_var": bytes(body[q + z:q + z + 4]),
|
||||
"pvs_sq": int.from_bytes(body[q + z:q + z + 4], "big"),
|
||||
"is_terminal": False,
|
||||
}
|
||||
|
||||
|
||||
@@ -543,6 +543,9 @@ class Event:
|
||||
total_samples: Optional[int] = None # from STRT record: expected total sample-sets
|
||||
pretrig_samples: Optional[int] = None # from STRT record: pre-trigger sample count
|
||||
rectime_seconds: Optional[int] = None # from STRT record: record duration (seconds)
|
||||
# Geophone range from the recording setup, as ComplianceConfig.geo_range:
|
||||
# 0 Normal (10 in/s full scale), 1 Sensitive (1.25 in/s). None: not read.
|
||||
geo_range: Optional[int] = None
|
||||
|
||||
# Sensor self-check traces keyed by channel label — the short diagnostic
|
||||
# waveforms the unit records when it pulses each sensor before monitoring
|
||||
|
||||
@@ -628,23 +628,34 @@ def decoded_to_adc_counts(decoded: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
# One MicL count is 0.25 Pa (measured 2026-10-31): count x 0.25 Pa matches
|
||||
# Blastware's "MicL Peak psi(L)" on all 1,729,253 DL2 histogram intervals
|
||||
# checked.
|
||||
MIC_PA_PER_COUNT = 0.25
|
||||
|
||||
# Blastware's dB(L) offset sits a hair above the exact 20 log10(0.25 Pa /
|
||||
# 20 uPa) = 81.93820: any value in [81.9383, 81.9385] matches its dB on
|
||||
# 1,729,252 / 1,729,253 intervals (the one left printed "0.000"), while
|
||||
# 81.93820 rounds count 129 (162 intervals) to 124.1 against Blastware's
|
||||
# 124.2, and the 81.94 first fitted to a handful of values misses counts 119
|
||||
# and 132. Its display chain presumably carries rounded constants; the
|
||||
# window, not the physics, is what is measured.
|
||||
_MIC_DB_REF = 81.9384
|
||||
|
||||
|
||||
def mic_count_to_db(count: int) -> float:
|
||||
"""Convert a MicL ADC count to dB(L) for BW-display-compatible output.
|
||||
|
||||
Empirical formula (confirmed 2026-05-11 against V70 fixture: count=813
|
||||
→ 140.1 dB; count=±1 → ±81.94 dB; count=±24 → ±109.5 dB):
|
||||
dB = sign(count) × (81.9384 + 20 × log10(|count|)) for |count| ≥ 1
|
||||
dB = 0.0 for count == 0
|
||||
|
||||
dB = sign(count) × (81.94 + 20 × log10(|count|)) for |count| ≥ 1
|
||||
dB = 0.0 for count == 0
|
||||
|
||||
The constant 81.94 corresponds to 10^(81.94/20) ≈ 12490 mic ADC counts
|
||||
being the dB(L) reference level — almost certainly a calibration
|
||||
constant from the device's mic.
|
||||
81.9384 ≈ 20 log10(0.25 Pa / 20 µPa); see _MIC_DB_REF.
|
||||
count=±1 → ±81.94 dB; count=813 → 140.14 dB (the V70 fixture).
|
||||
"""
|
||||
if count == 0:
|
||||
return 0.0
|
||||
sign = 1.0 if count > 0 else -1.0
|
||||
return sign * (81.94 + 20.0 * math.log10(abs(count)))
|
||||
return sign * (_MIC_DB_REF + 20.0 * math.log10(abs(count)))
|
||||
|
||||
|
||||
# ── A5-frame entry point ────────────────────────────────────────────────────
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "seismo-relay"
|
||||
version = "0.32.0"
|
||||
version = "0.33.0"
|
||||
description = "Python client and REST server for MiniMate Plus seismographs"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
The Series 3 decode checker: SFM's file-only decode of every event, compared
|
||||
with Blastware's `_XML.XML` report of the same event.
|
||||
|
||||
python scratch/check_s3_decode.py <binaries dir> <xml dir> [options]
|
||||
|
||||
Each event is decoded the way SFM ingest does, from its bytes alone -- no
|
||||
filename, no report -- and every field, waveform sample and histogram interval
|
||||
is compared (minimateplus/decode_check.py). Results go to a run folder outside
|
||||
the repo, because they carry customer project names:
|
||||
|
||||
~/dl2-archive/checker-runs/<YYYYmmdd-HHMMSS>/
|
||||
results.jsonl.gz one line per event: file, attrs, results rows
|
||||
run.json args, commit, event count, wall time
|
||||
|
||||
Partial runs: --serial BE9441, --year 2024, --type W|H, --field samples.,
|
||||
--sample 2000 [--seed K]. Spec:
|
||||
docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md.
|
||||
|
||||
A lab tool (ADR 0003): it may import from sfm/; the comparison it runs may not.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
_REPO = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(_REPO))
|
||||
|
||||
from minimateplus.bw_xml_report import XmlReport, parse_xml_report_file # noqa: E402
|
||||
from minimateplus.decode_check import compare, sfm_side # noqa: E402
|
||||
from minimateplus.decode_check_carveouts import CARVEOUTS # noqa: E402
|
||||
from scratch import decode_check_report as report # noqa: E402
|
||||
|
||||
RUNS_DIR = Path.home() / "dl2-archive" / "checker-runs"
|
||||
_BIN = re.compile(r"^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$", re.I)
|
||||
_MODEL = re.compile(r"^V\s+\S+\s+(.*)$")
|
||||
_EPOCH = datetime(1985, 1, 1)
|
||||
|
||||
|
||||
def find_pairs(bin_dir: Path, xml_dir: Path) -> list[tuple[str, Path, Optional[Path]]]:
|
||||
"""(basename, binary, XML report or None) for every Series 3 event file
|
||||
under `bin_dir`, deduped by basename -- an ACH folder's Sent/ mirrors its
|
||||
root."""
|
||||
xmls = {p.name.upper(): p for p in Path(xml_dir).iterdir() if p.is_file()}
|
||||
seen: dict[str, tuple[str, Path]] = {}
|
||||
for root, _, files in os.walk(bin_dir):
|
||||
for f in files:
|
||||
if _BIN.match(f) and f.upper() not in seen:
|
||||
seen[f.upper()] = (f, Path(root) / f)
|
||||
out = []
|
||||
for key in sorted(seen):
|
||||
name, path = seen[key]
|
||||
stem, ext = name.split(".")
|
||||
out.append((name, path, xmls.get(f"{stem}_{ext}_XML.XML".upper())))
|
||||
return out
|
||||
|
||||
|
||||
def event_attrs(name: str, ref: XmlReport, raw: bytes) -> dict[str, str]:
|
||||
"""The keys failures are grouped by -- all from the reference or the file."""
|
||||
s = ref.scalars
|
||||
m = _MODEL.match(s.get("Version", ""))
|
||||
date = s.get("EventDate") or s.get("HistogramStartDate") or ""
|
||||
return {
|
||||
"model": m.group(1) if m else s.get("Version", "?"),
|
||||
"serial": s.get("SerialNumber", "?"),
|
||||
"type": s.get("EventType", "?"),
|
||||
"year": date[:4] or "?",
|
||||
"sample_rate": s.get("SampleRate", "?").split(" ")[0],
|
||||
"range": s.get("GeoRange", "?"),
|
||||
"mic_units": ref.event_units or "?",
|
||||
"interval": s.get("IntervalSize", "-"),
|
||||
"setup_standard": "yes" if b"Standard Recording Setup" in raw else "no",
|
||||
}
|
||||
|
||||
|
||||
def check_event(name: str, bin_path: str, xml_path: Optional[str]) -> dict:
|
||||
"""One event: its grouping attrs and one row per compared field. A missing
|
||||
reference or any failure is a single row, so a run never stops on one file."""
|
||||
if xml_path is None:
|
||||
return {"file": name, "attrs": {},
|
||||
"results": [["event", "no_reference", None, None, "no XML report", None]]}
|
||||
try:
|
||||
raw = Path(bin_path).read_bytes()
|
||||
ref = parse_xml_report_file(xml_path)
|
||||
rows = compare(sfm_side(raw), ref, CARVEOUTS)
|
||||
return {"file": name, "attrs": event_attrs(name, ref, raw),
|
||||
"results": [[r.field, r.verdict, r.bw, r.sfm, r.detail, r.carveout] for r in rows]}
|
||||
except Exception as exc: # noqa: BLE001 -- one bad file must not stop a run
|
||||
return {"file": name, "attrs": {},
|
||||
"results": [["event", "error", None, None, repr(exc)[:300], None]]}
|
||||
|
||||
|
||||
def _check_pair(pair: tuple[str, str, Optional[str]]) -> dict:
|
||||
return check_event(*pair)
|
||||
|
||||
|
||||
def _quiet() -> None:
|
||||
logging.disable(logging.CRITICAL)
|
||||
|
||||
|
||||
def _filename_prefix(serial: str) -> str:
|
||||
"""BE9441 -> K441: the prefix Blastware's filenames encode a serial as."""
|
||||
num = int(re.sub(r"\D", "", serial))
|
||||
return f"{chr(ord('B') + num // 1000)}{num % 1000:03d}"
|
||||
|
||||
|
||||
def _filename_year(name: str) -> int:
|
||||
stem, ext = name.upper().split(".")
|
||||
return (_EPOCH + timedelta(seconds=int(stem[4:8], 36) * 1296 + int(ext[:2], 36))).year
|
||||
|
||||
|
||||
def _git_head() -> Optional[str]:
|
||||
try:
|
||||
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=_REPO, capture_output=True,
|
||||
text=True, check=True).stdout.strip()
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return None
|
||||
|
||||
|
||||
_SCOPE = ("bin_dir", "xml_dir", "serial", "year", "type", "field", "sample", "seed")
|
||||
|
||||
|
||||
def _scope(args: dict) -> dict:
|
||||
return {k: args.get(k) for k in _SCOPE}
|
||||
|
||||
|
||||
def _previous_run(out_dir: Path, args: dict) -> Optional[Path]:
|
||||
"""The newest other completed run (run.json written) of the same scope in
|
||||
the runs folder -- only for runs kept there. A sample or a one-serial run
|
||||
is no baseline for a full run, nor the other way round."""
|
||||
if out_dir.parent.resolve() != RUNS_DIR.resolve():
|
||||
return None
|
||||
want = _scope(args)
|
||||
for p in sorted(RUNS_DIR.iterdir(), reverse=True):
|
||||
if not p.is_dir() or p.resolve() == out_dir.resolve():
|
||||
continue
|
||||
try:
|
||||
if _scope(json.loads((p / "run.json").read_text())["args"]) == want:
|
||||
return p
|
||||
except (OSError, KeyError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _print_one(name: str, pairs: list[tuple[str, Path, Optional[Path]]]) -> int:
|
||||
"""--file: check one event and print its table; no run folder."""
|
||||
match = [p for p in pairs if p[0].upper() == name.upper()]
|
||||
if not match:
|
||||
print(f"{name}: no such event file under the binaries folder", file=sys.stderr)
|
||||
return 1
|
||||
n, b, x = match[0]
|
||||
ev = check_event(n, str(b), str(x) if x else None)
|
||||
print(f"{n} {ev['attrs']}")
|
||||
print(f"{'field':30s} {'verdict':12s} {'Blastware':30s} {'SFM':30s} detail")
|
||||
for field, verdict, bw, sfm, detail, carveout in ev["results"]:
|
||||
note = f"{detail} {('[' + carveout + ']') if carveout else ''}".strip()
|
||||
print(f"{field:30.30s} {verdict:12s} {str(bw):30.30s} {str(sfm):30.30s} {note}")
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: Optional[list[str]] = None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("bin_dir", type=Path)
|
||||
ap.add_argument("xml_dir", type=Path)
|
||||
ap.add_argument("--out", type=Path, help=f"run folder (default {RUNS_DIR}/<timestamp>)")
|
||||
ap.add_argument("--serial", action="append", default=[], help="e.g. BE9441; repeatable")
|
||||
ap.add_argument("--year", action="append", type=int, default=[], help="event year; repeatable")
|
||||
ap.add_argument("--type", choices=("W", "H"), help="waveforms or histograms only")
|
||||
ap.add_argument("--field", action="append", default=[], help="keep result rows whose field starts with this")
|
||||
ap.add_argument("--sample", type=int, help="check a random sample of N events")
|
||||
ap.add_argument("--seed", type=int, default=0)
|
||||
ap.add_argument("--jobs", type=int, default=os.cpu_count() or 1)
|
||||
ap.add_argument("--file", help="check one event and print its table")
|
||||
ap.add_argument("--compare-to", type=Path, help="an earlier run folder to diff against")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
started = time.monotonic()
|
||||
pairs = find_pairs(args.bin_dir, args.xml_dir)
|
||||
if args.file:
|
||||
return _print_one(args.file, pairs)
|
||||
if args.serial:
|
||||
prefixes = tuple(_filename_prefix(s) for s in args.serial)
|
||||
pairs = [p for p in pairs if p[0].upper().startswith(prefixes)]
|
||||
if args.year:
|
||||
pairs = [p for p in pairs if _filename_year(p[0]) in args.year]
|
||||
if args.type:
|
||||
pairs = [p for p in pairs if p[0].upper().endswith(args.type)]
|
||||
if args.sample is not None and args.sample < len(pairs):
|
||||
pairs = sorted(random.Random(args.seed).sample(pairs, args.sample))
|
||||
|
||||
out_dir = args.out or RUNS_DIR / datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
work = [(n, str(b), str(x) if x else None) for n, b, x in pairs]
|
||||
|
||||
_quiet()
|
||||
if args.jobs <= 1:
|
||||
results = map(_check_pair, work)
|
||||
pool = None
|
||||
else:
|
||||
pool = ProcessPoolExecutor(args.jobs, initializer=_quiet)
|
||||
results = pool.map(_check_pair, work, chunksize=64)
|
||||
try:
|
||||
with gzip.open(out_dir / "results.jsonl.gz", "wt", encoding="utf-8") as fh:
|
||||
for ev in results:
|
||||
if args.field:
|
||||
ev["results"] = [r for r in ev["results"] if r[0].startswith(tuple(args.field))]
|
||||
fh.write(json.dumps(ev) + "\n")
|
||||
finally:
|
||||
if pool is not None:
|
||||
pool.shutdown()
|
||||
|
||||
run = {"args": {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()},
|
||||
"commit": _git_head(), "events": len(work),
|
||||
"seconds": round(time.monotonic() - started, 1)}
|
||||
(out_dir / "run.json").write_text(json.dumps(run, indent=2))
|
||||
agg = report.aggregate(out_dir / "results.jsonl.gz")
|
||||
prev = args.compare_to or _previous_run(out_dir, run["args"])
|
||||
if prev is not None and (prev / "results.jsonl.gz").exists():
|
||||
chg = report.compare_runs(prev / "results.jsonl.gz", out_dir / "results.jsonl.gz")
|
||||
report.write_changes(chg, out_dir / "changes.md")
|
||||
agg["regressions"] = len(chg["regressions"])
|
||||
report.write_summary(agg, out_dir / "summary.md")
|
||||
report.write_details(agg, out_dir / "details.json")
|
||||
print(out_dir)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,235 @@
|
||||
"""
|
||||
Reports for the Series 3 decode checker (scratch/check_s3_decode.py).
|
||||
|
||||
From a run's results.jsonl.gz:
|
||||
|
||||
summary.md for Brian: per field, how many events got each verdict; how many
|
||||
fields fully match; non-matches by event year; carve-out counts
|
||||
details.json for Claude: each non-matching (field, verdict) with the event
|
||||
attributes its failures concentrate in, and example events, each
|
||||
with a command that re-runs just that event
|
||||
|
||||
Streams the results file and holds only counters and a capped example list.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import json
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
|
||||
_NOT_DONE = ("mismatch", "sfm_blank", "error")
|
||||
_GROUP_SHARE = 0.10 # an attribute value is shown when it holds >= 10% of a failure
|
||||
_CONCENTRATED = 0.95 # ... and flagged when nearly every compared event with it fails
|
||||
_EXAMPLES = 8
|
||||
_KEEP = 60 # candidate examples kept per failure while streaming
|
||||
|
||||
|
||||
def _run_dirs(results_path: Path) -> tuple[str, str]:
|
||||
run = results_path.parent / "run.json"
|
||||
try:
|
||||
args = json.loads(run.read_text())["args"]
|
||||
return args["bin_dir"], args["xml_dir"]
|
||||
except (OSError, KeyError, ValueError):
|
||||
return "<bin_dir>", "<xml_dir>"
|
||||
|
||||
|
||||
def aggregate(results_path: Path) -> dict:
|
||||
fields: dict[str, Counter] = defaultdict(Counter)
|
||||
by_year: dict[str, Counter] = defaultdict(Counter)
|
||||
compared: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
|
||||
failing: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
|
||||
examples: dict[str, list] = defaultdict(list)
|
||||
carveouts: Counter = Counter()
|
||||
events = 0
|
||||
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
ev = json.loads(line)
|
||||
events += 1
|
||||
attrs = ev.get("attrs") or {}
|
||||
covered = set()
|
||||
for field, verdict, bw, sfm, detail, carveout in ev["results"]:
|
||||
fields[field][verdict] += 1
|
||||
if carveout:
|
||||
covered.add(carveout)
|
||||
if verdict != "no_reference":
|
||||
for a, v in attrs.items():
|
||||
compared[field][a][str(v)] += 1
|
||||
if verdict in ("match", "accepted", "no_reference"):
|
||||
continue
|
||||
key = f"{field}|{verdict}"
|
||||
by_year[field][attrs.get("year", "?")] += 1
|
||||
for a, v in attrs.items():
|
||||
failing[key][a][str(v)] += 1
|
||||
if len(examples[key]) < _KEEP:
|
||||
examples[key].append({"file": ev["file"], "attrs": attrs, "bw": bw,
|
||||
"sfm": sfm, "detail": detail})
|
||||
carveouts.update(covered)
|
||||
bin_dir, xml_dir = _run_dirs(Path(results_path))
|
||||
return {"events": events, "fields": fields, "by_year": by_year, "compared": compared,
|
||||
"failing": failing, "examples": examples, "carveouts": carveouts,
|
||||
"bin_dir": bin_dir, "xml_dir": xml_dir, "regressions": None}
|
||||
|
||||
|
||||
def _fully_matching(counts: Counter) -> bool:
|
||||
"""Matched somewhere and failed nowhere. A field that only ever has no
|
||||
reference (an always-empty element) has proven nothing."""
|
||||
return (counts["match"] + counts["accepted"]) > 0 and not any(counts[v] for v in _NOT_DONE)
|
||||
|
||||
|
||||
def _events_line(event: Counter) -> str:
|
||||
def n(k: int, what: str) -> str:
|
||||
return f"{k} event{'' if k == 1 else 's'} {what}"
|
||||
return " · ".join(s for s in (n(event["no_reference"], "without a report") if event["no_reference"] else "",
|
||||
n(event["error"], "that failed to check") if event["error"] else "") if s)
|
||||
|
||||
|
||||
def write_summary(agg: dict, path: Path, title: Optional[str] = None) -> None:
|
||||
# The "event" pseudo-field is a whole event with no report or a failure,
|
||||
# not a field: it is reported on its own line.
|
||||
fields = {f: c for f, c in agg["fields"].items() if f != "event"}
|
||||
order = sorted(fields, key=lambda f: (-sum(fields[f][v] for v in _NOT_DONE), f))
|
||||
done = sum(_fully_matching(fields[f]) for f in fields)
|
||||
lines = [f"# Decode check — {title or Path(path).parent.name}", "",
|
||||
f"{agg['events']} events · {done} of {len(fields)} fields fully matching", ""]
|
||||
events = _events_line(agg["fields"].get("event", Counter()))
|
||||
if events:
|
||||
lines += [events, ""]
|
||||
if agg.get("regressions") is not None:
|
||||
n = agg["regressions"]
|
||||
lines += [f"**{n} regressions** since the previous run" + (" — see changes.md" if n else ""), ""]
|
||||
lines += ["| field | " + " | ".join(VERDICTS) + " |", "|---|" + "---:|" * len(VERDICTS)]
|
||||
lines += [f"| {f} | " + " | ".join(str(fields[f][v]) for v in VERDICTS) + " |" for f in order]
|
||||
|
||||
years = sorted({y for c in agg["by_year"].values() for y in c})
|
||||
bad = [f for f in order if not _fully_matching(fields[f])]
|
||||
if bad:
|
||||
lines += ["", "## Not matching, by event year", "",
|
||||
"| field | " + " | ".join(years) + " |", "|---|" + "---:|" * len(years)]
|
||||
lines += [f"| {f} | " + " | ".join(str(agg["by_year"][f][y] or "") for y in years) + " |"
|
||||
for f in bad]
|
||||
if agg["carveouts"]:
|
||||
lines += ["", "## Carve-outs (events covered)", "", "| carve-out | events |", "|---|---:|"]
|
||||
lines += [f"| {c} | {n} |" for c, n in agg["carveouts"].most_common()]
|
||||
Path(path).write_text("\n".join(lines) + "\n")
|
||||
|
||||
|
||||
def write_details(agg: dict, path: Path) -> None:
|
||||
def total_of(key: str) -> int:
|
||||
field, verdict = key.split("|", 1)
|
||||
return agg["fields"][field][verdict]
|
||||
|
||||
out = {}
|
||||
for key in sorted(agg["examples"], key=lambda k: (-total_of(k), k)):
|
||||
field = key.split("|", 1)[0]
|
||||
total = total_of(key)
|
||||
groups = {}
|
||||
for attr, values in agg["failing"].get(key, {}).items():
|
||||
rows = []
|
||||
for value, n in values.most_common():
|
||||
if n < _GROUP_SHARE * total:
|
||||
break
|
||||
seen = agg["compared"][field][attr][value]
|
||||
rate = round(n / seen, 3) if seen else 1.0
|
||||
rows.append({"value": value, "failing": n, "compared": seen, "rate": rate,
|
||||
"concentrated": rate >= _CONCENTRATED})
|
||||
if rows:
|
||||
groups[attr] = rows
|
||||
out[key] = {"total": total, "groups": groups,
|
||||
"examples": _pick_examples(agg, key, groups)}
|
||||
Path(path).write_text(json.dumps(out, indent=1))
|
||||
|
||||
|
||||
def _pick_examples(agg: dict, key: str, groups: dict) -> list[dict]:
|
||||
"""One example per top group value first, then the rest in run order."""
|
||||
pool, picked = agg["examples"][key], []
|
||||
for attr, rows in groups.items():
|
||||
for row in rows:
|
||||
ex = next((e for e in pool if str(e["attrs"].get(attr)) == row["value"]
|
||||
and e not in picked), None)
|
||||
if ex is not None and len(picked) < _EXAMPLES:
|
||||
picked.append(ex)
|
||||
picked += [e for e in pool if e not in picked][: _EXAMPLES - len(picked)]
|
||||
rerun = f"python scratch/check_s3_decode.py {agg['bin_dir']} {agg['xml_dir']} --file "
|
||||
return [{"file": e["file"], "bw": e["bw"], "sfm": e["sfm"], "detail": e["detail"],
|
||||
"rerun": rerun + e["file"]} for e in picked]
|
||||
|
||||
|
||||
_MATCHING = ("match", "accepted")
|
||||
|
||||
|
||||
def _verdicts(results_path: Path) -> tuple[dict[tuple[str, str], str], set[str], set[str]]:
|
||||
"""(file, field) -> verdict, every file in the run, and the files whose
|
||||
check failed outright (their field rows collapse to one "event" error)."""
|
||||
out, files, errored = {}, set(), set()
|
||||
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
ev = json.loads(line)
|
||||
files.add(ev["file"])
|
||||
for row in ev["results"]:
|
||||
out[(ev["file"], row[0])] = row[1]
|
||||
if row[0] == "event" and row[1] == "error":
|
||||
errored.add(ev["file"])
|
||||
return out, files, errored
|
||||
|
||||
|
||||
def compare_runs(prev_results: Path, cur_results: Path) -> dict:
|
||||
"""What changed between two runs, over the events both checked: per-field
|
||||
verdict counts before and after, every (event, field) that matched and no
|
||||
longer does -- including events that now fail outright -- and how many
|
||||
non-matches now match."""
|
||||
before, files_before, _ = _verdicts(prev_results)
|
||||
after, files_after, errored = _verdicts(cur_results)
|
||||
shared = files_before & files_after
|
||||
fields: dict[str, dict[str, list[int]]] = defaultdict(lambda: defaultdict(lambda: [0, 0]))
|
||||
for (f, field), v in before.items():
|
||||
if f in shared:
|
||||
fields[field][v][0] += 1
|
||||
for (f, field), v in after.items():
|
||||
if f in shared:
|
||||
fields[field][v][1] += 1
|
||||
regressions = []
|
||||
for (f, field), v in sorted(before.items()):
|
||||
if v not in _MATCHING or f not in shared:
|
||||
continue
|
||||
now = after.get((f, field), "error" if f in errored else "missing")
|
||||
if now not in _MATCHING:
|
||||
regressions.append({"file": f, "field": field, "before": v, "after": now})
|
||||
fixed = sum(1 for k, v in after.items()
|
||||
if k[0] in shared and v in _MATCHING and before.get(k) not in (None,) + _MATCHING)
|
||||
return {"fields": {f: dict(c) for f, c in fields.items()}, "regressions": regressions,
|
||||
"fixed": fixed, "shared_events": len(shared), "prev": str(prev_results),
|
||||
"prev_scope": _scope_of(Path(prev_results).parent)}
|
||||
|
||||
|
||||
def _scope_of(run_dir: Path) -> Optional[dict]:
|
||||
try:
|
||||
args = json.loads((run_dir / "run.json").read_text())["args"]
|
||||
except (OSError, KeyError, ValueError):
|
||||
return None
|
||||
return {k: args.get(k) for k in ("serial", "year", "type", "field", "sample", "seed") if args.get(k)}
|
||||
|
||||
|
||||
def write_changes(chg: dict, path: Path) -> None:
|
||||
regs = chg["regressions"]
|
||||
scope = chg.get("prev_scope")
|
||||
lines = [f"# Changes since {chg.get('prev', 'the previous run')}", "",
|
||||
f"Previous run's scope: {scope or 'all events'} · compared over "
|
||||
f"{chg.get('shared_events', '?')} events both runs checked", "",
|
||||
f"{len(regs)} regressions · {chg['fixed']} fixed", ""]
|
||||
if regs:
|
||||
lines += ["## Regressions (matched before, not now)", "", "| file | field | now |", "|---|---|---|"]
|
||||
lines += [f"| {r['file']} | {r['field']} | {r['after']} |" for r in regs[:500]]
|
||||
if len(regs) > 500:
|
||||
lines.append(f"| … {len(regs) - 500} more | | |")
|
||||
lines.append("")
|
||||
moved = {f: c for f, c in chg["fields"].items() if any(b != a for b, a in c.values())}
|
||||
if moved:
|
||||
lines += ["## Fields whose counts moved (before → after)", "",
|
||||
"| field | " + " | ".join(VERDICTS) + " |", "|---|" + "---|" * len(VERDICTS)]
|
||||
for f in sorted(moved):
|
||||
lines.append(f"| {f} | " + " | ".join(
|
||||
f"{moved[f].get(v, [0, 0])[0]} → {moved[f].get(v, [0, 0])[1]}" for v in VERDICTS) + " |")
|
||||
Path(path).write_text("\n".join(lines) + "\n")
|
||||
@@ -428,8 +428,7 @@ def main(argv=None) -> int:
|
||||
try:
|
||||
event_hdf5.write_event_hdf5(
|
||||
hdf5_path, ev,
|
||||
serial=serial,
|
||||
geo_range="normal",
|
||||
serial=serial, # range: the event's own, from its setup
|
||||
source_kind=source_kind,
|
||||
)
|
||||
hdf5_filename = hdf5_path.name
|
||||
|
||||
+6
-1
@@ -180,7 +180,7 @@ def write_event_hdf5(
|
||||
event: Event,
|
||||
*,
|
||||
serial: str,
|
||||
geo_range = "normal",
|
||||
geo_range = None,
|
||||
source_kind: str = "sfm-live",
|
||||
tool_version: Optional[str] = None,
|
||||
captured_at: Optional[datetime.datetime] = None,
|
||||
@@ -190,6 +190,9 @@ def write_event_hdf5(
|
||||
"""
|
||||
Persist a decoded Event as an HDF5 file with samples in physical units.
|
||||
|
||||
``geo_range`` left as None takes the event's own (``event.geo_range``,
|
||||
which a Blastware file's decode reads from its setup block), else Normal.
|
||||
|
||||
``geo_ips_per_count`` overrides the range-derived MiniMate count scale
|
||||
for sources whose counts differ — Thor IDF imports pass
|
||||
``micromate.idf_file._GEO_LSB_IPS`` (issue #42).
|
||||
@@ -202,6 +205,8 @@ def write_event_hdf5(
|
||||
pv = event.peak_values
|
||||
pi = event.project_info
|
||||
|
||||
if geo_range is None:
|
||||
geo_range = event.geo_range if getattr(event, "geo_range", None) is not None else "normal"
|
||||
geo_fs = _resolve_geo_full_scale(geo_range)
|
||||
geo_range_str = _normalise_range(geo_range)
|
||||
captured_at = captured_at or datetime.datetime.utcnow()
|
||||
|
||||
@@ -412,8 +412,7 @@ class WaveformStore:
|
||||
try:
|
||||
event_hdf5.write_event_hdf5(
|
||||
hdf5_path, ev,
|
||||
serial=serial,
|
||||
geo_range="normal", # BW file doesn't carry the range; assume Normal
|
||||
serial=serial, # range: the event's own, read from the file's setup
|
||||
source_kind="bw-import",
|
||||
)
|
||||
hdf5_filename = hdf5_path.name
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+3292
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+113
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE11529</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>M529L4XQ.R30H</FileName>
|
||||
<HistogramStartTime>14:54:39</HistogramStartTime>
|
||||
<HistogramStartDate>2025-07-02</HistogramStartDate>
|
||||
<HistogramStopTime>14:55:08</HistogramStopTime>
|
||||
<HistogramStopDate>2025-07-02</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.3 Volts</BatteryLevel>
|
||||
<Calibration>April 29, 2025 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Location>Test Loc</Location>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>2.430</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>0.940</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>1.900</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>13</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>>100</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>5.8</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>14:55:08</TranPeakTime>
|
||||
<TranPeakDate>2025-07-02</TranPeakDate>
|
||||
<VertPeakTime>14:55:08</VertPeakTime>
|
||||
<VertPeakDate>2025-07-02</VertPeakDate>
|
||||
<LongPeakTime>14:55:08</LongPeakTime>
|
||||
<LongPeakDate>2025-07-02</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>3.095</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>14:55:08</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2025-07-02</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>106.0</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>14:55:08</MicLTime>
|
||||
<MicLDate>2025-07-02</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>51</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.5 Hz.</TranTestFreq>
|
||||
<TranTestRatio>4.0</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.6 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.7</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.2 Hz.</LongTestFreq>
|
||||
<LongTestRatio>4.0</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Check</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2025-07-02 14:54:39 - 2025-07-02 14:55:08 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2025-07-02 14:55:08</Time>
|
||||
<Row>
|
||||
<Cell>2.430</Cell><Cell>13</Cell><Cell>0.940</Cell><Cell>>100</Cell><Cell>1.900</Cell><Cell>5.8</Cell><Cell>3.095</Cell><Cell>0.001</Cell><Cell>106.0</Cell><Cell>51</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+98
@@ -0,0 +1,98 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE16352</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>R352HFZ7.530H</FileName>
|
||||
<HistogramStartTime>21:17:27</HistogramStartTime>
|
||||
<HistogramStartDate>2018-06-04</HistogramStartDate>
|
||||
<HistogramStopTime>21:17:39</HistogramStopTime>
|
||||
<HistogramStopDate>2018-06-04</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.7 Volts</BatteryLevel>
|
||||
<Calibration>September 13, 2017 by Instantel</Calibration>
|
||||
<Units>in/s</Units>
|
||||
<Project>JV 241 - 1425 Spanlers Mill Rad</Project>
|
||||
<Client>Walsh Granite JV</Client>
|
||||
<UserName>Terra-Mechanics Inc- D. Harrison</UserName>
|
||||
<Seis.Loc>Loc #1 - 1425 Spanlers Mill Rd</Seis.Loc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.355</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>2.475</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>0.770</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>73</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>30</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>24</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>21:17:39</TranPeakTime>
|
||||
<TranPeakDate>2018-06-04</TranPeakDate>
|
||||
<VertPeakTime>21:17:39</VertPeakTime>
|
||||
<VertPeakDate>2018-06-04</VertPeakDate>
|
||||
<LongPeakTime>21:17:39</LongPeakTime>
|
||||
<LongPeakDate>2018-06-04</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>2.552</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>21:17:39</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2018-06-04</PeakVectorSumDate>
|
||||
<TranTestFreq>7.5 Hz.</TranTestFreq>
|
||||
<TranTestRatio>3.7</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.4 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.6</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.6 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.6</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2018-06-04 21:17:26 - 2018-06-04 21:17:39 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2018-06-04 21:17:39</Time>
|
||||
<Row>
|
||||
<Cell>0.355</Cell><Cell>73</Cell><Cell>2.475</Cell><Cell>30</Cell><Cell>0.770</Cell><Cell>24</Cell><Cell>2.552</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+3968
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+116
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE18004</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>T004JTRF.ME0H</FileName>
|
||||
<HistogramStartTime>12:49:26</HistogramStartTime>
|
||||
<HistogramStartDate>2022-12-28</HistogramStartDate>
|
||||
<HistogramStopTime>12:49:33</HistogramStopTime>
|
||||
<HistogramStopDate>2022-12-28</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.3 Volts</BatteryLevel>
|
||||
<Calibration>June 24, 2022 by Instantel</Calibration>
|
||||
<Units>in/s and psi(L)</Units>
|
||||
<Project>Robinson Run Bridge No 3-201 Marshall</Project>
|
||||
<Client>Mele & Mele & Sons, Inc.</Client>
|
||||
<UserName>Terra-Mechanics Inc. - D. Harrison</UserName>
|
||||
<SeisLoc>Location #1 - 201 Marshall Road</SeisLoc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.940</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>1.095</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>1.045</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>32</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>47</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>14</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>12:49:33</TranPeakTime>
|
||||
<TranPeakDate>2022-12-28</TranPeakDate>
|
||||
<VertPeakTime>12:49:33</VertPeakTime>
|
||||
<VertPeakDate>2022-12-28</VertPeakDate>
|
||||
<LongPeakTime>12:49:33</LongPeakTime>
|
||||
<LongPeakDate>2022-12-28</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>1.358</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>12:49:33</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2022-12-28</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>0.0</Value>
|
||||
<Units>psi(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>12:49:33</MicLTime>
|
||||
<MicLDate>2022-12-28</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>47</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.4 Hz.</TranTestFreq>
|
||||
<TranTestRatio>3.7</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.5 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.6</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.5 Hz.</LongTestFreq>
|
||||
<LongTestRatio>4.1</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Check</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2022-12-28 12:49:25 - 2022-12-28 12:49:33 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2022-12-28 12:49:33</Time>
|
||||
<Row>
|
||||
<Cell>0.940</Cell><Cell>32</Cell><Cell>1.095</Cell><Cell>47</Cell><Cell>1.045</Cell><Cell>14</Cell><Cell>1.358</Cell><Cell>0.001</Cell><Cell>104.9</Cell><Cell>47</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+3204
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+7049
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+3207
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+167
@@ -0,0 +1,167 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE11010</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>M010HR6K.OA0H</FileName>
|
||||
<HistogramStartTime>17:02:34</HistogramStartTime>
|
||||
<HistogramStartDate>2019-01-08</HistogramStartDate>
|
||||
<HistogramStopTime>17:20:00</HistogramStopTime>
|
||||
<HistogramStopDate>2019-01-08</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>18.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.8 Volts</BatteryLevel>
|
||||
<Calibration>December 17, 2018 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Project>Wampum Ave-ECMS 29301-215 Joseph St</Project>
|
||||
<Client>Brayman Construction</Client>
|
||||
<UserName>Terra-Mechanics Inc - D. Bartholomae</UserName>
|
||||
<Seis.Loc>Loc, #1 - 215 Joseph Street</Seis.Loc>
|
||||
<GeoRange>
|
||||
<Value>1.250</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.008</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>0.009</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>0.005</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>11</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>73</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>16</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>17:11:34</TranPeakTime>
|
||||
<TranPeakDate>2019-01-08</TranPeakDate>
|
||||
<VertPeakTime>17:03:34</VertPeakTime>
|
||||
<VertPeakDate>2019-01-08</VertPeakDate>
|
||||
<LongPeakTime>17:11:34</LongPeakTime>
|
||||
<LongPeakDate>2019-01-08</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>0.009</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>17:11:34</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2019-01-08</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>134.1</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>17:03:34</MicLTime>
|
||||
<MicLDate>2019-01-08</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>9.7</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.2 Hz.</TranTestFreq>
|
||||
<TranTestRatio>4.3</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.6 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.4</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.2 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.8</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>20.1 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>583 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Passed</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2019-01-08 17:02:33 - 2019-01-08 17:20:00 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2019-01-08 17:03:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>47</Cell><Cell>0.009</Cell><Cell>73</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.009</Cell><Cell>0.015</Cell><Cell>134.1</Cell><Cell>9.7</Cell></Row>
|
||||
<Time>2019-01-08 17:04:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>21</Cell><Cell>0.007</Cell><Cell>27</Cell><Cell>0.002</Cell><Cell>85</Cell><Cell>0.007</Cell><Cell>0.000</Cell><Cell>87.96</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2019-01-08 17:05:34</Time>
|
||||
<Row>
|
||||
<Cell>0.004</Cell><Cell>20</Cell><Cell>0.004</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>0.003</Cell><Cell>119.1</Cell><Cell>7.5</Cell></Row>
|
||||
<Time>2019-01-08 17:06:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>34</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>51</Cell><Cell>0.003</Cell><Cell>0.000</Cell><Cell>81.94</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2019-01-08 17:07:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>51</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.003</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>39</Cell></Row>
|
||||
<Time>2019-01-08 17:08:34</Time>
|
||||
<Row>
|
||||
<Cell>0.004</Cell><Cell>12</Cell><Cell>0.004</Cell><Cell>16</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.005</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>13</Cell></Row>
|
||||
<Time>2019-01-08 17:09:34</Time>
|
||||
<Row>
|
||||
<Cell>0.002</Cell><Cell>51</Cell><Cell>0.002</Cell><Cell>64</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.003</Cell><Cell>0.000</Cell><Cell>81.94</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2019-01-08 17:10:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>12</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.004</Cell><Cell>0.000</Cell><Cell>81.94</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2019-01-08 17:11:34</Time>
|
||||
<Row>
|
||||
<Cell>0.008</Cell><Cell>11</Cell><Cell>0.005</Cell><Cell>13</Cell><Cell>0.005</Cell><Cell>16</Cell><Cell>0.009</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>19</Cell></Row>
|
||||
<Time>2019-01-08 17:12:34</Time>
|
||||
<Row>
|
||||
<Cell>0.006</Cell><Cell>13</Cell><Cell>0.004</Cell><Cell>14</Cell><Cell>0.004</Cell><Cell>51</Cell><Cell>0.007</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>20</Cell></Row>
|
||||
<Time>2019-01-08 17:13:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>57</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.003</Cell><Cell>0.000</Cell><Cell>87.96</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2019-01-08 17:14:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>47</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.003</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>13</Cell></Row>
|
||||
<Time>2019-01-08 17:15:34</Time>
|
||||
<Row>
|
||||
<Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.004</Cell><Cell>0.000</Cell><Cell>95.92</Cell><Cell>2.5</Cell></Row>
|
||||
<Time>2019-01-08 17:16:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>13</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>85</Cell><Cell>0.004</Cell><Cell>0.000</Cell><Cell>93.98</Cell><Cell>9.1</Cell></Row>
|
||||
<Time>2019-01-08 17:17:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>17</Cell><Cell>0.002</Cell><Cell>85</Cell><Cell>0.002</Cell><Cell>73</Cell><Cell>0.003</Cell><Cell>0.000</Cell><Cell>81.94</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2019-01-08 17:18:34</Time>
|
||||
<Row>
|
||||
<Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.004</Cell><Cell>0.000</Cell><Cell>87.96</Cell><Cell>>100</Cell></Row>
|
||||
<Time>2019-01-08 17:19:34</Time>
|
||||
<Row>
|
||||
<Cell>0.003</Cell><Cell>73</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.003</Cell><Cell>20</Cell><Cell>0.004</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>6.1</Cell></Row>
|
||||
<Time>2019-01-08 17:20:00</Time>
|
||||
<Row>
|
||||
<Cell>0.002</Cell><Cell>37</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.002</Cell><Cell>>100</Cell><Cell>0.003</Cell><Cell>0.000</Cell><Cell>91.48</Cell><Cell>18</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
@@ -0,0 +1,278 @@
|
||||
"""
|
||||
Setup and note fields read from a Blastware event file alone (#44, #45).
|
||||
|
||||
Every expected value below comes from Blastware's own output for the same
|
||||
file -- its ASCII report or its `_XML.XML` event report -- or, for the bench
|
||||
file with neither, from the record length and the MiniMate Plus spec, as
|
||||
written up in #44/#45. None is derived from the decoder under test.
|
||||
|
||||
The STRT record's bytes are not these fields: STRT[18] is the record-type
|
||||
marker (0x46 waveform, 0x0A histogram), which is why every waveform used to
|
||||
read "70 s".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from minimateplus.event_file_io import read_blastware_file
|
||||
|
||||
_FIX = Path(__file__).resolve().parent / "fixtures"
|
||||
|
||||
# (file, sample rate, record time s, pre-trigger samples, total samples)
|
||||
_WAVEFORMS = [
|
||||
# ASCII report: 1024 sps, 3.0 s, -0.25 s; 3328 samples per channel.
|
||||
("5-11-26/M529LL1A.SP0", 1024, 3.0, 256, 3328),
|
||||
# ASCII report: 1024 sps, 1.0 s, -0.25 s.
|
||||
("decode-re-5-8-26/event-c/M529LK44.AB0", 1024, 1.0, 256, 1280),
|
||||
# #44/#45: BE9441 bench at 4096 sps, 5 s, 0.25 s -> 21,504 samples.
|
||||
("minimate-bench-10-26-26-blastware/blastware/K441LTOF.ZI0", 4096, 5.0, 1024, 21504),
|
||||
# XML: setup "BE16352.set", 1024 sps, 1.0 s, -0.247 s, 1277 sample rows.
|
||||
("bw-import-fields-10-29-26/R352HIUI.F40W", 1024, 1.0, 253, 1277),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,sr,rt,pretrig,total", _WAVEFORMS)
|
||||
def test_waveform_setup_fields_come_from_the_file(rel, sr, rt, pretrig, total):
|
||||
ev = read_blastware_file(_FIX / rel)
|
||||
assert ev.sample_rate == sr
|
||||
assert ev.rectime_seconds == pytest.approx(rt)
|
||||
assert ev.pretrig_samples == pretrig
|
||||
assert ev.total_samples == total
|
||||
|
||||
|
||||
# (file, sample rate) -- ASCII report / XML
|
||||
_HISTOGRAMS = [
|
||||
("histogram-mic-off-10-26-26/K441LTOK.QZ0", 2048),
|
||||
("ts-fix/K441LKZU.C30H", 1024),
|
||||
("bw-import-fields-10-29-26/M529L4XQ.R30H", 1024),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,sr", _HISTOGRAMS)
|
||||
def test_histogram_sample_rate_comes_from_the_file(rel, sr):
|
||||
ev = read_blastware_file(_FIX / rel)
|
||||
assert ev.sample_rate == sr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,sr", _HISTOGRAMS)
|
||||
def test_histogram_has_no_record_time_or_pretrigger(rel, sr):
|
||||
# Blastware reports neither for a histogram; the STRT record-type byte
|
||||
# (0x0A = 10) is not a record time.
|
||||
ev = read_blastware_file(_FIX / rel)
|
||||
assert ev.rectime_seconds is None
|
||||
assert ev.pretrig_samples is None
|
||||
|
||||
|
||||
# (file, setup name, project, client, operator, sensor location)
|
||||
_NOTES = [
|
||||
# ASCII report; default labels, location spelled "Seis Loc:".
|
||||
("5-11-26/M529LL1A.SP0", "Standard Recording Setup",
|
||||
"Test-5-8-26", "New Client", "Terra-Mechanics - Harrison", "Still Catbed."),
|
||||
# ASCII report; location spelled "Seis. Loc:". BE9441's bench setup is
|
||||
# saved as "Standard Recording Setup.set" (#45).
|
||||
("histogram-mic-off-10-26-26/K441LTOK.QZ0", "Standard Recording Setup.set",
|
||||
"TestUnit-Minimate", "Terra-Mechanics", "Terra-Mechanics Inc. - Harrison", "Test unit 1"),
|
||||
# XML; a setup not named "Standard Recording Setup".
|
||||
("bw-import-fields-10-29-26/R352HIUI.F40W", "BE16352.set",
|
||||
"JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV",
|
||||
"Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"),
|
||||
# XML (<Location>Test Loc</Location> only); the operator relabelled the
|
||||
# four note slots "Location:", "Client:", "User Name:", "General:" and
|
||||
# filled in only the first. Slots are positional, as in the ASCII parser.
|
||||
("bw-import-fields-10-29-26/M529L4XQ.R30H", "Standard Recording Setup",
|
||||
"Test Loc", None, None, None),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,setup,project,client,operator,location", _NOTES)
|
||||
def test_notes_come_from_the_file_by_position(rel, setup, project, client, operator, location):
|
||||
pi = read_blastware_file(_FIX / rel).project_info
|
||||
assert pi.setup_name == setup
|
||||
assert pi.project == project
|
||||
assert pi.client == client
|
||||
assert pi.operator == operator
|
||||
assert pi.sensor_location == location
|
||||
|
||||
|
||||
def test_import_without_a_report_stores_the_file_fields(tmp_path: Path):
|
||||
"""The watcher path with no ASCII report: the sidecar carries what the
|
||||
file holds, not blanks and not the STRT bytes."""
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
src = _FIX / "bw-import-fields-10-29-26/R352HIUI.F40W"
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
store.save_imported_bw(src.read_bytes(), source_path=src)
|
||||
|
||||
sc = store.load_sidecar("BE16352", src.name)
|
||||
assert sc["event"]["sample_rate"] == 1024
|
||||
assert sc["event"]["rectime_seconds"] == pytest.approx(1.0)
|
||||
assert sc["event"]["pretrig_samples"] == 253
|
||||
assert sc["project_info"]["project"] == "JV 241 - 1425 Spanlers Mill Rad"
|
||||
assert sc["project_info"]["sensor_location"] == "Loc #1 - 1425 Spanlers Mill Rd"
|
||||
|
||||
|
||||
# ── #41: the record type comes from the bytes ───────────────────────────────
|
||||
# STRT[18] is the record-type byte: 0x46 on every one of DL2's 6,577 waveform
|
||||
# files, 0x0A on every one of its 63,535 histograms (measured 2026-10-29).
|
||||
|
||||
from minimateplus import blastware_file as _bw # noqa: E402
|
||||
from minimateplus.event_file_io import decode_blastware_bytes # noqa: E402
|
||||
|
||||
_TYPES = [
|
||||
("bw-import-fields-10-29-26/R352HIUI.F40W", "Waveform"),
|
||||
("bw-import-fields-10-29-26/M529L4XQ.R30H", "Histogram"),
|
||||
("5-11-26/M529LL1A.SP0", "Waveform"), # name carries no type
|
||||
("histogram-mic-off-10-26-26/K441LTOK.QZ0", "Histogram"), # name carries no type
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,want", _TYPES)
|
||||
def test_record_type_comes_from_the_bytes_without_a_name(rel, want):
|
||||
assert decode_blastware_bytes((_FIX / rel).read_bytes(), name=None).record_type == want
|
||||
|
||||
|
||||
def test_the_bytes_win_over_a_filename_that_disagrees(caplog):
|
||||
raw = (_FIX / "bw-import-fields-10-29-26/M529L4XQ.R30H").read_bytes()
|
||||
ev = decode_blastware_bytes(raw, name="M529L4XQ.R30W")
|
||||
assert ev.record_type == "Histogram"
|
||||
assert "record type" in caplog.text
|
||||
|
||||
|
||||
def test_an_unknown_type_byte_is_unknown_not_a_guess():
|
||||
raw = bytearray((_FIX / "bw-import-fields-10-29-26/R352HIUI.F40W").read_bytes())
|
||||
raw[_bw._WAVEFORM_HEADER_SIZE + 18] = 0x99
|
||||
ev = decode_blastware_bytes(bytes(raw), name=None)
|
||||
assert ev.record_type is None
|
||||
assert any("record type" in p for p in ev.decode_problems)
|
||||
|
||||
|
||||
# ── A histogram's peak vector sum is read, not computed from channel peaks ──
|
||||
# Each interval stores the square of its vector sum (uint32 BE, in 0.005 in/s
|
||||
# units): bytes [21:25] of a standard block, the last 4 bytes of a sub-minute
|
||||
# record. sqrt(stored) x 0.005 matches Blastware's printed interval PVS on
|
||||
# 1,668,073 / 1,668,074 standard and 34.5 M sub-minute DL2 intervals
|
||||
# (measured 2026-10-30). The old value combined each channel's interval peak,
|
||||
# which can come from different moments, and read high on 86% of histograms.
|
||||
|
||||
from minimateplus.histogram_codec import interval_pvs # noqa: E402
|
||||
|
||||
# (file, Blastware's summary Peak Vector Sum)
|
||||
_HIST_PVS = [
|
||||
("decode-checker-10-29-26/M529L4XQ.R30H", 3.095), # XML; 1-minute
|
||||
("decode-checker-10-29-26/T004JTRF.ME0H", 1.358), # XML; SFM used to say 1.782
|
||||
("histogram-mic-off-10-26-26/K441LTOK.QZ0", 1.083), # ASCII report; 2 s, mic off
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,pvs", _HIST_PVS)
|
||||
def test_histogram_peak_vector_sum_is_the_stored_one(rel, pvs):
|
||||
got = read_blastware_file(_FIX / rel).peak_values.peak_vector_sum
|
||||
assert abs(got - pvs) <= 0.0005 + 1e-9, got
|
||||
|
||||
|
||||
def test_interval_pvs_per_interval():
|
||||
raw = (_FIX / "histogram-mic-off-10-26-26/K441LTOK.QZ0").read_bytes()
|
||||
pvs = interval_pvs(raw[_bw._WAVEFORM_HEADER_SIZE + 21:])
|
||||
assert len(pvs) == 22
|
||||
# Blastware's interval table, first four "Geo PVS" values
|
||||
for got, want in zip(pvs[:4], (0.065, 0.034, 0.015, 0.461)):
|
||||
assert abs(got * 0.005 - want) <= 0.0005 + 1e-9, (got, want)
|
||||
|
||||
|
||||
# ── The mic: one count = 0.25 Pa ────────────────────────────────────────────
|
||||
# Measured 2026-10-31 against 1,729,253 DL2 histogram intervals' "MicL Peak"
|
||||
# columns: count x 0.25 Pa matches Blastware's psi(L) on every one, and
|
||||
# 20 log10(count x 0.25 Pa / 20 uPa) its dB(L) on all but 17 exact half-way
|
||||
# cases. The old psi factor (a "~0.5 psi full-scale" guess) was ~95x small.
|
||||
|
||||
from minimateplus.waveform_codec import mic_count_to_db # noqa: E402
|
||||
|
||||
|
||||
@pytest.mark.parametrize("count,printed", [
|
||||
(1, "81.94"), # XML sample cell
|
||||
(119, "123.4"), # Blastware interval tables, where 81.94 + 20 log10 gave 123.451
|
||||
(132, "124.3"), # ... and 124.351
|
||||
(129, "124.2"), # 162 intervals; exactly 0.25 Pa gives 124.149997, a hair under half-way
|
||||
(813, "140.14"), # V70 fixture, Blastware display
|
||||
])
|
||||
def test_mic_db_matches_blastware(count, printed):
|
||||
d = len(printed.split(".")[1])
|
||||
assert abs(mic_count_to_db(count) - float(printed)) <= 0.5 * 10 ** -d + 1e-9
|
||||
|
||||
|
||||
def test_mic_peak_in_psi():
|
||||
# Blastware: MicL PSPL 106.0 dB(L) = 20 uPa x 10^(106/20) = 3.990 Pa = 5.787e-4 psi.
|
||||
ev = read_blastware_file(_FIX / "decode-checker-10-29-26/M529L4XQ.R30H")
|
||||
assert ev.peak_values.micl == pytest.approx(5.787e-4, rel=0.01)
|
||||
|
||||
|
||||
# ── The geophone range: Normal or Sensitive ─────────────────────────────────
|
||||
# In the setup's channel blocks, the byte 29 after each geophone label is the
|
||||
# range: 0x00 Normal (10 in/s full scale), 0x01 Sensitive (1.25 in/s). It
|
||||
# matches Blastware's GeoRange on 70,042 / 70,042 DL2 events, all three
|
||||
# channels agreeing on every one (35 Sensitive), measured 2026-11-01. Until
|
||||
# now SFM assumed Normal, so a Sensitive event read 8x high.
|
||||
|
||||
from minimateplus.event_file_io import _setup_name_at # noqa: E402
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rel,want", [
|
||||
("bw-import-fields-10-29-26/R352HIUI.F40W", 0),
|
||||
("geo-range-11-01-26/K557J1KB.RQ0W", 1), # waveform, XML GeoRange 1.250
|
||||
("geo-range-11-01-26/M010HR6K.OA0H", 1), # histogram, XML GeoRange 1.250
|
||||
])
|
||||
def test_geo_range_comes_from_the_file(rel, want):
|
||||
assert read_blastware_file(_FIX / rel).geo_range == want
|
||||
|
||||
|
||||
# (file, Blastware's Tran / Vert / Long PPV and Peak Vector Sum, from its XML)
|
||||
@pytest.mark.parametrize("rel,peaks", [
|
||||
("geo-range-11-01-26/K557J1KB.RQ0W", ("0.019", "0.055", "0.019", "0.061")),
|
||||
("geo-range-11-01-26/M010HR6K.OA0H", ("0.008", "0.009", "0.005", "0.009")),
|
||||
])
|
||||
def test_sensitive_range_peaks_are_not_8x(rel, peaks):
|
||||
pv = read_blastware_file(_FIX / rel).peak_values
|
||||
for got, want in zip((pv.tran, pv.vert, pv.long, pv.peak_vector_sum), peaks):
|
||||
assert abs(got - float(want)) <= 0.0005 + 1e-9, (got, want)
|
||||
|
||||
|
||||
def test_channels_that_disagree_give_no_range_and_a_problem():
|
||||
raw = bytearray((_FIX / "geo-range-11-01-26/K557J1KB.RQ0W").read_bytes())
|
||||
i = raw.find(b"\x00\x00\x01Vert", _setup_name_at(bytes(raw)))
|
||||
raw[i + 3 + 29] = 0x00 # Vert Normal, Tran / Long Sensitive
|
||||
ev = decode_blastware_bytes(bytes(raw), name=None)
|
||||
assert ev.geo_range is None
|
||||
assert any("range" in p for p in ev.decode_problems)
|
||||
|
||||
|
||||
def test_the_h5_takes_the_events_range(tmp_path):
|
||||
import h5py
|
||||
from sfm import event_hdf5
|
||||
ev = read_blastware_file(_FIX / "geo-range-11-01-26/K557J1KB.RQ0W")
|
||||
event_hdf5.write_event_hdf5(tmp_path / "e.h5", ev, serial="BE9557")
|
||||
with h5py.File(tmp_path / "e.h5", "r") as f:
|
||||
assert f.attrs["geo_range"] == "sensitive"
|
||||
assert abs(float(abs(f["samples/Vert"][:]).max()) - 0.055) <= 0.0005 + 1e-9
|
||||
|
||||
|
||||
def test_an_imported_file_and_the_backfill_store_its_range(tmp_path):
|
||||
import h5py
|
||||
import scripts.backfill_sidecars as backfill
|
||||
from sfm import event_hdf5
|
||||
from sfm.waveform_store import WaveformStore
|
||||
|
||||
src = _FIX / "geo-range-11-01-26/K557J1KB.RQ0W"
|
||||
store = WaveformStore(tmp_path / "waveforms")
|
||||
ev, _ = store.save_imported_bw(src.read_bytes(), source_path=src)
|
||||
h5 = store.hdf5_path_for("BE9557", src.name)
|
||||
with h5py.File(h5, "r") as f:
|
||||
assert f.attrs["geo_range"] == "sensitive"
|
||||
|
||||
# A file stored before this fix carries "normal"; the backfill rewrites it.
|
||||
event_hdf5.write_event_hdf5(h5, ev, serial="BE9557", geo_range="normal")
|
||||
assert backfill.main(["--store-root", str(tmp_path / "waveforms"),
|
||||
"--db-path", str(tmp_path / "seismo_relay.db"), "--force"]) == 0
|
||||
with h5py.File(h5, "r") as f:
|
||||
assert f.attrs["geo_range"] == "sensitive"
|
||||
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
Blastware's `_XML.XML` event report, parsed (decode checker, Task 1).
|
||||
|
||||
Expected values are copied from the fixture XML files themselves.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from minimateplus.bw_xml_report import parse_xml_report, parse_xml_report_file
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
|
||||
|
||||
|
||||
def test_scalars_units_and_special_text():
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert r.scalars["SampleRate"] == "1024 sps"
|
||||
assert r.scalars["RecordTime"] == "1.0 sec."
|
||||
assert r.scalars["TranPPV"] == "0.005" and r.units["TranPPV"] == "in/s"
|
||||
assert r.scalars["VertZCFreq"] == ">100" # entity unescaped
|
||||
assert r.scalars["TranZCFreq"] == "N/A"
|
||||
assert r.scalars["TranTestResults"] == "Check"
|
||||
assert r.scalars["BatteryLevel"] == "6.7 Volts"
|
||||
assert r.job_number == "1" and r.notes == []
|
||||
assert r.channels == ["Tran", "Vert", "Long", "MicL"]
|
||||
|
||||
|
||||
def test_waveform_sample_rows():
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert len(r.sample_rows) == 1024
|
||||
assert r.sample_rows[0] == ["-0.005", "0.000", "0.000", "81.94"]
|
||||
assert r.intervals is None
|
||||
|
||||
|
||||
def test_ragged_rows_are_kept_as_printed():
|
||||
r = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML")
|
||||
assert len(r.sample_rows) == 2304
|
||||
assert r.sample_rows[-4] == ["-0.185", "0.235", "-0.255", "-87.96"]
|
||||
assert r.sample_rows[-1] == ["-0.245"] # only Long still running
|
||||
|
||||
|
||||
def test_relabelled_notes_keep_their_tags_in_order():
|
||||
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
|
||||
assert r.notes == [("Location", "Test Loc")]
|
||||
r = parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML")
|
||||
assert r.notes[1] == ("Client", "Mele & Mele & Sons, Inc.")
|
||||
assert r.event_units == "in/s and psi(L)"
|
||||
|
||||
|
||||
def test_notes_and_job_number_are_not_scalars():
|
||||
r = parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML")
|
||||
assert "Project" not in r.scalars and "SeisLoc" not in r.scalars
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert "JobNumber" not in r.scalars
|
||||
|
||||
|
||||
def test_histogram_intervals_and_columns():
|
||||
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
|
||||
assert r.interval_columns[0] == "Tran Peak in/s" and len(r.interval_columns) == 10
|
||||
assert r.intervals == [("2025-07-02 14:55:08",
|
||||
["2.430", "13", "0.940", ">100", "1.900", "5.8", "3.095", "0.001", "106.0", "51"])]
|
||||
assert r.sample_rows is None
|
||||
|
||||
|
||||
def test_no_mic_histogram_has_seven_columns():
|
||||
r = parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML")
|
||||
assert r.event_units == "in/s"
|
||||
assert r.channels == ["Tran", "Vert", "Long"]
|
||||
assert len(r.interval_columns) == 7 and len(r.intervals[0][1]) == 7
|
||||
|
||||
|
||||
def test_oorange_and_range_values():
|
||||
r = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML")
|
||||
assert r.scalars["TranPPV"] == "OORANGE"
|
||||
assert r.scalars["GeoRange"] == "1.250" and r.units["GeoRange"] == "in/s"
|
||||
|
||||
|
||||
def test_truncated_xml_raises_valueerror():
|
||||
data = (FIX / "M529L4XQ_R30H_XML.XML").read_bytes()
|
||||
with pytest.raises(ValueError):
|
||||
parse_xml_report(data[: len(data) // 2])
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
The decode checker's runner and reports (decode checker, Tasks 5-7).
|
||||
|
||||
Runs on the fixture folder, which holds the binaries and their XML reports
|
||||
side by side.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
run = importlib.import_module("scratch.check_s3_decode")
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
|
||||
|
||||
|
||||
def test_find_pairs_dedupes_and_pairs(tmp_path):
|
||||
(tmp_path / "Sent").mkdir()
|
||||
for n in ("R352HIUI.F40W", "Sent/R352HIUI.F40W", "UM11719_20240404193109.IDFH"):
|
||||
(tmp_path / n).write_bytes(b"x")
|
||||
pairs = run.find_pairs(tmp_path, FIX)
|
||||
assert [p[0] for p in pairs] == ["R352HIUI.F40W"]
|
||||
assert pairs[0][2].name == "R352HIUI_F40W_XML.XML"
|
||||
|
||||
|
||||
def test_check_event_rows_and_attrs():
|
||||
out = run.check_event("M007HVWF.K30W", str(FIX / "M007HVWF.K30W"), str(FIX / "M007HVWF_K30W_XML.XML"))
|
||||
assert out["attrs"]["range"] == "1.250" and out["attrs"]["model"] == "MiniMate Plus"
|
||||
# clipped at its own 1.250 ceiling: accepted under the saturation carve-out
|
||||
assert ["TranPPV", "accepted"] in [r[:2] for r in out["results"]]
|
||||
|
||||
|
||||
def test_bad_input_is_one_error_row(tmp_path):
|
||||
bad = tmp_path / "R352HIUI.F40W"
|
||||
bad.write_bytes(b"not a blastware file")
|
||||
out = run.check_event(bad.name, str(bad), str(FIX / "R352HIUI_F40W_XML.XML"))
|
||||
assert out["results"] == [["event", "error", None, None, out["results"][0][4], None]]
|
||||
|
||||
|
||||
def test_missing_reference_is_one_no_reference_row():
|
||||
out = run.check_event("R352HIUI.F40W", str(FIX / "R352HIUI.F40W"), None)
|
||||
assert [r[:2] for r in out["results"]] == [["event", "no_reference"]]
|
||||
|
||||
|
||||
def test_cli_writes_results(tmp_path):
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1"]) == 0
|
||||
lines = gzip.open(tmp_path / "run/results.jsonl.gz", "rt").read().splitlines()
|
||||
assert len(lines) == 7
|
||||
assert json.loads((tmp_path / "run/run.json").read_text())["events"] == 7
|
||||
|
||||
|
||||
def test_field_filter_keeps_only_matching_rows(tmp_path):
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1",
|
||||
"--field", "samples."]) == 0
|
||||
for line in gzip.open(tmp_path / "run/results.jsonl.gz", "rt"):
|
||||
assert all(r[0].startswith("samples.") for r in json.loads(line)["results"])
|
||||
|
||||
|
||||
# ── Task 6: summary and detailed report ─────────────────────────────────────
|
||||
|
||||
report = importlib.import_module("scratch.decode_check_report")
|
||||
|
||||
|
||||
def _write_results(path, events):
|
||||
with gzip.open(path, "wt") as fh:
|
||||
for ev in events:
|
||||
fh.write(json.dumps(ev) + "\n")
|
||||
|
||||
|
||||
def _ev(name, sr, verdict):
|
||||
return {"file": name, "attrs": {"sample_rate": sr, "year": "2024"},
|
||||
"results": [["SampleRate", verdict, sr + " sps", "1024", "", None]]}
|
||||
|
||||
|
||||
def test_details_group_failures_by_what_they_share(tmp_path):
|
||||
res = tmp_path / "results.jsonl.gz"
|
||||
_write_results(res, [_ev("A.W", "2048", "mismatch"), _ev("B.W", "2048", "mismatch"),
|
||||
_ev("C.W", "1024", "match")])
|
||||
agg = report.aggregate(res)
|
||||
report.write_details(agg, tmp_path / "details.json")
|
||||
d = json.loads((tmp_path / "details.json").read_text())["SampleRate|mismatch"]
|
||||
assert d["total"] == 2
|
||||
assert d["groups"]["sample_rate"] == [
|
||||
{"value": "2048", "failing": 2, "compared": 2, "rate": 1.0, "concentrated": True}]
|
||||
assert d["examples"] and all("--file" in e["rerun"] for e in d["examples"])
|
||||
|
||||
|
||||
def test_summary_counts_fields_fully_matching(tmp_path):
|
||||
res = tmp_path / "results.jsonl.gz"
|
||||
_write_results(res, [_ev("A.W", "2048", "mismatch"), _ev("C.W", "1024", "match")])
|
||||
report.write_summary(report.aggregate(res), tmp_path / "summary.md")
|
||||
text = (tmp_path / "summary.md").read_text()
|
||||
assert "0 of 1 fields fully matching" in text and "| SampleRate |" in text
|
||||
|
||||
|
||||
def test_a_run_writes_both_reports(tmp_path):
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1"]) == 0
|
||||
assert (tmp_path / "run/summary.md").exists() and (tmp_path / "run/details.json").exists()
|
||||
|
||||
|
||||
# ── Task 7: run-to-run changes and the one-event view ───────────────────────
|
||||
|
||||
def _one(name, field, verdict):
|
||||
return {"file": name, "attrs": {}, "results": [[field, verdict, "x", "y", "", None]]}
|
||||
|
||||
|
||||
def test_compare_runs_finds_regressions_and_fixes(tmp_path):
|
||||
prev, cur = tmp_path / "prev.jsonl.gz", tmp_path / "cur.jsonl.gz"
|
||||
_write_results(prev, [_one("A.W", "SampleRate", "match"), _one("B.W", "notes", "sfm_blank")])
|
||||
_write_results(cur, [_one("A.W", "SampleRate", "mismatch"), _one("B.W", "notes", "match")])
|
||||
chg = report.compare_runs(prev, cur)
|
||||
assert chg["regressions"] == [{"file": "A.W", "field": "SampleRate",
|
||||
"before": "match", "after": "mismatch"}]
|
||||
assert chg["fixed"] == 1
|
||||
report.write_changes(chg, tmp_path / "changes.md")
|
||||
assert "A.W" in (tmp_path / "changes.md").read_text()
|
||||
|
||||
|
||||
def test_compare_to_marks_the_summary(tmp_path):
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "a"), "--jobs", "1"]) == 0
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "b"), "--jobs", "1",
|
||||
"--compare-to", str(tmp_path / "a")]) == 0
|
||||
assert "**0 regressions**" in (tmp_path / "b/summary.md").read_text()
|
||||
assert (tmp_path / "b/changes.md").exists()
|
||||
|
||||
|
||||
def test_file_prints_one_event(tmp_path, capsys):
|
||||
assert run.main([str(FIX), str(FIX), "--file", "M007HVWF.K30W"]) == 0
|
||||
out = capsys.readouterr().out
|
||||
assert any("TranPPV" in line and "accepted" in line for line in out.splitlines())
|
||||
|
||||
|
||||
# ── Final review fixes ──────────────────────────────────────────────────────
|
||||
|
||||
def test_a_matching_event_that_now_errors_is_a_regression(tmp_path):
|
||||
prev, cur = tmp_path / "prev.jsonl.gz", tmp_path / "cur.jsonl.gz"
|
||||
_write_results(prev, [_one("A.W", "SampleRate", "match"), _one("B.W", "notes", "match")])
|
||||
_write_results(cur, [_one("A.W", "event", "error"), _one("B.W", "notes", "match")])
|
||||
chg = report.compare_runs(prev, cur)
|
||||
assert chg["regressions"] == [{"file": "A.W", "field": "SampleRate",
|
||||
"before": "match", "after": "error"}]
|
||||
|
||||
|
||||
def test_counts_moved_cover_only_shared_events(tmp_path):
|
||||
prev, cur = tmp_path / "prev.jsonl.gz", tmp_path / "cur.jsonl.gz"
|
||||
_write_results(prev, [_one("A.W", "SampleRate", "match")])
|
||||
_write_results(cur, [_one("A.W", "SampleRate", "match"), _one("B.W", "SampleRate", "match")])
|
||||
assert report.compare_runs(prev, cur)["fields"]["SampleRate"]["match"] == [1, 1]
|
||||
|
||||
|
||||
def test_default_comparison_is_the_newest_completed_run_of_the_same_scope(tmp_path, monkeypatch):
|
||||
runs = tmp_path / "runs"
|
||||
monkeypatch.setattr(run, "RUNS_DIR", runs)
|
||||
base = [str(FIX), str(FIX), "--jobs", "1"]
|
||||
assert run.main(base + ["--out", str(runs / "20990101-000001")]) == 0 # same scope
|
||||
assert run.main(base + ["--out", str(runs / "20990101-000002"), "--type", "W"]) == 0 # narrower
|
||||
(runs / "20990101-000003").mkdir() # never finished
|
||||
assert run.main(base + ["--out", str(runs / "20990101-000004")]) == 0
|
||||
assert "20990101-000001" in (runs / "20990101-000004/changes.md").read_text().splitlines()[0]
|
||||
|
||||
|
||||
def test_fields_fully_matching_need_a_match_and_skip_the_event_row(tmp_path):
|
||||
res = tmp_path / "results.jsonl.gz"
|
||||
_write_results(res, [
|
||||
{"file": "A.W", "attrs": {}, "results": [["SampleRate", "match", "1", "1", "", None],
|
||||
["UsbSummaryChannels", "no_reference", "", None, "", None]]},
|
||||
{"file": "B.W", "attrs": {}, "results": [["event", "no_reference", None, None, "no XML report", None]]},
|
||||
])
|
||||
report.write_summary(report.aggregate(res), tmp_path / "summary.md")
|
||||
text = (tmp_path / "summary.md").read_text()
|
||||
assert "1 of 2 fields fully matching" in text
|
||||
assert "1 event without a report" in text and "| event |" not in text
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
The decode checker's SFM side and comparison (decode checker, Tasks 2-4).
|
||||
|
||||
Expected values come from the fixtures' Blastware XML reports. SFM's side is
|
||||
built from the event bytes alone -- no filename, no report.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from minimateplus.decode_check import sfm_side
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
|
||||
|
||||
|
||||
def test_waveform_side_from_bytes():
|
||||
s = sfm_side((FIX / "R352HIUI.F40W").read_bytes())
|
||||
assert s.values["SampleRate"] == 1024 and s.values["RecordTime"] == pytest.approx(1.0)
|
||||
assert s.values["Pre-triggerLength"] == pytest.approx(-253 / 1024)
|
||||
assert (s.values["EventDate"], s.values["EventTime"]) == ("2018-07-30", "16:13:52")
|
||||
assert s.notes == ["JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV",
|
||||
"Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"]
|
||||
assert len(s.counts["Tran"]) == 1277 and s.job_number is None
|
||||
|
||||
|
||||
def test_histogram_interval_peak_in_counts():
|
||||
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
|
||||
# Blastware: Tran interval peak 2.430 in/s = 7776 counts at 10/32000 in/s per count
|
||||
assert s.counts["Tran"] == [7776] and s.values["NumberofIntervals"] == 1
|
||||
|
||||
|
||||
def test_event_type_comes_from_the_bytes():
|
||||
# No filename reaches the decoder; the type is the STRT record-type byte (#41).
|
||||
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
|
||||
assert s.values["EventType"] == "Full Histogram"
|
||||
|
||||
|
||||
def test_report_fields_stay_blank():
|
||||
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
|
||||
for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"):
|
||||
assert s.values.get(tag) is None
|
||||
|
||||
|
||||
# ── Task 3: the comparison ──────────────────────────────────────────────────
|
||||
|
||||
from minimateplus.bw_xml_report import parse_xml_report_file # noqa: E402
|
||||
from minimateplus.decode_check import compare, matches_printed # noqa: E402
|
||||
|
||||
|
||||
def _results(stem, carveouts=()):
|
||||
raw = (FIX / stem).read_bytes()
|
||||
ref = parse_xml_report_file(FIX / (stem.replace(".", "_") + "_XML.XML"))
|
||||
return {r.field: r for r in compare(sfm_side(raw), ref, carveouts)}
|
||||
|
||||
|
||||
def test_matches_printed_rounds_half_away():
|
||||
assert matches_printed(-0.0625, "-0.063") and matches_printed(0.0015, "0.002")
|
||||
assert not matches_printed(0.0026, "0.002")
|
||||
|
||||
|
||||
def test_full_waveform_row_verdicts():
|
||||
res = _results("R352HIUI.F40W")
|
||||
for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime",
|
||||
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
|
||||
assert res["BatteryLevel"].verdict == "sfm_blank"
|
||||
assert "FileName" not in res
|
||||
|
||||
|
||||
def test_ragged_rows_match_by_running_channels():
|
||||
# Tran/Vert/MicL end 3 samples before Long, in SFM and in Blastware's table alike
|
||||
res = _results("T438HGTZ.B30W")
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
assert res[f"samples.{ch}"].verdict == "match", res[f"samples.{ch}"]
|
||||
|
||||
|
||||
def test_an_extra_reference_row_is_a_mismatch_with_detail():
|
||||
raw = (FIX / "T1905KDW.5F0W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
ref.sample_rows.append(["0.000", "0.000", "0.000", "0.000"])
|
||||
res = {r.field: r for r in compare(sfm_side(raw), ref)}
|
||||
assert res["samples.Tran"].verdict == "mismatch"
|
||||
assert "row_length_disagreements=1" in res["samples.Tran"].detail
|
||||
|
||||
|
||||
def test_job_number_na_and_above_range():
|
||||
res = _results("T1905KDW.5F0W")
|
||||
assert res["JobNumber"].verdict == "sfm_blank"
|
||||
assert res["TranZCFreq"].verdict == "no_reference" # N/A
|
||||
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
|
||||
|
||||
|
||||
def test_mic_units_pick_the_conversion():
|
||||
res = _results("T004JTRF.ME0H") # psi(L)
|
||||
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
|
||||
assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank"
|
||||
fields = set(_results("R352HFZ7.530H")) # no mic
|
||||
assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields)
|
||||
|
||||
|
||||
# ── Task 4: carve-outs ──────────────────────────────────────────────────────
|
||||
|
||||
from minimateplus.decode_check_carveouts import CARVEOUTS # noqa: E402
|
||||
|
||||
|
||||
def test_clipped_normal_range_is_accepted():
|
||||
# Blastware: Tran 5.445, Vert 6.310, Long OORANGE, PVS OORANGE; SFM Long 10.005, PVS 11.55
|
||||
res = _results("T438HGTZ.B30W", CARVEOUTS)
|
||||
assert res["TranPPV"].verdict == "match" and res["VertPPV"].verdict == "match"
|
||||
for f in ("LongPPV", "PeakVectorSum"):
|
||||
assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation")
|
||||
|
||||
|
||||
def test_a_clipped_sensitive_event_is_accepted_at_its_own_ceiling():
|
||||
# SFM reads the 1.250 range from the file; the clipped channels sit at 1.2506.
|
||||
res = _results("M007HVWF.K30W", CARVEOUTS)
|
||||
assert res["GeoRange"].verdict == "match" and res["samples.Tran"].verdict == "match"
|
||||
for f in ("TranPPV", "PeakVectorSum"):
|
||||
assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation")
|
||||
|
||||
|
||||
def test_the_carveout_never_accepts_an_8x_value():
|
||||
# What SFM produced while it assumed Normal on a Sensitive unit: 8x high.
|
||||
# The saturation rule must leave it a mismatch.
|
||||
raw = (FIX / "M007HVWF.K30W").read_bytes()
|
||||
side = sfm_side(raw)
|
||||
side.values.update(TranPPV=10.005, VertPPV=10.005, LongPPV=10.005, PeakVectorSum=17.33)
|
||||
side.geo_ips_per_count = 10.0 / 32000
|
||||
res = {r.field: r for r in compare(side, parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML"),
|
||||
CARVEOUTS)}
|
||||
assert res["TranPPV"].verdict == "mismatch" and res["samples.Tran"].verdict == "mismatch"
|
||||
assert res["PeakVectorSum"].verdict == "mismatch"
|
||||
|
||||
|
||||
def test_every_carveout_has_evidence():
|
||||
assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS)
|
||||
|
||||
|
||||
def test_pvs_carveout_needs_oorange_from_blastware():
|
||||
raw = (FIX / "T438HGTZ.B30W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML")
|
||||
ref.scalars["PeakVectorSum"] = "10.392" # a vector sum may exceed the range unclipped
|
||||
res = {r.field: r for r in compare(sfm_side(raw), ref, CARVEOUTS)}
|
||||
assert res["PeakVectorSum"].verdict == "mismatch"
|
||||
|
||||
|
||||
def test_pvs_carveout_needs_the_clipped_channel_at_the_ceiling():
|
||||
# 1.250 range, Blastware PVS OORANGE, but no channel Blastware clamped: an
|
||||
# UNclipped channel's 8x value landing in the 1.250 band must not let a vector
|
||||
# sum through, even one inside the sqrt(3) bound.
|
||||
raw = (FIX / "M007HVWF.K30W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML")
|
||||
ref.scalars.update(TranPPV="0.157", VertPPV="0.157", LongPPV="0.157")
|
||||
side = sfm_side(raw)
|
||||
side.values.update(TranPPV=1.256, PeakVectorSum=2.0)
|
||||
res = {r.field: r for r in compare(side, ref, CARVEOUTS)}
|
||||
assert res["PeakVectorSum"].verdict == "mismatch"
|
||||
|
||||
|
||||
def test_interval_mic_psi_matches():
|
||||
# psi(L) report: every interval's "MicL Peak psi(L)" now converts right
|
||||
assert _results("T004JTRF.ME0H")["intervals.MicL Peak psi(L)"].verdict == "match"
|
||||
|
||||
|
||||
def test_a_sensitive_range_event_now_matches():
|
||||
gr = FIX.parent / "geo-range-11-01-26"
|
||||
raw = (gr / "K557J1KB.RQ0W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(gr / "K557J1KB_RQ0W_XML.XML"))}
|
||||
for f in ("GeoRange", "TranPPV", "VertPPV", "LongPPV", "PeakVectorSum",
|
||||
"samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
@@ -269,7 +269,7 @@ def test_seismodb_persists_sidecar_filename_and_review_sync(tmp_path: Path):
|
||||
|
||||
|
||||
def test_read_blastware_file_round_trip(tmp_path: Path):
|
||||
"""write → read → key/timestamp/rectime survive."""
|
||||
"""write → read → key/timestamp survive."""
|
||||
from minimateplus.blastware_file import write_blastware_file, blastware_filename
|
||||
|
||||
ev, frames = _make_synthetic_event()
|
||||
@@ -278,7 +278,10 @@ def test_read_blastware_file_round_trip(tmp_path: Path):
|
||||
|
||||
parsed = event_file_io.read_blastware_file(bw_path)
|
||||
assert parsed._waveform_key == ev._waveform_key
|
||||
assert parsed.rectime_seconds == ev.rectime_seconds
|
||||
# The synthetic file has no recording-setup block, so its record time is
|
||||
# unknown. STRT[18], where the helper puts it, is the record-type marker
|
||||
# and is not read as a record time (#44/#45).
|
||||
assert parsed.rectime_seconds is None
|
||||
# Timestamp lands via the footer; year/month/day/hour/min/sec all survive.
|
||||
assert parsed.timestamp is not None
|
||||
assert parsed.timestamp.year == ev.timestamp.year
|
||||
|
||||
Reference in new issue
Block a user