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