merge: the Series 3 decode checker -- SFM's file-only decode against Blastware's XML reports
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
This commit is contained in:
commit
fed6489330
27 files changed
+20193
-159
No files matched your search
@@ -14,6 +14,32 @@ pair — lives in `../terra-view/docs/tmi-stack.md`, which is also loaded as
|
||||
|
||||
Read this first when picking the project back up.
|
||||
|
||||
- **🔑 The Series-3 decode checker (2026-10-29).** Goal: SFM produces everything
|
||||
Blastware reports, from the event file alone (spec/plan in `docs/superpowers/`).
|
||||
Run it with `scratch/check_s3_decode.py ~/dl2-archive/files ~/dl2-archive/xml`.
|
||||
It decodes each event from its bytes only (no filename, no report) and
|
||||
compares every field, sample and interval with Blastware's `_XML.XML`: 70,042
|
||||
events, 2016–2026, ~22 min at `--jobs 4`. Run output (`summary.md`,
|
||||
`details.json`, `changes.md`) goes to `~/dl2-archive/checker-runs/` and is
|
||||
never committed. The rule: every mismatch is SFM's bug unless a carve-out
|
||||
with evidence covers it.
|
||||
**First full run:**
|
||||
- ✅ Sample rate, record time, pre-trigger and notes match everywhere.
|
||||
- ✅ Geophone samples are exact on 6,491 / 6,524 waveforms in every year. The
|
||||
33 others are the 1.250 in/s range, 8× under SFM's Normal-range assumption.
|
||||
- ❌ Every histogram reads as a waveform without its filename (#41), and
|
||||
their start times are 1 s early (#51).
|
||||
- ❌ Open findings:
|
||||
- histogram PVS: SFM takes the vector magnitude of each channel's interval
|
||||
peak (peaks that may come from different moments); Blastware takes the
|
||||
per-interval vector sum
|
||||
- mic psi conversion
|
||||
- mic dB off by 0.05–0.1 on ~1,000 events
|
||||
- 35 sub-minute (5 s / 2 s) histograms decode wrongly, plus 2 one-minute
|
||||
no-mic histograms (`R352HFZ7`-shaped, likely a separate cause)
|
||||
- 26 histogram start dates are a day off
|
||||
- ⬜ Not read yet: job number, ZC frequency, acceleration, displacement, time
|
||||
of peak, sensor check, battery, calibration, range, units, monitor log.
|
||||
- **The Series-4 LIVE wire protocol is reverse-engineered end to end
|
||||
(2026-09-25).** `docs/micromate_protocol_reference.md` is the Series-4
|
||||
Rosetta Stone, sibling to `instantel_protocol_reference.md`. **A Micromate
|
||||
|
||||
@@ -2309,6 +2309,14 @@ The early captures were all in April (month `04`, sent as `10 04`). Not changed
|
||||
codec. They are decoded as histograms and stamped with the footer start, 4 s off; `dev`
|
||||
behaves the same. Prod's store has none. Tracked in #53.
|
||||
|
||||
⚠ **Corrected 2026-10-29 (measured against their Blastware `_XML.XML` reports):** they
|
||||
do **not** decode as histograms. All three decode as waveforms with Blastware's full
|
||||
sample count (4,352 / 4,352 / 13,280 rows), and their record time and sample rate are
|
||||
read. Only the time is wrong: no footer stop time (`ts2`) is read, so the decoder falls
|
||||
back to the footer start -- 11:14:12 / 11:14:12 / 16:14:11 against Blastware's
|
||||
11:14:08 / 11:14:08 / 16:14:08 -- and records no `decode_problems` entry. 🔶 Inferred,
|
||||
from the decode-checker design review: the decoder takes an earlier, false footer.
|
||||
|
||||
## 7.9 Compliance Config Field Inventory (Blastware UI, 2026-04-08) ✅
|
||||
|
||||
Fields visible in the Blastware "Compliance Setup" dialog. ✅ = byte offset confirmed in code. ❓ = not yet located in raw bytes.
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
# Series 3 Decode Checker Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** A repeatable check that decodes every DL2 Series 3 event file the way SFM ingest does, with no report and no filename, and compares every field, sample and histogram interval with Blastware's `_XML.XML` report. It reports matches, mismatches and gaps, grouped for diagnosis, run after run.
|
||||
|
||||
**Architecture:** There are four pieces. Two are pure codec-library modules:
|
||||
- `bw_xml_report.py` parses the reference.
|
||||
- `decode_check.py` builds SFM's side from the bytes and compares the two.
|
||||
|
||||
A carve-out list sits beside the comparison. Two lab-tool scripts in
|
||||
`scratch/` do the rest: one runs the corpus in parallel and writes a
|
||||
results file, the other turns results into the summary, the detailed
|
||||
report and the run-to-run changes.
|
||||
|
||||
**Tech Stack:** Python 3.10, standard library only (`xml.etree.ElementTree`, `concurrent.futures`, `gzip`, `json`), pytest.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Work on branch `feat/s3-decode-checker`, worktree `~/seismo-relay-checker`.
|
||||
Never commit to `main` or `dev`. **Do not touch `CHANGELOG.md`**: it is
|
||||
written on dev at merge.
|
||||
- **Standard library only.** `lxml` is not installed; do not add dependencies.
|
||||
- **Codec-library modules never import `sfm/`.** These are
|
||||
`minimateplus/bw_xml_report.py`, `minimateplus/decode_check.py` and
|
||||
`minimateplus/decode_check_carveouts.py`. Only `scratch/` may import `sfm/`.
|
||||
- **SFM's side comes only from the event bytes:**
|
||||
`decode_blastware_bytes(raw, name=None)`. No filename, no report overlay,
|
||||
and nothing from the XML ever reaches it.
|
||||
- **SFM's own assumptions are kept:**
|
||||
- geophone counts become in/s at the Normal range, `10.0 / 32000` per count
|
||||
(`event_file_io._GEO_NORMAL_FS_INS / _GEO_INT16_FS`)
|
||||
- mic counts become dB with `waveform_codec.mic_count_to_db`, or psi with
|
||||
`event_file_io._MIC_FS_PSI`
|
||||
- the range is never taken from the reference
|
||||
- **Precision rule:** a number matches when
|
||||
`|sfm − printed| ≤ 0.5·10^(−decimals in the printed text) + 1e-9`.
|
||||
Blastware rounds halves away from zero.
|
||||
- **Verdicts are exactly** `match`, `mismatch`, `sfm_blank`, `accepted`,
|
||||
`no_reference`, `error`.
|
||||
- **Series 3 only:** skip `UM…` XMLs. Dedupe binaries by upper-cased basename
|
||||
(`Sent/` mirrors the root).
|
||||
- **Run output goes outside the repo.** Default
|
||||
`~/dl2-archive/checker-runs/<YYYYmmdd-HHMMSS>/`; it contains customer
|
||||
names, so never commit it.
|
||||
- **Speed:** a full run (70,042 events, `--jobs 4`) in under 1 h; `--sample
|
||||
2000` in a few minutes.
|
||||
- **Tests:** run with `/home/serversdown/seismo-relay/.venv/bin/python -m
|
||||
pytest`.
|
||||
- The full suite has 18 known failures in this worktree, and they also fail
|
||||
on unchanged dev: 15 in `tests/test_bw_ascii_report.py`,
|
||||
`tests/test_event_file_io.py::test_save_imported_bw_without_report_works_unchanged`,
|
||||
and 2 in `tests/test_idf_binary_codec.py` (three-channel).
|
||||
- A task may add **no new** failures.
|
||||
- **Fixtures:** `tests/fixtures/` is gitignored. Add new fixtures with
|
||||
`git add -f`.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. **Ragged sample rows.** Channels can end at different lengths: in
|
||||
`T438HGTZ.B30W`, Tran/Vert/MicL stop 3 samples before Long. Blastware's
|
||||
own table then prints rows with fewer cells, holding the channels still
|
||||
running, in order. Cells must be attributed by SFM's per-channel lengths,
|
||||
not by position. That file must come out `match`. A row whose cell count
|
||||
disagrees with SFM's running channels is a `mismatch` with
|
||||
`row_length_disagreements` in `detail`; never a silent zip. Tests in Task 3.
|
||||
2. **The Sensitive range: a clipped 1.250 in/s event** (`M007HVWF.K30W`,
|
||||
`OORANGE`). SFM's Normal-range values (8× high) must stay `mismatch`; the
|
||||
saturation carve-out must not swallow them. Test in Task 4.
|
||||
3. **An event that fails to decode, or an XML that is truncated or
|
||||
malformed.** That event gets one `error` row and the run continues. Test in
|
||||
Task 5.
|
||||
4. **Non-numeric reference text where numbers are expected:** `>100`, `N/A`,
|
||||
`Check`, `OORANGE`, and units inside the text (`6.7 Volts`, `3.0 sec.`).
|
||||
These parse without exceptions and map to the rules in Task 3. Tests in
|
||||
Tasks 1 and 3.
|
||||
5. **Mic units: `dB(L)` vs `psi(L)` vs none** (`in/s` only, 3 channels, 7
|
||||
interval columns). The comparison picks SFM's conversion by the reference's
|
||||
units, and a no-mic event has no MicL rows at all. Tests in Tasks 1 and 3.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Fixtures and the XML report parser
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/fixtures/decode-checker-10-29-26/` holding these binaries
|
||||
plus each one's `<stem>_<ext>_XML.XML`, copied from `~/dl2-archive/files/`
|
||||
and `~/dl2-archive/xml/`:
|
||||
- `R352HIUI.F40W`: waveform, setup `BE16352.set`
|
||||
- `M529L4XQ.R30H`: histogram, relabelled notes
|
||||
- `T1905KDW.5F0W`: waveform, job number, `>100`, `N/A`, `Check`
|
||||
- `M007HVWF.K30W`: waveform, range 1.250, `OORANGE`
|
||||
- `T004JTRF.ME0H`: histogram, `psi(L)`
|
||||
- `R352HFZ7.530H`: histogram, no mic
|
||||
- `T438HGTZ.B30W`: waveform, ragged rows, `OORANGE` at range 10.000
|
||||
- Create: `minimateplus/bw_xml_report.py`
|
||||
- Test: `tests/test_bw_xml_report.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
```python
|
||||
@dataclass
|
||||
class XmlReport:
|
||||
scalars: dict[str, str] # tag -> text: top-level simple elements, and
|
||||
# <Tag><Value>v</Value><Units>u</Units></Tag> -> v
|
||||
units: dict[str, str] # tag -> the nested <Units> text
|
||||
event_units: Optional[str] # top-level <Units>, e.g. "in/s and dB(L)"
|
||||
channels: list[str] # <Channels>/<Channel> in order
|
||||
job_number: Optional[str]
|
||||
notes: list[tuple[str, str]] # (tag, value), non-empty, in order, between
|
||||
# top-level </Units> and <GeoRange>, JobNumber excluded
|
||||
sample_rows: Optional[list[list[str]]] # waveform: printed cells per row, as-is;
|
||||
# a row holds only the channels still running
|
||||
interval_columns: Optional[list[str]] # histogram: ColumnTitle, whitespace collapsed
|
||||
intervals: Optional[list[tuple[str, list[str]]]] # histogram: (Time, cells)
|
||||
def parse_xml_report(data: bytes) -> XmlReport
|
||||
def parse_xml_report_file(path: Union[str, Path]) -> XmlReport
|
||||
```
|
||||
|
||||
- [ ] **Step 1: Copy the seven pairs into the fixture folder** (`cp` from the two dl2 folders; XML names keep the `_XML.XML` form).
|
||||
|
||||
- [ ] **Step 2: Write the failing tests** (literal values read from the XMLs):
|
||||
|
||||
```python
|
||||
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
|
||||
|
||||
def test_scalars_units_and_special_text():
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert r.scalars["SampleRate"] == "1024 sps"
|
||||
assert r.scalars["RecordTime"] == "1.0 sec."
|
||||
assert r.scalars["TranPPV"] == "0.005" and r.units["TranPPV"] == "in/s"
|
||||
assert r.scalars["VertZCFreq"] == ">100" # entity unescaped
|
||||
assert r.scalars["TranZCFreq"] == "N/A"
|
||||
assert r.scalars["TranTestResults"] == "Check"
|
||||
assert r.scalars["BatteryLevel"] == "6.7 Volts"
|
||||
assert r.job_number == "1" and r.notes == []
|
||||
assert r.channels == ["Tran", "Vert", "Long", "MicL"]
|
||||
|
||||
def test_waveform_sample_rows():
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert len(r.sample_rows) == 1024
|
||||
assert r.sample_rows[0] == ["-0.005", "0.000", "0.000", "81.94"]
|
||||
assert r.intervals is None
|
||||
|
||||
def test_ragged_rows_are_kept_as_printed():
|
||||
r = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML")
|
||||
assert len(r.sample_rows) == 2304
|
||||
assert r.sample_rows[-4] == ["-0.185", "0.235", "-0.255", "-87.96"]
|
||||
assert r.sample_rows[-1] == ["-0.245"] # only Long still running
|
||||
|
||||
def test_relabelled_notes_keep_their_tags_in_order():
|
||||
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
|
||||
assert r.notes == [("Location", "Test Loc")]
|
||||
r = parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML")
|
||||
assert r.notes[1] == ("Client", "Mele & Mele & Sons, Inc.")
|
||||
assert r.event_units == "in/s and psi(L)"
|
||||
|
||||
def test_histogram_intervals_and_columns():
|
||||
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
|
||||
assert r.interval_columns[0] == "Tran Peak in/s" and len(r.interval_columns) == 10
|
||||
assert r.intervals == [("2025-07-02 14:55:08",
|
||||
["2.430", "13", "0.940", ">100", "1.900", "5.8", "3.095", "0.001", "106.0", "51"])]
|
||||
assert r.samples is None
|
||||
|
||||
def test_no_mic_histogram_has_seven_columns():
|
||||
r = parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML")
|
||||
assert r.event_units == "in/s"
|
||||
assert r.channels == ["Tran", "Vert", "Long"]
|
||||
assert len(r.interval_columns) == 7 and len(r.intervals[0][1]) == 7
|
||||
|
||||
def test_oorange_and_range_values():
|
||||
r = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML")
|
||||
assert r.scalars["TranPPV"] == "OORANGE"
|
||||
assert r.scalars["GeoRange"] == "1.250" and r.units["GeoRange"] == "in/s"
|
||||
|
||||
def test_truncated_xml_raises_valueerror():
|
||||
data = (FIX / "M529L4XQ_R30H_XML.XML").read_bytes()
|
||||
with pytest.raises(ValueError):
|
||||
parse_xml_report(data[: len(data) // 2])
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run them to watch them fail.**
|
||||
Run: `…/python -m pytest tests/test_bw_xml_report.py -v`. Expected: FAIL on import.
|
||||
|
||||
- [ ] **Step 4: Implement `bw_xml_report.py`.**
|
||||
- Parse with `xml.etree.ElementTree.fromstring`; wrap `ParseError` in `ValueError`.
|
||||
- Walk the root's children in order.
|
||||
- A child with a `<Value>` child goes in `scalars` and `units`.
|
||||
- The notes are the simple children after the top-level `Units` and before
|
||||
`GeoRange`.
|
||||
- Waveform cells: `WaveformDataChannels/Data/Row/Cell`, one list per row,
|
||||
unaltered.
|
||||
- Histogram: `HistogramData/HistogramDataColumnTitle/ColumnTitle` and
|
||||
`HistogramDataIntervals`, which interleaves `Time` and `Row`.
|
||||
|
||||
- [ ] **Step 5: Run the tests.** Expected: PASS.
|
||||
|
||||
- [ ] **Step 6: Commit** (fixtures with `git add -f`):
|
||||
`feat(codec): parse Blastware's _XML.XML event report`
|
||||
|
||||
---
|
||||
|
||||
### Task 2: SFM's side, from the bytes alone
|
||||
|
||||
**Files:**
|
||||
- Create: `minimateplus/decode_check.py`
|
||||
- Test: `tests/test_decode_check.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `minimateplus.event_file_io.decode_blastware_bytes`, `_GEO_NORMAL_FS_INS`, `_GEO_INT16_FS`, `_MIC_FS_PSI`; `minimateplus.waveform_codec.mic_count_to_db`.
|
||||
- Produces:
|
||||
```python
|
||||
GEO_IPS_PER_COUNT: float = 10.0 / 32000 # from the event_file_io constants
|
||||
@dataclass
|
||||
class SfmSide:
|
||||
event: Event
|
||||
values: dict[str, object] # reference tag -> SFM's value, or absent/None = blank
|
||||
notes: list[str] # non-empty project_info slots, in order
|
||||
job_number: Optional[str] # None until the decoder reads it
|
||||
channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order
|
||||
counts: dict[str, list[int]] # waveform samples or histogram interval peaks, per channel
|
||||
def sfm_side(raw: bytes) -> SfmSide
|
||||
```
|
||||
The `values` keys, and the only ones SFM fills today:
|
||||
- `EventType`: `"Full Waveform"` / `"Full Histogram"` from `record_type`
|
||||
- `SampleRate` (int), `RecordTime` (float)
|
||||
- `Pre-triggerLength`: `-pretrig_samples / sample_rate`
|
||||
- `EventDate` and `EventTime` for a waveform, or `HistogramStartDate` and
|
||||
`HistogramStartTime` for a histogram: `YYYY-MM-DD` and `HH:MM:SS` from
|
||||
`event.timestamp`
|
||||
- `TranPPV`, `VertPPV`, `LongPPV`, `PeakVectorSum` from `peak_values`
|
||||
- `MicLPSPL dB(L)`: `mic_count_to_db` of the largest |MicL count|
|
||||
- `MicLPSPL psi(L)`: `peak_values.micl`
|
||||
- `NumberofIntervals` for a histogram: the interval count
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
|
||||
```python
|
||||
def test_waveform_side_from_bytes():
|
||||
s = sfm_side((FIX / "R352HIUI.F40W").read_bytes())
|
||||
assert s.values["SampleRate"] == 1024 and s.values["RecordTime"] == pytest.approx(1.0)
|
||||
assert s.values["Pre-triggerLength"] == pytest.approx(-253 / 1024)
|
||||
assert (s.values["EventDate"], s.values["EventTime"]) == ("2018-07-30", "16:13:52")
|
||||
assert s.notes == ["JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV",
|
||||
"Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"]
|
||||
assert len(s.counts["Tran"]) == 1277 and s.job_number is None
|
||||
|
||||
def test_histogram_interval_peak_in_counts():
|
||||
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
|
||||
# Blastware: Tran interval peak 2.430 in/s = 7776 counts at 10/32000 in/s per count
|
||||
assert s.counts["Tran"] == [7776] and s.values["NumberofIntervals"] == 1
|
||||
|
||||
def test_no_filename_reaches_the_decoder():
|
||||
# the type must come from bytes; today they can't tell (#41), so a histogram reads Waveform
|
||||
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
|
||||
assert s.values["EventType"] == "Full Waveform"
|
||||
|
||||
def test_report_fields_stay_blank():
|
||||
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
|
||||
for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"):
|
||||
assert s.values.get(tag) is None
|
||||
```
|
||||
|
||||
When #41 is fixed, `test_no_filename_reaches_the_decoder` is updated to
|
||||
`"Full Histogram"`. Until then it pins that no name is passed.
|
||||
|
||||
- [ ] **Step 2: Run them; expect a FAIL on import.**
|
||||
- [ ] **Step 3: Implement `sfm_side`** in `minimateplus/decode_check.py`, per the Interfaces block.
|
||||
- [ ] **Step 4: Run them; expect PASS.**
|
||||
- [ ] **Step 5: Commit:** `feat(codec): SFM's side of the decode check, from the event bytes alone`
|
||||
|
||||
---
|
||||
|
||||
### Task 3: The comparison
|
||||
|
||||
**Files:**
|
||||
- Modify: `minimateplus/decode_check.py`
|
||||
- Test: `tests/test_decode_check.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `XmlReport` (Task 1), `SfmSide` (Task 2), `Carveout` (Task 4,
|
||||
passed in; default `()` so this task stands alone).
|
||||
- Produces:
|
||||
```python
|
||||
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
|
||||
@dataclass
|
||||
class FieldResult:
|
||||
field: str # reference tag, or "notes", "JobNumber", "Channels",
|
||||
# "samples.<ch>", "intervals.<column title>"
|
||||
verdict: str
|
||||
bw: Optional[str] # printed text, or "<n> cells" for a series
|
||||
sfm: Optional[str] # SFM's value rendered at the printed precision
|
||||
detail: str = "" # series: "rows=… differing=… row_length_disagreements=… first_diff=… max_abs=…"
|
||||
carveout: Optional[str] = None
|
||||
def matches_printed(value: float, printed: str) -> bool
|
||||
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]
|
||||
```
|
||||
|
||||
**Rules** (exact; the tests pin each):
|
||||
|
||||
- **Which fields:** every tag in `ref.scalars` is compared except
|
||||
`FileVersion` and `FileName`. So a field the XML carries and SFM doesn't is
|
||||
automatically `sfm_blank`.
|
||||
- **The reference says `N/A`:** the verdict is `no_reference`.
|
||||
- **SFM has nothing (`None`):** `sfm_blank`.
|
||||
- **Numbers:** for a value whose printed text begins with a number
|
||||
(`-?\d+(\.\d+)?`, units after it ignored), the verdict is `match` when
|
||||
`matches_printed` holds, else `mismatch`.
|
||||
- **`>100`:** matches only when SFM's matching `*_zc_above_range` flag is True.
|
||||
- **`OORANGE`:** a `mismatch` unless a carve-out applies.
|
||||
- **Text:** anything else is compared exactly after whitespace collapse.
|
||||
- **`MicLPSPL`:** compared against SFM's `MicLPSPL dB(L)` when `event_units`
|
||||
contains `dB(L)`, `MicLPSPL psi(L)` when it contains `psi(L)`, otherwise
|
||||
`sfm_blank`.
|
||||
- **`notes`:** the list of note values vs `sfm.notes`. **`JobNumber`:**
|
||||
`ref.job_number` vs `sfm.job_number` (skipped when the reference has none).
|
||||
**`Channels`:** `ref.channels` vs `sfm.channels`.
|
||||
- **`samples.<ch>`, one result per reference channel:**
|
||||
- SFM's cells are geophone `count × GEO_IPS_PER_COUNT`; MicL uses
|
||||
`mic_count_to_db(count)` for `dB(L)` or `count × _MIC_FS_PSI` for
|
||||
`psi(L)`.
|
||||
- For row *j*, SFM's running channels are the reference channels (in
|
||||
order) with `len(sfm.counts[ch]) > j`. Their cells pair up, in order,
|
||||
with the reference row's cells.
|
||||
- A row whose cell count differs from SFM's running count is a row-length
|
||||
disagreement for every channel in it. So are reference rows past SFM's
|
||||
longest channel.
|
||||
- A channel is `match` only with no row-length disagreements and every
|
||||
paired cell `matches_printed`.
|
||||
- `detail` always carries `rows=`, `differing=`,
|
||||
`row_length_disagreements=`, `first_diff=` and `max_abs=`.
|
||||
- **`intervals.<column>`, one row per column title:**
|
||||
- The peak columns compare like samples: geophone `Peak in/s`, MicL
|
||||
`Peak psi(L)` and `Peak dB(L)`.
|
||||
- The `Freq` and `Geo PVS` columns are `sfm_blank` (SFM drops them).
|
||||
- `intervals.Time` is `sfm_blank`.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
|
||||
```python
|
||||
def test_matches_printed_rounds_half_away():
|
||||
assert matches_printed(-0.0625, "-0.063") and matches_printed(0.0015, "0.002")
|
||||
assert not matches_printed(0.0026, "0.002")
|
||||
|
||||
def test_full_waveform_row_verdicts():
|
||||
raw = (FIX / "R352HIUI.F40W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "R352HIUI_F40W_XML.XML"))}
|
||||
for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime",
|
||||
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
|
||||
assert res["BatteryLevel"].verdict == "sfm_blank"
|
||||
assert "FileName" not in res
|
||||
|
||||
def test_ragged_rows_match_by_running_channels():
|
||||
# Tran/Vert/MicL end 3 samples before Long, in SFM and in Blastware's table alike
|
||||
raw = (FIX / "T438HGTZ.B30W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML"))}
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
assert res[f"samples.{ch}"].verdict == "match", res[f"samples.{ch}"]
|
||||
|
||||
def test_an_extra_reference_row_is_a_mismatch_with_detail():
|
||||
raw = (FIX / "T1905KDW.5F0W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
ref.sample_rows.append(["0.000", "0.000", "0.000", "0.000"])
|
||||
res = {r.field: r for r in compare(sfm_side(raw), ref)}
|
||||
assert res["samples.Tran"].verdict == "mismatch"
|
||||
assert "row_length_disagreements=1" in res["samples.Tran"].detail
|
||||
|
||||
def test_job_number_na_and_above_range():
|
||||
raw = (FIX / "T1905KDW.5F0W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML"))}
|
||||
assert res["JobNumber"].verdict == "sfm_blank"
|
||||
assert res["TranZCFreq"].verdict == "no_reference" # N/A
|
||||
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
|
||||
|
||||
def test_mic_units_pick_the_conversion():
|
||||
raw = (FIX / "T004JTRF.ME0H").read_bytes() # psi(L)
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML"))}
|
||||
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
|
||||
assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank"
|
||||
raw = (FIX / "R352HFZ7.530H").read_bytes() # no mic
|
||||
fields = {r.field for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML"))}
|
||||
assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them; expect a FAIL** (no `compare`).
|
||||
- [ ] **Step 3: Implement `matches_printed` and `compare`**, per the rules.
|
||||
- [ ] **Step 4: Run them; expect PASS.** If a `match` assertion fails, report
|
||||
the `FieldResult` and stop. Do not loosen a rule to make it pass.
|
||||
- [ ] **Step 5: Commit:** `feat(codec): compare SFM's file-only decode with Blastware's XML, field by field`
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Carve-outs
|
||||
|
||||
**Files:**
|
||||
- Create: `minimateplus/decode_check_carveouts.py`
|
||||
- Modify: `minimateplus/decode_check.py` (apply carve-outs in `compare`)
|
||||
- Test: `tests/test_decode_check.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
```python
|
||||
@dataclass(frozen=True)
|
||||
class Carveout:
|
||||
id: str
|
||||
fields: tuple[str, ...] # exact names, or prefixes ending in "." ("samples.")
|
||||
evidence: str # why Blastware is the one that differs, and the source
|
||||
applies: Callable[[SfmSide, XmlReport, FieldResult], bool]
|
||||
SATURATION: Carveout
|
||||
CARVEOUTS: tuple[Carveout, ...] = (SATURATION,)
|
||||
```
|
||||
- **How `compare` uses them:** a `mismatch` whose field a carve-out covers and
|
||||
whose `applies` returns True becomes `accepted`, with `carveout=<id>`.
|
||||
- **`SATURATION`:**
|
||||
- Covers `TranPPV`, `VertPPV`, `LongPPV`, `PeakVectorSum`,
|
||||
`samples.Tran/Vert/Long` and the `intervals.* Peak in/s` columns.
|
||||
- `r = float(ref.scalars["GeoRange"])`. A cell or value Blastware printed as
|
||||
`OORANGE`, or with `|bw| ≥ r − 0.0006`, is "clamped".
|
||||
- It applies when every differing cell/value is clamped and SFM's is the
|
||||
same sign with `r − 0.0006 ≤ |sfm| ≤ r × 1.01`.
|
||||
- The upper bound keeps an 8× Sensitive-range value a mismatch.
|
||||
- **`PeakVectorSum`** is a vector sum, so it can exceed the range (11.55
|
||||
on `T438HGTZ`). It is accepted when Blastware printed `OORANGE` and at
|
||||
least one of SFM's three PPVs sits in that ceiling band.
|
||||
- Evidence text: *"Blastware clamps a clipped channel to the range maximum
|
||||
and prints OORANGE; the file holds counts past full scale (32016 counts =
|
||||
10.005 in/s observed). scratch/verify_against_ascii.py, 2026-08-28."*
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
|
||||
```python
|
||||
def test_clipped_normal_range_is_accepted():
|
||||
# Blastware: Tran 5.445, Vert 6.310, Long OORANGE, PVS OORANGE; SFM Long 10.005, PVS 11.55
|
||||
raw = (FIX / "T438HGTZ.B30W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML"), CARVEOUTS)}
|
||||
assert res["TranPPV"].verdict == "match" and res["VertPPV"].verdict == "match"
|
||||
for f in ("LongPPV", "PeakVectorSum"):
|
||||
assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation")
|
||||
|
||||
def test_sensitive_range_8x_stays_a_mismatch():
|
||||
raw = (FIX / "M007HVWF.K30W").read_bytes()
|
||||
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML"), CARVEOUTS)}
|
||||
assert res["TranPPV"].verdict == "mismatch" and res["samples.Tran"].verdict == "mismatch"
|
||||
|
||||
def test_every_carveout_has_evidence():
|
||||
assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them; expect a FAIL.**
|
||||
- [ ] **Step 3: Implement the module and the hook in `compare`.**
|
||||
- [ ] **Step 4: Run all `tests/test_decode_check.py`; expect PASS.**
|
||||
- [ ] **Step 5: Commit:** `feat(codec): carve-outs for proven Blastware differences -- saturation first`
|
||||
|
||||
---
|
||||
|
||||
### Task 5: The runner
|
||||
|
||||
**Files:**
|
||||
- Create: `scratch/check_s3_decode.py`
|
||||
- Test: `tests/test_check_s3_decode.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `parse_xml_report_file`, `sfm_side`, `compare`, `CARVEOUTS`.
|
||||
- Produces:
|
||||
```python
|
||||
def find_pairs(bin_dir: Path, xml_dir: Path) -> list[tuple[str, Path, Optional[Path]]]
|
||||
# (basename, binary, xml or None); Series 3 binaries only (^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$),
|
||||
# deduped by upper-case basename; xml = <stem>_<ext>_XML.XML in xml_dir
|
||||
def event_attrs(name: str, ref: XmlReport, raw: bytes) -> dict[str, str]
|
||||
# grouping keys, all from the reference or the file:
|
||||
# model ("MiniMate Plus" / "BlastMate III" from Version), serial (SerialNumber),
|
||||
# type (EventType), year (EventDate or HistogramStartDate), sample_rate, range (GeoRange),
|
||||
# mic_units (event_units), interval (IntervalSize or "-"),
|
||||
# setup_standard ("yes" if b"Standard Recording Setup" in raw else "no")
|
||||
def check_event(name: str, bin_path: str, xml_path: Optional[str]) -> dict
|
||||
# {"file", "attrs", "results": [[field, verdict, bw, sfm, detail, carveout], ...]}
|
||||
# no xml -> one ["event","no_reference",…] row; any exception -> one ["event","error",None,None,repr(exc),None] row
|
||||
def main(argv: Optional[list[str]] = None) -> int
|
||||
```
|
||||
- **CLI:** `bin_dir xml_dir [--out DIR] [--serial S]... [--year Y]...
|
||||
[--type W|H] [--field PREFIX]... [--sample N] [--seed K] [--jobs N]
|
||||
[--file NAME] [--compare-to DIR]`.
|
||||
- `--field` keeps only result rows whose field starts with a given prefix
|
||||
(the spec's "field group" partial run).
|
||||
- `--file` and `--compare-to` are wired in Task 7; here they are only
|
||||
accepted.
|
||||
- The spec's "decoder path" grouping key is omitted: the decoder does not
|
||||
expose it today.
|
||||
- **Output:** writes `<out>/results.jsonl.gz` (one line per event) and
|
||||
`<out>/run.json`.
|
||||
- `run.json` holds the args, the `git rev-parse HEAD`, the event count and
|
||||
the wall time.
|
||||
- It prints the run folder.
|
||||
- Parallelism: `ProcessPoolExecutor(jobs).map(…, chunksize=64)`.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests** (on the fixture folder, which holds
|
||||
binaries and XMLs together):
|
||||
|
||||
```python
|
||||
def test_find_pairs_dedupes_and_pairs(tmp_path):
|
||||
(tmp_path / "Sent").mkdir()
|
||||
for n in ("R352HIUI.F40W", "Sent/R352HIUI.F40W", "UM11719_20240404193109.IDFH"):
|
||||
(tmp_path / n).write_bytes(b"x")
|
||||
pairs = find_pairs(tmp_path, FIX)
|
||||
assert [p[0] for p in pairs] == ["R352HIUI.F40W"] and pairs[0][2].name == "R352HIUI_F40W_XML.XML"
|
||||
|
||||
def test_check_event_rows_and_attrs():
|
||||
out = check_event("M007HVWF.K30W", str(FIX / "M007HVWF.K30W"), str(FIX / "M007HVWF_K30W_XML.XML"))
|
||||
assert out["attrs"]["range"] == "1.250" and out["attrs"]["model"] == "MiniMate Plus"
|
||||
assert any(r[0] == "TranPPV" and r[1] == "mismatch" for r in out["results"])
|
||||
|
||||
def test_bad_input_is_one_error_row(tmp_path):
|
||||
bad = tmp_path / "R352HIUI.F40W"; bad.write_bytes(b"not a blastware file")
|
||||
out = check_event(bad.name, str(bad), str(FIX / "R352HIUI_F40W_XML.XML"))
|
||||
assert out["results"] == [["event", "error", None, None, out["results"][0][4], None]]
|
||||
|
||||
def test_cli_writes_results(tmp_path):
|
||||
assert main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1"]) == 0
|
||||
lines = gzip.open(tmp_path / "run/results.jsonl.gz", "rt").read().splitlines()
|
||||
assert len(lines) == 7 and json.loads((tmp_path / "run/run.json").read_text())["events"] == 7
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run them; expect a FAIL.**
|
||||
- [ ] **Step 3: Implement**, per the Interfaces block.
|
||||
- [ ] **Step 4: Run them; expect PASS.**
|
||||
- [ ] **Step 5: Time a sample.** Run `scratch/check_s3_decode.py
|
||||
~/dl2-archive/files ~/dl2-archive/xml --sample 2000 --jobs 4`. Expected: a
|
||||
few minutes. Note the time in the commit body.
|
||||
- [ ] **Step 6: Commit:** `tooling(scratch): run the decode check over the archive in parallel`
|
||||
|
||||
---
|
||||
|
||||
### Task 6: The summary and the detailed report
|
||||
|
||||
**Files:**
|
||||
- Create: `scratch/decode_check_report.py`
|
||||
- Modify: `scratch/check_s3_decode.py` (write both reports at the end of a run)
|
||||
- Test: `tests/test_check_s3_decode.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
```python
|
||||
def aggregate(results_path: Path) -> dict
|
||||
def write_summary(agg: dict, path: Path) -> None # <out>/summary.md, for Brian
|
||||
def write_details(agg: dict, path: Path) -> None # <out>/details.json, for Claude
|
||||
```
|
||||
- **`summary.md`** has four parts:
|
||||
- a per-field table with one column per verdict (in `VERDICTS` order),
|
||||
sorted by non-match count
|
||||
- a line `N of M fields fully matching`
|
||||
- the non-match counts per event year
|
||||
- the carve-out counts
|
||||
- **`details.json`** has one entry per `(field, verdict)` with verdict ≠
|
||||
`match`. Each entry holds:
|
||||
- `total`
|
||||
- `groups`: for each attribute, the values whose failing count is ≥ 10% of
|
||||
`total`. Each value carries `{value, failing, compared, rate}`, where
|
||||
`compared` counts events where the field's verdict was not
|
||||
`no_reference`. Sorted by `failing` descending; `concentrated: true` when
|
||||
`rate ≥ 0.95`.
|
||||
- `examples`: up to 8, taking one per top group value first. Each gives
|
||||
`{file, bw, sfm, detail, rerun}` with `rerun = "python
|
||||
scratch/check_s3_decode.py <bin_dir> <xml_dir> --file <name>"`.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:** build a small `results.jsonl.gz` by
|
||||
hand with literal rows: 3 events, one field `SampleRate`, two `mismatch` on
|
||||
`sample_rate=2048`, one `match` on `1024`. Assert:
|
||||
- `details.json["SampleRate|mismatch"]["groups"]["sample_rate"]` is
|
||||
`[{"value": "2048", "failing": 2, "compared": 2, "rate": 1.0,
|
||||
"concentrated": True}]`
|
||||
- `summary.md` contains `0 of 1 fields fully matching`
|
||||
- every example carries a `rerun` with `--file`
|
||||
- [ ] **Step 2: Run them; expect a FAIL.**
|
||||
- [ ] **Step 3: Implement**, streaming the results file line by line and
|
||||
holding only counters plus a capped example list.
|
||||
- [ ] **Step 4: Run them; expect PASS.**
|
||||
- [ ] **Step 5: Commit:** `tooling(scratch): decode-check summary and grouped detail report`
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Run-to-run changes and the single-event view
|
||||
|
||||
**Files:**
|
||||
- Modify: `scratch/decode_check_report.py`, `scratch/check_s3_decode.py`
|
||||
- Test: `tests/test_check_s3_decode.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
```python
|
||||
def compare_runs(prev_results: Path, cur_results: Path) -> dict
|
||||
# {"fields": {field: {verdict: [before, after]}},
|
||||
# "regressions": [{"file", "field", "before", "after"}], # before == "match", after != "match"
|
||||
# "fixed": int} # before != "match", after == "match"
|
||||
def write_changes(chg: dict, path: Path) -> None # <out>/changes.md, regressions first
|
||||
```
|
||||
- **`--compare-to DIR`:** defaults to the newest other folder in the runs
|
||||
folder. `summary.md` starts with a regressions line (`0 regressions` or the
|
||||
count plus a pointer to `changes.md`).
|
||||
- **`--file NAME`:** finds that one event, runs `check_event` and prints a
|
||||
table `field | verdict | Blastware | SFM | detail` to stdout. No run folder
|
||||
is written.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:**
|
||||
- Two hand-built results files where one `(file, field)` goes from `match`
|
||||
to `mismatch` and another from `sfm_blank` to `match`: assert one
|
||||
regression and `fixed == 1`.
|
||||
- `main([FIX, FIX, "--file", "M007HVWF.K30W"])` prints a line containing
|
||||
`TranPPV` and `mismatch`, and returns 0.
|
||||
- [ ] **Step 2: Run them; expect a FAIL.**
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run them; expect PASS.**
|
||||
- [ ] **Step 5: Commit:** `tooling(scratch): decode-check run-to-run changes and a one-event view`
|
||||
|
||||
---
|
||||
|
||||
### Task 8: The first full run, checked against what we know
|
||||
|
||||
**Files:**
|
||||
- Delete: `scratch/verify_bw_fields_against_xml.py` (the checker replaces it)
|
||||
- Modify: `CLAUDE.md` ("Where things stand": one short bullet with the first
|
||||
run's headline numbers and the command)
|
||||
- Modify: `docs/instantel_protocol_reference.md`. Correct the `#53` note in
|
||||
place, per the retraction convention: the three files pick an earlier,
|
||||
false footer, get the right sample count and a time 4 s off, and log no
|
||||
`decode_problems`. ⚠ The file is CRLF, so edit it with the Edit tool, not a
|
||||
Python text-mode rewrite.
|
||||
|
||||
- [ ] **Step 1: Full run.** `scratch/check_s3_decode.py ~/dl2-archive/files
|
||||
~/dl2-archive/xml --jobs 4`. Expected: it finishes in under an hour and
|
||||
writes `summary.md`, `details.json` and `results.jsonl.gz`.
|
||||
- [ ] **Step 2: Check the first-run expectations from the spec's "What success
|
||||
looks like"**, one by one, against `summary.md` and `details.json`:
|
||||
- `SampleRate`, `RecordTime`, `Pre-triggerLength` and `notes` all `match`
|
||||
- `samples.*` mismatch only on the range-1.250 events (8×) among 2025–26
|
||||
events; `T438HGTZ.B30W` matches
|
||||
- `EventType` mismatches exactly on the histograms
|
||||
- `JobNumber` and the calculated fields are `sfm_blank`
|
||||
- the three `#53` files show as time mismatches
|
||||
Any other non-match is a finding. Write it into the report's notes for
|
||||
Brian; **do not change a rule to hide it.** If an expectation fails because
|
||||
the checker is wrong, fix the checker with a test first.
|
||||
- [ ] **Step 3: Full suite.** Expected: no new failures beyond the 18 known.
|
||||
- [ ] **Step 4: Docs, per Files above.**
|
||||
- [ ] **Step 5: Commit:** `docs: the decode checker's first full run; correct the #53 note`
|
||||
@@ -0,0 +1,268 @@
|
||||
# Series 3 decode checker — design
|
||||
|
||||
**Date:** 2026-10-29 · **Branch:** `feat/s3-decode-checker` · **Status:** design
|
||||
|
||||
## Why this exists
|
||||
|
||||
SFM is meant to replace Blastware. Today, when a Series 3 event arrives with
|
||||
Blastware's ASCII report, SFM takes many of its values from the report: ZC
|
||||
frequency, acceleration, the sensor check and so on. Two of the four ways
|
||||
events will reach SFM, its own serial/modem download and its future call-in
|
||||
server, never have a report. So SFM must produce **everything Blastware
|
||||
reports, from the event file alone**, and we need proof that it does.
|
||||
|
||||
The checker is that proof, and the to-do list for getting there. It decodes
|
||||
each event file the way SFM ingest does, with no report, and compares every
|
||||
field with Blastware's own report of the same event. Then it says what
|
||||
matches, what doesn't, and what SFM can't produce yet.
|
||||
|
||||
It is the first of four pieces, agreed with Brian on 2026-10-29:
|
||||
|
||||
1. **This checker.**
|
||||
2. Completing SFM's file-only decode, one field group at a time, each slice
|
||||
done when the checker shows it matching. Slice 1, the setup fields and
|
||||
notes (#44/#45), merged to dev as `42fe35f`.
|
||||
3. Flipping ingest to file-only. Reports are kept for checking only. This
|
||||
happens only when piece 2 leaves no blanks and the checker proves it.
|
||||
Prod keeps its current behaviour until then.
|
||||
4. The watcher: it forwards the XML report while we verify, then stops
|
||||
forwarding reports.
|
||||
|
||||
## The reference: Blastware's XML event reports
|
||||
|
||||
Every Blastware ACH machine keeps, in `Sent/`, a full XML event report for each
|
||||
event: `<stem>_<ext>_XML.XML` next to the binary `<stem>.<ext>`. DL2's backup
|
||||
holds **70,042 of them for Series 3 events, from 2016 to 2026**. Its ASCII
|
||||
reports, by contrast, cover only 2025–26.
|
||||
|
||||
Local copies on the dev box (`tmi-dev`, 10.0.0.44):
|
||||
|
||||
| what | where | count |
|
||||
|---|---|---|
|
||||
| event binaries (Series 3) | `~/dl2-archive/files/` (root + `Sent/` mirror, dedupe by basename) | 70,112 distinct |
|
||||
| XML reports | `~/dl2-archive/xml/` (flat) | 75,958 = 70,042 Series 3 + 5,916 Micromate (`UM…_IDF?_XML.XML`) |
|
||||
| ASCII reports | `~/dl2-archive/files/` | 14,338 (2025–26 only) |
|
||||
|
||||
What the Series 3 XML contains (surveyed across all 75,958 on 2026-10-29):
|
||||
|
||||
- **Identity:** `EventType` (`Full Waveform` 6,524, `Full Histogram`
|
||||
63,518), `SerialNumber`, `Version` (`V 10.72-8.17 MiniMate Plus` or
|
||||
`… BlastMate III`), `FileName`.
|
||||
- **Time:** waveform `EventDate`/`EventTime`; histogram
|
||||
`HistogramStart*`/`HistogramStop*`.
|
||||
- **Setup:** `Channels`, `Trigger`, `GeoTriggerLevel`, `MicTriggerLevel`,
|
||||
`Pre-triggerLength`, `RecordTime`, `RecordStopMode` (only `Fixed` occurs),
|
||||
`SampleRate`, `IntervalSize` (2 s / 5 s / 15 s / 1 min / 5 min),
|
||||
`NumberofIntervals`, `GeoRange` (10.000: 75,923; 1.250: 35), `Units` (`in/s
|
||||
and dB(L)` / `psi(L)` / `dB(A)` / `in/s`), `Microphone` (weighting).
|
||||
- **Unit:** `BatteryLevel`, `Calibration` (date + by whom), `MicCalibration`.
|
||||
- **Notes:** `JobNumber`, then up to four user notes. Each is tagged with its
|
||||
operator-editable label (`Project`, `Location`, `Seis.Loc`, `SeisLocation`,
|
||||
`SeismographLoc`, `Company`, `General`, …), and empty notes are omitted.
|
||||
They sit between the top-level `</Units>` and `<GeoRange>`.
|
||||
- **Results:** per channel `PPV`, `ZCFreq`, `TimeofPeak`, `PeakAcceleration`,
|
||||
`PeakDisplacement` (waveform) or `PeakDate`/`PeakTime` (histogram);
|
||||
`PeakVectorSum` with its time; mic `PSPL`, time, `ZCFreq` (dB(A)
|
||||
histograms carry `MicA*` fields instead).
|
||||
- **Sensor check:** per geophone `TestFreq`, `TestRatio`, `TestResults`; mic
|
||||
`TestFreq`, `TestAmplitude`, `TestResults`.
|
||||
- **`MonitorLog`:** the session's start, stop and status text.
|
||||
- **Data:** waveform `WaveformDataChannels/Data/Row/Cell` (4 cells per
|
||||
sample: Tran, Vert, Long in in/s, MicL in the event's mic units); histogram
|
||||
`HistogramDataIntervals` (a `Time` and a 10-cell `Row` per interval:
|
||||
Tran/Vert/Long peak + freq, geo PVS, MicL psi, dB and freq).
|
||||
|
||||
Value forms the parser must handle: numbers with units in the text (`6.7
|
||||
Volts`, `7.6 Hz.`, `3.0 sec.`, `-0.250 sec`); `>100` (ZC frequency above
|
||||
range; 71,823 files), `N/A` (37,293 files), `OORANGE` (59 files: the channel
|
||||
clipped), `Check` (2,193 files), and XML entities. Two `_XML.XML` details
|
||||
matter:
|
||||
|
||||
- Blastware prints each number to a fixed number of decimals and **rounds
|
||||
halves away from zero** (−0.0625 s prints as −0.063).
|
||||
- The small `<stem>_<ext>.XML` summary next to it uses **decimal commas**.
|
||||
It is not the reference; the `_XML.XML` is.
|
||||
|
||||
## Goals
|
||||
|
||||
- For every Series 3 event file with an XML report, compare **every field the
|
||||
XML carries**, plus every waveform sample and every histogram interval,
|
||||
against SFM's file-only decode.
|
||||
- Give each comparison one verdict: **match**, **mismatch**, **SFM blank**
|
||||
(SFM produced nothing), **accepted difference** (covered by a written
|
||||
carve-out), **no reference** (the XML lacks the field), or **error** (the
|
||||
decode or parse failed).
|
||||
- Produce two outputs:
|
||||
- **A short summary for Brian:** per field, the counts of each verdict and
|
||||
how far we are from done.
|
||||
- **A detailed report for Claude** that groups failures by what the failing
|
||||
events share, so 17,000 mismatches read as "one bug on 2048 sps
|
||||
histograms". It gives example files with Blastware's value and SFM's, and
|
||||
a one-line command to re-run a single event.
|
||||
- **Run again and again.** Each run is compared with the previous one, so a
|
||||
fix shows as numbers moving, and anything that used to match and stops is
|
||||
called out.
|
||||
- Keep the comparison as library code, so ingest can later run it on one
|
||||
event as it arrives (piece 3/4).
|
||||
|
||||
## What counts as "SFM's side"
|
||||
|
||||
The SFM side is **what SFM produces from the event's bytes alone**:
|
||||
|
||||
- **The `Event` that `decode_blastware_bytes` returns when given the bytes and
|
||||
no filename.**
|
||||
- SFM's own download and call-in paths never have a Blastware name.
|
||||
- Today the event type comes only from the filename's extension, so every
|
||||
histogram decodes as "Waveform". The checker reports that as it is: a
|
||||
mismatch until the decoder reads the type from the file (#41). It must
|
||||
not borrow the name to make it match.
|
||||
- **Anything else SFM reads from those bytes outside the decoder**, such as the
|
||||
serial.
|
||||
- Ingest's `sfm/waveform_store._serial_from_bw_bytes` uses the filename to
|
||||
validate what it finds.
|
||||
- Whatever SFM can't get from the bytes alone is "SFM blank".
|
||||
- **Values the codec computes but never puts on the `Event`** count as SFM
|
||||
blank until they are wired through (piece 2). For example, histogram
|
||||
half-periods in `histogram_codec.decode_histogram_body_full` give the
|
||||
per-interval frequency.
|
||||
- **SFM's assumptions included.**
|
||||
- SFM cannot yet read the geophone range from the file, and assumes Normal
|
||||
(10 in/s): `_peaks_from_samples` does, and ingest writes `.h5` with
|
||||
`geo_range="normal"`.
|
||||
- The checker compares what SFM actually produces under that assumption.
|
||||
The range field itself is SFM blank.
|
||||
- So the 35 events recorded on the 1.250 in/s range show as 8× mismatches,
|
||||
not blanks. Example: `T438L713.QP0W` gives PPV 0.015/0.02/0.015 against
|
||||
Blastware's 0.002.
|
||||
- The range is never taken from the reference.
|
||||
|
||||
So the comparison takes an SFM-side record plus the parsed reference. The
|
||||
runner assembles that record from the decoder and any SFM helpers. The
|
||||
comparison itself stays pure codec-library code; only the runner (a lab tool)
|
||||
may import from `sfm/`.
|
||||
|
||||
## The rule for disagreements (decided by Brian)
|
||||
|
||||
**Every mismatch is an SFM bug until shown otherwise.** A mismatch becomes an
|
||||
"accepted difference" only through a written carve-out that names the fields
|
||||
it covers and the rule it applies. Its evidence must not rest on SFM's own
|
||||
output: Blastware contradicting itself, the instrument's own data (counts
|
||||
in the file, the unit's embedded record), a third source (another instrument,
|
||||
a known signal), or Instantel documentation. Each run reports how many events
|
||||
each carve-out covers.
|
||||
|
||||
The carve-out list starts with one entry, already proven in
|
||||
`scratch/verify_against_ascii.py`: **saturation**. On a clipped channel,
|
||||
Blastware clamps its numbers to the range maximum and writes `OORANGE`, while
|
||||
the file holds counts past full scale. Rounding to Blastware's printed
|
||||
precision is a comparison rule, not a carve-out.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **Series 4 / Micromate.** Thor's IDF decode has its own CSV-based check, and
|
||||
the 5,916 Micromate XMLs are noted for a later Series 4 checker.
|
||||
- **Changing what SFM decodes.** The checker reports gaps; filling them is
|
||||
piece 2.
|
||||
- **Wiring the check into ingest, the watcher or Terra-View.** That's pieces
|
||||
3/4. Nothing on prod changes.
|
||||
- **ASCII reports as a reference.** The XML covers every year, including the
|
||||
2025–26 events that have ASCII. The reference is parsed into a shape another
|
||||
report format could fill later, but no ASCII adapter is built now.
|
||||
|
||||
## Anti-goals (would make it a failure even if it runs)
|
||||
|
||||
- **Comparing SFM with Blastware's own numbers.** The SFM side must come only
|
||||
from the event file, through `decode_blastware_bytes` with no report
|
||||
overlay. Nothing from the XML or ASCII report may reach the SFM side.
|
||||
- **Hiding mismatches:** a carve-out without evidence, a tolerance looser
|
||||
than Blastware's printed precision, or blanks counted as matches.
|
||||
- **Wrong conversions:** counts converted to in/s with a range or scale that
|
||||
came from the reference rather than the file. If SFM can't read the range
|
||||
from the file yet, that is a gap to report, not something to borrow.
|
||||
- **A report that only says "N mismatches"** without grouping and examples.
|
||||
It must be usable to find the cause.
|
||||
- **A full run so slow it isn't run after every fix.**
|
||||
|
||||
## Constraints
|
||||
|
||||
- **Hardware:** runs on the dev box (4 cores, ~17 GB free disk after the
|
||||
22 GB XML copy; Brian can add space).
|
||||
- **Read-only:** it never writes to the corpus folders and needs no network.
|
||||
- **Speed:** a full run over all 70,042 events in **under an hour**. A
|
||||
partial run (by serial, year, event type or field group, or a random sample)
|
||||
in **a few minutes**. The setup/notes harness covering ~6 fields took ~4
|
||||
minutes with 4 processes. Samples and intervals add parsing 22 GB of XML.
|
||||
The standard library parses at ~45 MB/s per core (`lxml` is not
|
||||
installed), which fits the budget.
|
||||
- **Codec library purity (ADR 0003):** the codec library stays pure. Bench and
|
||||
lab tools stay out of the production image.
|
||||
- **Results contain customer project names**, so run output is kept outside
|
||||
the repo and never committed.
|
||||
|
||||
## What's decided, and by whom
|
||||
|
||||
**Brian:**
|
||||
- SFM's data comes only from the binary; reports are for checking.
|
||||
- The disagreement rule and carve-outs above.
|
||||
- The two outputs: a summary for him, a detailed report for Claude to diagnose.
|
||||
- Repeated runs with run-to-run comparison.
|
||||
- It lives in seismo-relay, and the comparison is library code.
|
||||
- Series 3 only. Nothing on prod or in Terra-View changes.
|
||||
|
||||
**Claude's calls (correct if wrong):**
|
||||
- The XML is the single reference.
|
||||
- **Placement:**
|
||||
- The XML report parser belongs in the codec library, a sibling of
|
||||
`minimateplus/bw_ascii_report.py`.
|
||||
- The comparison (one decoded `Event` + one parsed report → verdicts per
|
||||
field) is pure and belongs in the codec library too.
|
||||
- The batch runner is a lab tool (`scratch/`), per ADR 0003.
|
||||
- The carve-out list lives in the repo next to the comparison, as code or
|
||||
data the comparison reads, with each entry's evidence written beside it.
|
||||
- **Grouping attributes for the detailed report:**
|
||||
- device model (from `Version`), serial
|
||||
- event type, event year
|
||||
- sample rate, geophone range, mic units/weighting, interval size
|
||||
- whether the setup is named "Standard Recording Setup"
|
||||
- which decoder path produced the samples, where the decoder exposes it
|
||||
- `scratch/verify_bw_fields_against_xml.py` (committed `f46afaf`) is the
|
||||
starting point. It already handles the notes/job-number layout and the
|
||||
rounding rule. The checker replaces it.
|
||||
|
||||
**Left to the builder:**
|
||||
- module, function and file names; the output file formats
|
||||
- how runs are stored and compared
|
||||
- parallelism and any caching of decode or parse results
|
||||
- the CLI shape, as long as the partial-run filters and single-event re-run
|
||||
exist
|
||||
|
||||
## What success looks like
|
||||
|
||||
- **One command** produces the summary and the detailed report for all 70,042
|
||||
events within the time budget.
|
||||
- **The first run reproduces what is known**, which is how we tell the
|
||||
checker is honest:
|
||||
- sample rate, record time, pre-trigger and notes match everywhere
|
||||
- `T438HGTZ.B30W` matches. Its Tran, Vert and MicL end 3 samples before
|
||||
Long, and Blastware's own table does the same: its last rows carry only
|
||||
the Long cell. An earlier harness that compared one channel's length with
|
||||
the table's row count called this a decoder truncation; it was not.
|
||||
- samples and histogram intervals match on the 2025–26 events, as
|
||||
`verify_against_ascii.py` showed, **except the events on the 1.250 in/s
|
||||
range**, which are 8× high (5 of them in 2025–26, 35 in all)
|
||||
- event type mismatches on every histogram, because no filename is given
|
||||
(#41)
|
||||
- job number and the calculated values (ZC frequency, acceleration,
|
||||
displacement, time of peak, sensor check, battery, calibration, trigger
|
||||
levels, range, units, monitor log) show up as SFM blank
|
||||
- the three `#53` files fail loudly as waveform time mismatches, 4 s off.
|
||||
The decoder picks an earlier, false footer and records no
|
||||
`decode_problems`. The `#53` description in
|
||||
`docs/instantel_protocol_reference.md`, which says they decode as
|
||||
histograms, is out of date.
|
||||
- Every non-match group in the detailed report carries example files and a
|
||||
re-run command.
|
||||
- Tests cover the XML parser on real fixture reports with literal expected
|
||||
values, every comparison rule (rounding, `>100`, `N/A`, `OORANGE`,
|
||||
units), carve-out accounting, and a guard that the SFM side never sees the
|
||||
reference.
|
||||
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
minimateplus/bw_xml_report.py — parse Blastware's `_XML.XML` event report.
|
||||
|
||||
Blastware's ACH keeps, in `Sent/`, a full XML report beside each event binary:
|
||||
`<stem>_<ext>_XML.XML` for `<stem>.<ext>`. It carries every field of the event
|
||||
report plus every waveform sample or histogram interval, and DL2's backup holds
|
||||
one for 70,042 Series 3 events back to 2016 (its ASCII reports start in 2025).
|
||||
SFM uses it only to check its own decode, never as data.
|
||||
|
||||
The small `<stem>_<ext>.XML` summary beside it writes decimal commas and is not
|
||||
this file.
|
||||
|
||||
Layout (FileVersion 8.0), as the parser reads it:
|
||||
|
||||
- top-level simple elements, e.g. ``<SampleRate>1024 sps</SampleRate>``
|
||||
- value elements, e.g. ``<TranPPV><Value>0.015</Value><Units>in/s</Units></TranPPV>``
|
||||
- ``<Channels><Channel>Tran</Channel>...</Channels>``
|
||||
- the job number and up to four user notes, between the top-level
|
||||
``<Units>`` and ``<GeoRange>``; each note is tagged with its
|
||||
operator-editable label (``Project``, ``Location``, ``Seis.Loc`` ...) and
|
||||
an empty note is omitted
|
||||
- waveform: ``WaveformDataChannels/Data/Row/Cell``. A row holds only the
|
||||
channels still running: where channels end at different lengths, the last
|
||||
rows have fewer cells
|
||||
- histogram: ``HistogramData`` with ``HistogramDataColumnTitle/ColumnTitle``
|
||||
and ``HistogramDataIntervals``, alternating ``Time`` and ``Row``
|
||||
|
||||
Cell and value text is kept exactly as printed (``">100"``, ``"N/A"``,
|
||||
``"OORANGE"``, ``"6.7 Volts"``); interpreting it is the comparison's job.
|
||||
|
||||
Pure: no I/O beyond reading the file passed to `parse_xml_report_file`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import xml.etree.ElementTree as ET
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
|
||||
|
||||
@dataclass
|
||||
class XmlReport:
|
||||
scalars: dict[str, str]
|
||||
units: dict[str, str]
|
||||
event_units: Optional[str]
|
||||
channels: list[str]
|
||||
job_number: Optional[str]
|
||||
notes: list[tuple[str, str]]
|
||||
sample_rows: Optional[list[list[str]]]
|
||||
interval_columns: Optional[list[str]]
|
||||
intervals: Optional[list[tuple[str, list[str]]]]
|
||||
|
||||
|
||||
def _text(el: ET.Element) -> str:
|
||||
return (el.text or "").strip()
|
||||
|
||||
|
||||
def _cells(row: ET.Element) -> list[str]:
|
||||
return [_text(c) for c in row.findall("Cell")]
|
||||
|
||||
|
||||
def parse_xml_report(data: bytes) -> XmlReport:
|
||||
"""Parse the bytes of an `_XML.XML` event report. Raises ValueError when
|
||||
they are not well-formed XML (a truncated file, for one)."""
|
||||
try:
|
||||
root = ET.fromstring(data)
|
||||
except ET.ParseError as exc:
|
||||
raise ValueError(f"not a well-formed XML report: {exc}") from exc
|
||||
|
||||
scalars: dict[str, str] = {}
|
||||
units: dict[str, str] = {}
|
||||
event_units: Optional[str] = None
|
||||
channels: list[str] = []
|
||||
job_number: Optional[str] = None
|
||||
notes: list[tuple[str, str]] = []
|
||||
sample_rows: Optional[list[list[str]]] = None
|
||||
interval_columns: Optional[list[str]] = None
|
||||
intervals: Optional[list[tuple[str, list[str]]]] = None
|
||||
|
||||
in_notes = False
|
||||
for el in root:
|
||||
tag = el.tag
|
||||
if tag == "Units" and len(el) == 0:
|
||||
event_units = _text(el)
|
||||
scalars[tag] = event_units
|
||||
in_notes = True
|
||||
continue
|
||||
if tag == "GeoRange":
|
||||
in_notes = False
|
||||
if in_notes and len(el) == 0:
|
||||
# Job number and user notes: never scalars, so the comparison
|
||||
# scores each once.
|
||||
if tag == "JobNumber":
|
||||
job_number = _text(el)
|
||||
elif _text(el):
|
||||
notes.append((tag, _text(el)))
|
||||
continue
|
||||
if tag == "Channels":
|
||||
channels = [_text(c) for c in el.findall("Channel")]
|
||||
elif tag == "WaveformDataChannels":
|
||||
data_el = el.find("Data")
|
||||
if data_el is not None:
|
||||
sample_rows = [_cells(r) for r in data_el.findall("Row")]
|
||||
elif tag == "HistogramData":
|
||||
titles = el.find("HistogramDataColumnTitle")
|
||||
interval_columns = ([" ".join(_text(t).split()) for t in titles.findall("ColumnTitle")]
|
||||
if titles is not None else [])
|
||||
body = el.find("HistogramDataIntervals")
|
||||
intervals = []
|
||||
time: Optional[str] = None
|
||||
for child in (body if body is not None else []):
|
||||
if child.tag == "Time":
|
||||
time = _text(child)
|
||||
elif child.tag == "Row":
|
||||
intervals.append((time or "", _cells(child)))
|
||||
time = None
|
||||
elif el.find("Value") is not None:
|
||||
scalars[tag] = _text(el.find("Value"))
|
||||
u = el.find("Units")
|
||||
if u is not None:
|
||||
units[tag] = _text(u)
|
||||
elif len(el) == 0:
|
||||
scalars[tag] = _text(el)
|
||||
|
||||
return XmlReport(
|
||||
scalars=scalars, units=units, event_units=event_units, channels=channels,
|
||||
job_number=job_number, notes=notes, sample_rows=sample_rows,
|
||||
interval_columns=interval_columns, intervals=intervals,
|
||||
)
|
||||
|
||||
|
||||
def parse_xml_report_file(path: Union[str, Path]) -> XmlReport:
|
||||
return parse_xml_report(Path(path).read_bytes())
|
||||
@@ -0,0 +1,302 @@
|
||||
"""
|
||||
minimateplus/decode_check.py — SFM's file-only decode, set beside Blastware's
|
||||
report of the same event, field by field.
|
||||
|
||||
The decode checker's core (`docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md`).
|
||||
SFM's side comes from the event bytes alone, through
|
||||
`decode_blastware_bytes(raw, name=None)`: no filename, because SFM's own
|
||||
download and call-in paths have none, and no report overlay. Nothing from the
|
||||
reference reaches it. SFM's own assumptions stay in -- geophone counts become
|
||||
in/s at the Normal range -- because the point is to judge what SFM produces.
|
||||
|
||||
Pure: no I/O, and no import from `sfm/`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Optional, Sequence
|
||||
|
||||
from .bw_xml_report import XmlReport
|
||||
from .event_file_io import _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_FS_PSI, decode_blastware_bytes
|
||||
from .models import Event
|
||||
from .waveform_codec import mic_count_to_db
|
||||
|
||||
# SFM's conversion: it cannot yet read the geophone range from the file, and
|
||||
# assumes Normal (10 in/s full scale = 32000 counts).
|
||||
GEO_IPS_PER_COUNT: float = _GEO_NORMAL_FS_INS / _GEO_INT16_FS
|
||||
|
||||
_CHANNELS = ("Tran", "Vert", "Long", "MicL")
|
||||
_EVENT_TYPE = {"Waveform": "Full Waveform", "Histogram": "Full Histogram"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class SfmSide:
|
||||
event: Event
|
||||
values: dict[str, object] # reference tag -> SFM's value; absent or None = blank
|
||||
notes: list[str] # non-empty user-note slots, in order
|
||||
job_number: Optional[str] # None until the decoder reads it
|
||||
channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order
|
||||
counts: dict[str, list[int]] # waveform samples or histogram interval peaks
|
||||
|
||||
|
||||
def sfm_side(raw: bytes) -> SfmSide:
|
||||
"""What SFM makes of an event from its bytes alone."""
|
||||
ev = decode_blastware_bytes(raw, name=None)
|
||||
counts = {ch: list((ev.raw_samples or {}).get(ch) or []) for ch in _CHANNELS}
|
||||
pv, pi, ts = ev.peak_values, ev.project_info, ev.timestamp
|
||||
|
||||
values: dict[str, object] = {
|
||||
"EventType": _EVENT_TYPE.get(ev.record_type, ev.record_type),
|
||||
"SampleRate": ev.sample_rate,
|
||||
"RecordTime": ev.rectime_seconds,
|
||||
"Pre-triggerLength": (-ev.pretrig_samples / ev.sample_rate
|
||||
if ev.pretrig_samples is not None and ev.sample_rate else None),
|
||||
# SFM's interval count is its decoded entry count; the reference
|
||||
# carries this field for histograms only.
|
||||
"NumberofIntervals": len(counts["Tran"]) or None,
|
||||
}
|
||||
if ts is not None:
|
||||
date = f"{ts.year:04d}-{ts.month:02d}-{ts.day:02d}"
|
||||
time = f"{ts.hour:02d}:{ts.minute:02d}:{ts.second:02d}"
|
||||
# The event's time, under both of Blastware's names for it, so a time
|
||||
# is judged as a time even while the type is wrong (#41).
|
||||
values.update(EventDate=date, EventTime=time,
|
||||
HistogramStartDate=date, HistogramStartTime=time)
|
||||
if pv is not None:
|
||||
values.update(TranPPV=pv.tran, VertPPV=pv.vert, LongPPV=pv.long,
|
||||
PeakVectorSum=pv.peak_vector_sum)
|
||||
if counts["MicL"]:
|
||||
values["MicLPSPL dB(L)"] = mic_count_to_db(max(abs(c) for c in counts["MicL"]))
|
||||
values["MicLPSPL psi(L)"] = pv.micl if pv is not None else None
|
||||
|
||||
return SfmSide(
|
||||
event=ev,
|
||||
values=values,
|
||||
notes=[v for v in (pi.project, pi.client, pi.operator, pi.sensor_location) if v]
|
||||
if pi is not None else [],
|
||||
job_number=None,
|
||||
channels=[ch for ch in _CHANNELS if counts[ch]],
|
||||
counts=counts,
|
||||
)
|
||||
|
||||
|
||||
# ── The comparison ──────────────────────────────────────────────────────────
|
||||
|
||||
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
|
||||
|
||||
# Not event data: the report's own format version and Blastware's file name.
|
||||
_NOT_COMPARED = {"FileVersion", "FileName"}
|
||||
_NUMBER = re.compile(r"^\s*(-?\d+(?:\.\d+)?)")
|
||||
_GEO = ("Tran", "Vert", "Long")
|
||||
|
||||
|
||||
@dataclass
|
||||
class FieldResult:
|
||||
field: str
|
||||
verdict: str
|
||||
bw: Optional[str]
|
||||
sfm: Optional[str]
|
||||
detail: str = ""
|
||||
carveout: Optional[str] = None
|
||||
|
||||
|
||||
def _printed_number(printed: str) -> Optional[tuple[float, int]]:
|
||||
m = _NUMBER.match(printed)
|
||||
if not m:
|
||||
return None
|
||||
num = m.group(1)
|
||||
return float(num), (len(num) - num.index(".") - 1 if "." in num else 0)
|
||||
|
||||
|
||||
def matches_printed(value: float, printed: str) -> bool:
|
||||
"""True when `value` prints as `printed` at Blastware's precision. Blastware
|
||||
rounds halves away from zero (-0.0625 s -> -0.063), so half a unit of the last
|
||||
printed decimal either way is a match."""
|
||||
p = _printed_number(printed)
|
||||
return p is not None and abs(value - p[0]) <= 0.5 * 10 ** -p[1] + 1e-9
|
||||
|
||||
|
||||
def _render(value: object, printed: str) -> str:
|
||||
p = _printed_number(printed)
|
||||
if p is not None and isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
return f"{value:.{p[1]}f}"
|
||||
return str(value)
|
||||
|
||||
|
||||
def _same_text(a: object, b: str) -> bool:
|
||||
return " ".join(str(a).split()) == " ".join(b.split())
|
||||
|
||||
|
||||
def _mic_converter(ref: XmlReport) -> Optional[Callable[[int], float]]:
|
||||
units = ref.event_units or ""
|
||||
if "dB(L)" in units:
|
||||
return mic_count_to_db
|
||||
if "psi(L)" in units:
|
||||
return lambda c: c * _MIC_FS_PSI
|
||||
return None
|
||||
|
||||
|
||||
def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> FieldResult:
|
||||
if not printed.strip() or printed.strip() == "N/A":
|
||||
return FieldResult(tag, "no_reference", printed, None)
|
||||
if tag == "MicLPSPL":
|
||||
units = ref.event_units or ""
|
||||
key = ("MicLPSPL dB(L)" if "dB(L)" in units else
|
||||
"MicLPSPL psi(L)" if "psi(L)" in units else None)
|
||||
value = sfm.values.get(key) if key else None
|
||||
else:
|
||||
value = sfm.values.get(tag)
|
||||
if value is None:
|
||||
return FieldResult(tag, "sfm_blank", printed, None)
|
||||
if printed.startswith(">"):
|
||||
# ZC frequency above range: SFM agrees only by setting its flag.
|
||||
flag = getattr(sfm.event.peak_values, tag[:-len("ZCFreq")].lower() + "_zc_above_range", False)
|
||||
return FieldResult(tag, "match" if flag else "mismatch", printed, str(value))
|
||||
if printed == "OORANGE":
|
||||
return FieldResult(tag, "mismatch", printed, str(value))
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool) and _printed_number(printed):
|
||||
ok = matches_printed(float(value), printed)
|
||||
else:
|
||||
ok = _same_text(value, printed)
|
||||
return FieldResult(tag, "match" if ok else "mismatch", printed, _render(value, printed))
|
||||
|
||||
|
||||
def _cell_diff(value: float, printed: str) -> Optional[float]:
|
||||
"""|value - printed| when the cell disagrees, else None; inf for a cell that
|
||||
is not a number."""
|
||||
p = _printed_number(printed)
|
||||
if p is None:
|
||||
return float("inf")
|
||||
d = abs(value - p[0])
|
||||
return d if d > 0.5 * 10 ** -p[1] + 1e-9 else None
|
||||
|
||||
|
||||
def _series_result(field: str, n_bw: int, n_sfm: int, diffs: list[tuple[int, float]],
|
||||
row_len: int) -> FieldResult:
|
||||
first = diffs[0][0] if diffs else None
|
||||
max_abs = max((d for _, d in diffs), default=0.0)
|
||||
ok = not diffs and not row_len
|
||||
return FieldResult(
|
||||
field, "match" if ok else "mismatch", f"{n_bw} rows", f"{n_sfm} values",
|
||||
f"rows={n_bw} sfm={n_sfm} differing={len(diffs)} row_length_disagreements={row_len} "
|
||||
f"first_diff={first} max_abs={max_abs:.4g}",
|
||||
)
|
||||
|
||||
|
||||
def _sample_converters(ref: XmlReport) -> dict[str, Callable[[int], float]]:
|
||||
convert: dict[str, Callable[[int], float]] = {ch: (lambda c: c * GEO_IPS_PER_COUNT) for ch in _GEO}
|
||||
mic = _mic_converter(ref)
|
||||
if mic is not None:
|
||||
convert["MicL"] = mic
|
||||
return convert
|
||||
|
||||
|
||||
def _interval_converter(title: str) -> Optional[Callable[[int], float]]:
|
||||
"""SFM keeps each interval's peaks; it drops their frequencies and geo PVS."""
|
||||
ch, _, rest = title.partition(" ")
|
||||
if rest.startswith("Peak") and ch in _GEO:
|
||||
return lambda c: c * GEO_IPS_PER_COUNT
|
||||
if ch == "MicL" and rest == "Peak dB(L)":
|
||||
return mic_count_to_db
|
||||
if ch == "MicL" and rest == "Peak psi(L)":
|
||||
return lambda c: c * _MIC_FS_PSI
|
||||
return None
|
||||
|
||||
|
||||
def series_pairs(sfm: SfmSide, ref: XmlReport,
|
||||
field: str) -> Optional[tuple[list[tuple[int, str, float]], int]]:
|
||||
"""For a `samples.<ch>` or `intervals.<column>` field: the (index, printed
|
||||
cell, SFM value) pairs and the count of row-length disagreements, or None
|
||||
when SFM has no conversion or no data for it.
|
||||
|
||||
A waveform row holds only the channels still running, so row j's cells
|
||||
pair, in order, with the reference channels SFM has more than j samples of;
|
||||
a row whose cell count differs is a disagreement for every channel."""
|
||||
if field.startswith("samples."):
|
||||
ch = field[len("samples."):]
|
||||
convert = _sample_converters(ref).get(ch)
|
||||
counts = sfm.counts.get(ch, [])
|
||||
if convert is None or not counts:
|
||||
return None
|
||||
rows = ref.sample_rows or []
|
||||
lens = {c: len(sfm.counts.get(c, [])) for c in ref.channels}
|
||||
pairs, row_len = [], 0
|
||||
for j, row in enumerate(rows):
|
||||
running = [c for c in ref.channels if lens[c] > j]
|
||||
if len(running) != len(row):
|
||||
row_len += 1
|
||||
elif ch in running:
|
||||
pairs.append((j, row[running.index(ch)], convert(counts[j])))
|
||||
return pairs, row_len + max(0, len(counts) - len(rows))
|
||||
if field.startswith("intervals."):
|
||||
title = field[len("intervals."):]
|
||||
columns = ref.interval_columns or []
|
||||
convert = _interval_converter(title)
|
||||
counts = sfm.counts.get(title.partition(" ")[0], [])
|
||||
if convert is None or not counts or title not in columns:
|
||||
return None
|
||||
i = columns.index(title)
|
||||
cells = [row[i] if i < len(row) else "" for _, row in (ref.intervals or [])]
|
||||
pairs = [(j, cell, convert(c)) for j, (cell, c) in enumerate(zip(cells, counts))]
|
||||
return pairs, abs(len(cells) - len(counts))
|
||||
return None
|
||||
|
||||
|
||||
def _compare_series(field: str, n_bw: int, sfm: SfmSide, ref: XmlReport) -> FieldResult:
|
||||
got = series_pairs(sfm, ref, field)
|
||||
if got is None:
|
||||
return FieldResult(field, "sfm_blank", f"{n_bw} rows", None)
|
||||
pairs, row_len = got
|
||||
diffs = [(j, d) for j, cell, v in pairs if (d := _cell_diff(v, cell)) is not None]
|
||||
n_sfm = len(sfm.counts.get(field.split(".", 1)[1].partition(" ")[0], []))
|
||||
return _series_result(field, n_bw, n_sfm, diffs, row_len)
|
||||
|
||||
|
||||
def _compare_samples(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
||||
"""One result per reference channel."""
|
||||
n = len(ref.sample_rows or [])
|
||||
return [_compare_series(f"samples.{ch}", n, sfm, ref) for ch in ref.channels]
|
||||
|
||||
|
||||
def _compare_intervals(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
||||
"""One result per column, plus the interval times, which SFM does not keep."""
|
||||
n = len(ref.intervals or [])
|
||||
return ([FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)]
|
||||
+ [_compare_series(f"intervals.{t}", n, sfm, ref) for t in ref.interval_columns or []])
|
||||
|
||||
|
||||
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]:
|
||||
"""Every field Blastware's report carries, set against what SFM produced.
|
||||
A mismatch a carve-out covers and applies to becomes `accepted`."""
|
||||
out = [_compare_scalar(tag, text, sfm, ref)
|
||||
for tag, text in ref.scalars.items() if tag not in _NOT_COMPARED]
|
||||
|
||||
ref_notes = [v for _, v in ref.notes]
|
||||
if ref_notes and not sfm.notes:
|
||||
out.append(FieldResult("notes", "sfm_blank", " | ".join(ref_notes), None))
|
||||
else:
|
||||
ok = [" ".join(v.split()) for v in ref_notes] == [" ".join(v.split()) for v in sfm.notes]
|
||||
out.append(FieldResult("notes", "match" if ok else "mismatch",
|
||||
" | ".join(ref_notes), " | ".join(sfm.notes)))
|
||||
if ref.job_number is not None:
|
||||
out.append(FieldResult("JobNumber", "sfm_blank", ref.job_number, None)
|
||||
if sfm.job_number is None else
|
||||
FieldResult("JobNumber", "match" if _same_text(sfm.job_number, ref.job_number)
|
||||
else "mismatch", ref.job_number, sfm.job_number))
|
||||
out.append(FieldResult("Channels", "match" if ref.channels == sfm.channels else "mismatch",
|
||||
" ".join(ref.channels), " ".join(sfm.channels)))
|
||||
if ref.sample_rows is not None:
|
||||
out.extend(_compare_samples(sfm, ref))
|
||||
if ref.intervals is not None:
|
||||
out.extend(_compare_intervals(sfm, ref))
|
||||
|
||||
for r in out:
|
||||
if r.verdict != "mismatch":
|
||||
continue
|
||||
for co in carveouts:
|
||||
covered = any(r.field == f or (f.endswith(".") and r.field.startswith(f)) for f in co.fields)
|
||||
if covered and co.applies(sfm, ref, r):
|
||||
r.verdict, r.carveout = "accepted", co.id
|
||||
break
|
||||
return out
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
minimateplus/decode_check_carveouts.py — the proven ways Blastware's report
|
||||
differs from the instrument's data.
|
||||
|
||||
Every disagreement between SFM and Blastware is SFM's bug until shown otherwise.
|
||||
A carve-out is that showing: the fields it covers, the rule it applies, and
|
||||
evidence that does not rest on SFM's own output -- Blastware contradicting
|
||||
itself, the instrument's own data, a third source, or Instantel documentation.
|
||||
`compare` turns a covered mismatch into `accepted` only when the rule holds,
|
||||
and every run counts the events each carve-out covers.
|
||||
|
||||
Pure: no I/O, and no import from `sfm/`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
from .bw_xml_report import XmlReport
|
||||
from .decode_check import FieldResult, SfmSide, _printed_number, series_pairs, matches_printed
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Carveout:
|
||||
id: str
|
||||
fields: tuple[str, ...] # exact names, or prefixes ending in "."
|
||||
evidence: str
|
||||
applies: Callable[[SfmSide, XmlReport, FieldResult], bool]
|
||||
|
||||
|
||||
_TOL = 0.0006
|
||||
|
||||
|
||||
def _at_ceiling(value: float, r: float) -> bool:
|
||||
"""SFM's value sits at the range ceiling: a decoder unit or two past nominal
|
||||
full scale is the clipped count itself (32016 = 10.005 in/s). An 8x
|
||||
Sensitive-range value is far above the band and does not qualify."""
|
||||
return r - _TOL <= abs(value) <= r * 1.01
|
||||
|
||||
|
||||
def _clamped(printed: str, r: float) -> bool:
|
||||
if printed.strip() == "OORANGE":
|
||||
return True
|
||||
p = _printed_number(printed)
|
||||
return p is not None and abs(p[0]) >= r - _TOL
|
||||
|
||||
|
||||
def _saturation(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
|
||||
try:
|
||||
r = float(ref.scalars["GeoRange"])
|
||||
except (KeyError, ValueError):
|
||||
return False
|
||||
if res.field in ("TranPPV", "VertPPV", "LongPPV"):
|
||||
v = sfm.values.get(res.field)
|
||||
return v is not None and _clamped(res.bw or "", r) and _at_ceiling(float(v), r)
|
||||
if res.field == "PeakVectorSum":
|
||||
# A vector sum can exceed the range without any clipping, so only
|
||||
# Blastware's OORANGE counts. SFM's sum is bounded by three channels at
|
||||
# the ceiling (11.55 on T438HGTZ.B30W), and a channel Blastware itself
|
||||
# clamped must be the one SFM has at the ceiling -- an unclipped channel
|
||||
# read 8x high on the Sensitive range does not qualify.
|
||||
pvs = sfm.values.get("PeakVectorSum")
|
||||
return ((res.bw or "").strip() == "OORANGE" and pvs is not None
|
||||
and r - _TOL <= float(pvs) <= 3 ** 0.5 * r * 1.01
|
||||
and any(_clamped(ref.scalars.get(f, ""), r) and sfm.values.get(f) is not None
|
||||
and _at_ceiling(float(sfm.values[f]), r)
|
||||
for f in ("TranPPV", "VertPPV", "LongPPV")))
|
||||
got = series_pairs(sfm, ref, res.field)
|
||||
if got is None or got[1]:
|
||||
return False
|
||||
differing = [(cell, v) for _, cell, v in got[0] if not matches_printed(v, cell)]
|
||||
return bool(differing) and all(
|
||||
_clamped(cell, r) and _at_ceiling(v, r)
|
||||
and (cell.strip() == "OORANGE" or (v >= 0) == (_printed_number(cell)[0] >= 0))
|
||||
for cell, v in differing)
|
||||
|
||||
|
||||
SATURATION = Carveout(
|
||||
id="saturation",
|
||||
fields=("TranPPV", "VertPPV", "LongPPV", "PeakVectorSum",
|
||||
"samples.Tran", "samples.Vert", "samples.Long",
|
||||
"intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s"),
|
||||
evidence=("Blastware clamps a clipped channel to the range maximum and prints OORANGE; "
|
||||
"the file holds counts past full scale (32016 counts = 10.005 in/s observed). "
|
||||
"scratch/verify_against_ascii.py, 2026-08-28."),
|
||||
applies=_saturation,
|
||||
)
|
||||
|
||||
CARVEOUTS: tuple[Carveout, ...] = (SATURATION,)
|
||||
@@ -0,0 +1,243 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
The Series 3 decode checker: SFM's file-only decode of every event, compared
|
||||
with Blastware's `_XML.XML` report of the same event.
|
||||
|
||||
python scratch/check_s3_decode.py <binaries dir> <xml dir> [options]
|
||||
|
||||
Each event is decoded the way SFM ingest does, from its bytes alone -- no
|
||||
filename, no report -- and every field, waveform sample and histogram interval
|
||||
is compared (minimateplus/decode_check.py). Results go to a run folder outside
|
||||
the repo, because they carry customer project names:
|
||||
|
||||
~/dl2-archive/checker-runs/<YYYYmmdd-HHMMSS>/
|
||||
results.jsonl.gz one line per event: file, attrs, results rows
|
||||
run.json args, commit, event count, wall time
|
||||
|
||||
Partial runs: --serial BE9441, --year 2024, --type W|H, --field samples.,
|
||||
--sample 2000 [--seed K]. Spec:
|
||||
docs/superpowers/specs/2026-10-29-s3-decode-checker-design.md.
|
||||
|
||||
A lab tool (ADR 0003): it may import from sfm/; the comparison it runs may not.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
_REPO = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(_REPO))
|
||||
|
||||
from minimateplus.bw_xml_report import XmlReport, parse_xml_report_file # noqa: E402
|
||||
from minimateplus.decode_check import compare, sfm_side # noqa: E402
|
||||
from minimateplus.decode_check_carveouts import CARVEOUTS # noqa: E402
|
||||
from scratch import decode_check_report as report # noqa: E402
|
||||
|
||||
RUNS_DIR = Path.home() / "dl2-archive" / "checker-runs"
|
||||
_BIN = re.compile(r"^[A-Z]\d{3}[0-9A-Z]{4}\.[0-9A-Z]{2}0[WH]$", re.I)
|
||||
_MODEL = re.compile(r"^V\s+\S+\s+(.*)$")
|
||||
_EPOCH = datetime(1985, 1, 1)
|
||||
|
||||
|
||||
def find_pairs(bin_dir: Path, xml_dir: Path) -> list[tuple[str, Path, Optional[Path]]]:
|
||||
"""(basename, binary, XML report or None) for every Series 3 event file
|
||||
under `bin_dir`, deduped by basename -- an ACH folder's Sent/ mirrors its
|
||||
root."""
|
||||
xmls = {p.name.upper(): p for p in Path(xml_dir).iterdir() if p.is_file()}
|
||||
seen: dict[str, tuple[str, Path]] = {}
|
||||
for root, _, files in os.walk(bin_dir):
|
||||
for f in files:
|
||||
if _BIN.match(f) and f.upper() not in seen:
|
||||
seen[f.upper()] = (f, Path(root) / f)
|
||||
out = []
|
||||
for key in sorted(seen):
|
||||
name, path = seen[key]
|
||||
stem, ext = name.split(".")
|
||||
out.append((name, path, xmls.get(f"{stem}_{ext}_XML.XML".upper())))
|
||||
return out
|
||||
|
||||
|
||||
def event_attrs(name: str, ref: XmlReport, raw: bytes) -> dict[str, str]:
|
||||
"""The keys failures are grouped by -- all from the reference or the file."""
|
||||
s = ref.scalars
|
||||
m = _MODEL.match(s.get("Version", ""))
|
||||
date = s.get("EventDate") or s.get("HistogramStartDate") or ""
|
||||
return {
|
||||
"model": m.group(1) if m else s.get("Version", "?"),
|
||||
"serial": s.get("SerialNumber", "?"),
|
||||
"type": s.get("EventType", "?"),
|
||||
"year": date[:4] or "?",
|
||||
"sample_rate": s.get("SampleRate", "?").split(" ")[0],
|
||||
"range": s.get("GeoRange", "?"),
|
||||
"mic_units": ref.event_units or "?",
|
||||
"interval": s.get("IntervalSize", "-"),
|
||||
"setup_standard": "yes" if b"Standard Recording Setup" in raw else "no",
|
||||
}
|
||||
|
||||
|
||||
def check_event(name: str, bin_path: str, xml_path: Optional[str]) -> dict:
|
||||
"""One event: its grouping attrs and one row per compared field. A missing
|
||||
reference or any failure is a single row, so a run never stops on one file."""
|
||||
if xml_path is None:
|
||||
return {"file": name, "attrs": {},
|
||||
"results": [["event", "no_reference", None, None, "no XML report", None]]}
|
||||
try:
|
||||
raw = Path(bin_path).read_bytes()
|
||||
ref = parse_xml_report_file(xml_path)
|
||||
rows = compare(sfm_side(raw), ref, CARVEOUTS)
|
||||
return {"file": name, "attrs": event_attrs(name, ref, raw),
|
||||
"results": [[r.field, r.verdict, r.bw, r.sfm, r.detail, r.carveout] for r in rows]}
|
||||
except Exception as exc: # noqa: BLE001 -- one bad file must not stop a run
|
||||
return {"file": name, "attrs": {},
|
||||
"results": [["event", "error", None, None, repr(exc)[:300], None]]}
|
||||
|
||||
|
||||
def _check_pair(pair: tuple[str, str, Optional[str]]) -> dict:
|
||||
return check_event(*pair)
|
||||
|
||||
|
||||
def _quiet() -> None:
|
||||
logging.disable(logging.CRITICAL)
|
||||
|
||||
|
||||
def _filename_prefix(serial: str) -> str:
|
||||
"""BE9441 -> K441: the prefix Blastware's filenames encode a serial as."""
|
||||
num = int(re.sub(r"\D", "", serial))
|
||||
return f"{chr(ord('B') + num // 1000)}{num % 1000:03d}"
|
||||
|
||||
|
||||
def _filename_year(name: str) -> int:
|
||||
stem, ext = name.upper().split(".")
|
||||
return (_EPOCH + timedelta(seconds=int(stem[4:8], 36) * 1296 + int(ext[:2], 36))).year
|
||||
|
||||
|
||||
def _git_head() -> Optional[str]:
|
||||
try:
|
||||
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=_REPO, capture_output=True,
|
||||
text=True, check=True).stdout.strip()
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return None
|
||||
|
||||
|
||||
_SCOPE = ("bin_dir", "xml_dir", "serial", "year", "type", "field", "sample", "seed")
|
||||
|
||||
|
||||
def _scope(args: dict) -> dict:
|
||||
return {k: args.get(k) for k in _SCOPE}
|
||||
|
||||
|
||||
def _previous_run(out_dir: Path, args: dict) -> Optional[Path]:
|
||||
"""The newest other completed run (run.json written) of the same scope in
|
||||
the runs folder -- only for runs kept there. A sample or a one-serial run
|
||||
is no baseline for a full run, nor the other way round."""
|
||||
if out_dir.parent.resolve() != RUNS_DIR.resolve():
|
||||
return None
|
||||
want = _scope(args)
|
||||
for p in sorted(RUNS_DIR.iterdir(), reverse=True):
|
||||
if not p.is_dir() or p.resolve() == out_dir.resolve():
|
||||
continue
|
||||
try:
|
||||
if _scope(json.loads((p / "run.json").read_text())["args"]) == want:
|
||||
return p
|
||||
except (OSError, KeyError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _print_one(name: str, pairs: list[tuple[str, Path, Optional[Path]]]) -> int:
|
||||
"""--file: check one event and print its table; no run folder."""
|
||||
match = [p for p in pairs if p[0].upper() == name.upper()]
|
||||
if not match:
|
||||
print(f"{name}: no such event file under the binaries folder", file=sys.stderr)
|
||||
return 1
|
||||
n, b, x = match[0]
|
||||
ev = check_event(n, str(b), str(x) if x else None)
|
||||
print(f"{n} {ev['attrs']}")
|
||||
print(f"{'field':30s} {'verdict':12s} {'Blastware':30s} {'SFM':30s} detail")
|
||||
for field, verdict, bw, sfm, detail, carveout in ev["results"]:
|
||||
note = f"{detail} {('[' + carveout + ']') if carveout else ''}".strip()
|
||||
print(f"{field:30.30s} {verdict:12s} {str(bw):30.30s} {str(sfm):30.30s} {note}")
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: Optional[list[str]] = None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("bin_dir", type=Path)
|
||||
ap.add_argument("xml_dir", type=Path)
|
||||
ap.add_argument("--out", type=Path, help=f"run folder (default {RUNS_DIR}/<timestamp>)")
|
||||
ap.add_argument("--serial", action="append", default=[], help="e.g. BE9441; repeatable")
|
||||
ap.add_argument("--year", action="append", type=int, default=[], help="event year; repeatable")
|
||||
ap.add_argument("--type", choices=("W", "H"), help="waveforms or histograms only")
|
||||
ap.add_argument("--field", action="append", default=[], help="keep result rows whose field starts with this")
|
||||
ap.add_argument("--sample", type=int, help="check a random sample of N events")
|
||||
ap.add_argument("--seed", type=int, default=0)
|
||||
ap.add_argument("--jobs", type=int, default=os.cpu_count() or 1)
|
||||
ap.add_argument("--file", help="check one event and print its table")
|
||||
ap.add_argument("--compare-to", type=Path, help="an earlier run folder to diff against")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
started = time.monotonic()
|
||||
pairs = find_pairs(args.bin_dir, args.xml_dir)
|
||||
if args.file:
|
||||
return _print_one(args.file, pairs)
|
||||
if args.serial:
|
||||
prefixes = tuple(_filename_prefix(s) for s in args.serial)
|
||||
pairs = [p for p in pairs if p[0].upper().startswith(prefixes)]
|
||||
if args.year:
|
||||
pairs = [p for p in pairs if _filename_year(p[0]) in args.year]
|
||||
if args.type:
|
||||
pairs = [p for p in pairs if p[0].upper().endswith(args.type)]
|
||||
if args.sample is not None and args.sample < len(pairs):
|
||||
pairs = sorted(random.Random(args.seed).sample(pairs, args.sample))
|
||||
|
||||
out_dir = args.out or RUNS_DIR / datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
work = [(n, str(b), str(x) if x else None) for n, b, x in pairs]
|
||||
|
||||
_quiet()
|
||||
if args.jobs <= 1:
|
||||
results = map(_check_pair, work)
|
||||
pool = None
|
||||
else:
|
||||
pool = ProcessPoolExecutor(args.jobs, initializer=_quiet)
|
||||
results = pool.map(_check_pair, work, chunksize=64)
|
||||
try:
|
||||
with gzip.open(out_dir / "results.jsonl.gz", "wt", encoding="utf-8") as fh:
|
||||
for ev in results:
|
||||
if args.field:
|
||||
ev["results"] = [r for r in ev["results"] if r[0].startswith(tuple(args.field))]
|
||||
fh.write(json.dumps(ev) + "\n")
|
||||
finally:
|
||||
if pool is not None:
|
||||
pool.shutdown()
|
||||
|
||||
run = {"args": {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()},
|
||||
"commit": _git_head(), "events": len(work),
|
||||
"seconds": round(time.monotonic() - started, 1)}
|
||||
(out_dir / "run.json").write_text(json.dumps(run, indent=2))
|
||||
agg = report.aggregate(out_dir / "results.jsonl.gz")
|
||||
prev = args.compare_to or _previous_run(out_dir, run["args"])
|
||||
if prev is not None and (prev / "results.jsonl.gz").exists():
|
||||
chg = report.compare_runs(prev / "results.jsonl.gz", out_dir / "results.jsonl.gz")
|
||||
report.write_changes(chg, out_dir / "changes.md")
|
||||
agg["regressions"] = len(chg["regressions"])
|
||||
report.write_summary(agg, out_dir / "summary.md")
|
||||
report.write_details(agg, out_dir / "details.json")
|
||||
print(out_dir)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,235 @@
|
||||
"""
|
||||
Reports for the Series 3 decode checker (scratch/check_s3_decode.py).
|
||||
|
||||
From a run's results.jsonl.gz:
|
||||
|
||||
summary.md for Brian: per field, how many events got each verdict; how many
|
||||
fields fully match; non-matches by event year; carve-out counts
|
||||
details.json for Claude: each non-matching (field, verdict) with the event
|
||||
attributes its failures concentrate in, and example events, each
|
||||
with a command that re-runs just that event
|
||||
|
||||
Streams the results file and holds only counters and a capped example list.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import json
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
VERDICTS = ("match", "mismatch", "sfm_blank", "accepted", "no_reference", "error")
|
||||
_NOT_DONE = ("mismatch", "sfm_blank", "error")
|
||||
_GROUP_SHARE = 0.10 # an attribute value is shown when it holds >= 10% of a failure
|
||||
_CONCENTRATED = 0.95 # ... and flagged when nearly every compared event with it fails
|
||||
_EXAMPLES = 8
|
||||
_KEEP = 60 # candidate examples kept per failure while streaming
|
||||
|
||||
|
||||
def _run_dirs(results_path: Path) -> tuple[str, str]:
|
||||
run = results_path.parent / "run.json"
|
||||
try:
|
||||
args = json.loads(run.read_text())["args"]
|
||||
return args["bin_dir"], args["xml_dir"]
|
||||
except (OSError, KeyError, ValueError):
|
||||
return "<bin_dir>", "<xml_dir>"
|
||||
|
||||
|
||||
def aggregate(results_path: Path) -> dict:
|
||||
fields: dict[str, Counter] = defaultdict(Counter)
|
||||
by_year: dict[str, Counter] = defaultdict(Counter)
|
||||
compared: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
|
||||
failing: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
|
||||
examples: dict[str, list] = defaultdict(list)
|
||||
carveouts: Counter = Counter()
|
||||
events = 0
|
||||
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
ev = json.loads(line)
|
||||
events += 1
|
||||
attrs = ev.get("attrs") or {}
|
||||
covered = set()
|
||||
for field, verdict, bw, sfm, detail, carveout in ev["results"]:
|
||||
fields[field][verdict] += 1
|
||||
if carveout:
|
||||
covered.add(carveout)
|
||||
if verdict != "no_reference":
|
||||
for a, v in attrs.items():
|
||||
compared[field][a][str(v)] += 1
|
||||
if verdict in ("match", "accepted", "no_reference"):
|
||||
continue
|
||||
key = f"{field}|{verdict}"
|
||||
by_year[field][attrs.get("year", "?")] += 1
|
||||
for a, v in attrs.items():
|
||||
failing[key][a][str(v)] += 1
|
||||
if len(examples[key]) < _KEEP:
|
||||
examples[key].append({"file": ev["file"], "attrs": attrs, "bw": bw,
|
||||
"sfm": sfm, "detail": detail})
|
||||
carveouts.update(covered)
|
||||
bin_dir, xml_dir = _run_dirs(Path(results_path))
|
||||
return {"events": events, "fields": fields, "by_year": by_year, "compared": compared,
|
||||
"failing": failing, "examples": examples, "carveouts": carveouts,
|
||||
"bin_dir": bin_dir, "xml_dir": xml_dir, "regressions": None}
|
||||
|
||||
|
||||
def _fully_matching(counts: Counter) -> bool:
|
||||
"""Matched somewhere and failed nowhere. A field that only ever has no
|
||||
reference (an always-empty element) has proven nothing."""
|
||||
return (counts["match"] + counts["accepted"]) > 0 and not any(counts[v] for v in _NOT_DONE)
|
||||
|
||||
|
||||
def _events_line(event: Counter) -> str:
|
||||
def n(k: int, what: str) -> str:
|
||||
return f"{k} event{'' if k == 1 else 's'} {what}"
|
||||
return " · ".join(s for s in (n(event["no_reference"], "without a report") if event["no_reference"] else "",
|
||||
n(event["error"], "that failed to check") if event["error"] else "") if s)
|
||||
|
||||
|
||||
def write_summary(agg: dict, path: Path, title: Optional[str] = None) -> None:
|
||||
# The "event" pseudo-field is a whole event with no report or a failure,
|
||||
# not a field: it is reported on its own line.
|
||||
fields = {f: c for f, c in agg["fields"].items() if f != "event"}
|
||||
order = sorted(fields, key=lambda f: (-sum(fields[f][v] for v in _NOT_DONE), f))
|
||||
done = sum(_fully_matching(fields[f]) for f in fields)
|
||||
lines = [f"# Decode check — {title or Path(path).parent.name}", "",
|
||||
f"{agg['events']} events · {done} of {len(fields)} fields fully matching", ""]
|
||||
events = _events_line(agg["fields"].get("event", Counter()))
|
||||
if events:
|
||||
lines += [events, ""]
|
||||
if agg.get("regressions") is not None:
|
||||
n = agg["regressions"]
|
||||
lines += [f"**{n} regressions** since the previous run" + (" — see changes.md" if n else ""), ""]
|
||||
lines += ["| field | " + " | ".join(VERDICTS) + " |", "|---|" + "---:|" * len(VERDICTS)]
|
||||
lines += [f"| {f} | " + " | ".join(str(fields[f][v]) for v in VERDICTS) + " |" for f in order]
|
||||
|
||||
years = sorted({y for c in agg["by_year"].values() for y in c})
|
||||
bad = [f for f in order if not _fully_matching(fields[f])]
|
||||
if bad:
|
||||
lines += ["", "## Not matching, by event year", "",
|
||||
"| field | " + " | ".join(years) + " |", "|---|" + "---:|" * len(years)]
|
||||
lines += [f"| {f} | " + " | ".join(str(agg["by_year"][f][y] or "") for y in years) + " |"
|
||||
for f in bad]
|
||||
if agg["carveouts"]:
|
||||
lines += ["", "## Carve-outs (events covered)", "", "| carve-out | events |", "|---|---:|"]
|
||||
lines += [f"| {c} | {n} |" for c, n in agg["carveouts"].most_common()]
|
||||
Path(path).write_text("\n".join(lines) + "\n")
|
||||
|
||||
|
||||
def write_details(agg: dict, path: Path) -> None:
|
||||
def total_of(key: str) -> int:
|
||||
field, verdict = key.split("|", 1)
|
||||
return agg["fields"][field][verdict]
|
||||
|
||||
out = {}
|
||||
for key in sorted(agg["examples"], key=lambda k: (-total_of(k), k)):
|
||||
field = key.split("|", 1)[0]
|
||||
total = total_of(key)
|
||||
groups = {}
|
||||
for attr, values in agg["failing"].get(key, {}).items():
|
||||
rows = []
|
||||
for value, n in values.most_common():
|
||||
if n < _GROUP_SHARE * total:
|
||||
break
|
||||
seen = agg["compared"][field][attr][value]
|
||||
rate = round(n / seen, 3) if seen else 1.0
|
||||
rows.append({"value": value, "failing": n, "compared": seen, "rate": rate,
|
||||
"concentrated": rate >= _CONCENTRATED})
|
||||
if rows:
|
||||
groups[attr] = rows
|
||||
out[key] = {"total": total, "groups": groups,
|
||||
"examples": _pick_examples(agg, key, groups)}
|
||||
Path(path).write_text(json.dumps(out, indent=1))
|
||||
|
||||
|
||||
def _pick_examples(agg: dict, key: str, groups: dict) -> list[dict]:
|
||||
"""One example per top group value first, then the rest in run order."""
|
||||
pool, picked = agg["examples"][key], []
|
||||
for attr, rows in groups.items():
|
||||
for row in rows:
|
||||
ex = next((e for e in pool if str(e["attrs"].get(attr)) == row["value"]
|
||||
and e not in picked), None)
|
||||
if ex is not None and len(picked) < _EXAMPLES:
|
||||
picked.append(ex)
|
||||
picked += [e for e in pool if e not in picked][: _EXAMPLES - len(picked)]
|
||||
rerun = f"python scratch/check_s3_decode.py {agg['bin_dir']} {agg['xml_dir']} --file "
|
||||
return [{"file": e["file"], "bw": e["bw"], "sfm": e["sfm"], "detail": e["detail"],
|
||||
"rerun": rerun + e["file"]} for e in picked]
|
||||
|
||||
|
||||
_MATCHING = ("match", "accepted")
|
||||
|
||||
|
||||
def _verdicts(results_path: Path) -> tuple[dict[tuple[str, str], str], set[str], set[str]]:
|
||||
"""(file, field) -> verdict, every file in the run, and the files whose
|
||||
check failed outright (their field rows collapse to one "event" error)."""
|
||||
out, files, errored = {}, set(), set()
|
||||
with gzip.open(results_path, "rt", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
ev = json.loads(line)
|
||||
files.add(ev["file"])
|
||||
for row in ev["results"]:
|
||||
out[(ev["file"], row[0])] = row[1]
|
||||
if row[0] == "event" and row[1] == "error":
|
||||
errored.add(ev["file"])
|
||||
return out, files, errored
|
||||
|
||||
|
||||
def compare_runs(prev_results: Path, cur_results: Path) -> dict:
|
||||
"""What changed between two runs, over the events both checked: per-field
|
||||
verdict counts before and after, every (event, field) that matched and no
|
||||
longer does -- including events that now fail outright -- and how many
|
||||
non-matches now match."""
|
||||
before, files_before, _ = _verdicts(prev_results)
|
||||
after, files_after, errored = _verdicts(cur_results)
|
||||
shared = files_before & files_after
|
||||
fields: dict[str, dict[str, list[int]]] = defaultdict(lambda: defaultdict(lambda: [0, 0]))
|
||||
for (f, field), v in before.items():
|
||||
if f in shared:
|
||||
fields[field][v][0] += 1
|
||||
for (f, field), v in after.items():
|
||||
if f in shared:
|
||||
fields[field][v][1] += 1
|
||||
regressions = []
|
||||
for (f, field), v in sorted(before.items()):
|
||||
if v not in _MATCHING or f not in shared:
|
||||
continue
|
||||
now = after.get((f, field), "error" if f in errored else "missing")
|
||||
if now not in _MATCHING:
|
||||
regressions.append({"file": f, "field": field, "before": v, "after": now})
|
||||
fixed = sum(1 for k, v in after.items()
|
||||
if k[0] in shared and v in _MATCHING and before.get(k) not in (None,) + _MATCHING)
|
||||
return {"fields": {f: dict(c) for f, c in fields.items()}, "regressions": regressions,
|
||||
"fixed": fixed, "shared_events": len(shared), "prev": str(prev_results),
|
||||
"prev_scope": _scope_of(Path(prev_results).parent)}
|
||||
|
||||
|
||||
def _scope_of(run_dir: Path) -> Optional[dict]:
|
||||
try:
|
||||
args = json.loads((run_dir / "run.json").read_text())["args"]
|
||||
except (OSError, KeyError, ValueError):
|
||||
return None
|
||||
return {k: args.get(k) for k in ("serial", "year", "type", "field", "sample", "seed") if args.get(k)}
|
||||
|
||||
|
||||
def write_changes(chg: dict, path: Path) -> None:
|
||||
regs = chg["regressions"]
|
||||
scope = chg.get("prev_scope")
|
||||
lines = [f"# Changes since {chg.get('prev', 'the previous run')}", "",
|
||||
f"Previous run's scope: {scope or 'all events'} · compared over "
|
||||
f"{chg.get('shared_events', '?')} events both runs checked", "",
|
||||
f"{len(regs)} regressions · {chg['fixed']} fixed", ""]
|
||||
if regs:
|
||||
lines += ["## Regressions (matched before, not now)", "", "| file | field | now |", "|---|---|---|"]
|
||||
lines += [f"| {r['file']} | {r['field']} | {r['after']} |" for r in regs[:500]]
|
||||
if len(regs) > 500:
|
||||
lines.append(f"| … {len(regs) - 500} more | | |")
|
||||
lines.append("")
|
||||
moved = {f: c for f, c in chg["fields"].items() if any(b != a for b, a in c.values())}
|
||||
if moved:
|
||||
lines += ["## Fields whose counts moved (before → after)", "",
|
||||
"| field | " + " | ".join(VERDICTS) + " |", "|---|" + "---|" * len(VERDICTS)]
|
||||
for f in sorted(moved):
|
||||
lines.append(f"| {f} | " + " | ".join(
|
||||
f"{moved[f].get(v, [0, 0])[0]} → {moved[f].get(v, [0, 0])[1]}" for v in VERDICTS) + " |")
|
||||
Path(path).write_text("\n".join(lines) + "\n")
|
||||
@@ -1,159 +0,0 @@
|
||||
"""
|
||||
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.
+3292
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+113
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE11529</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>M529L4XQ.R30H</FileName>
|
||||
<HistogramStartTime>14:54:39</HistogramStartTime>
|
||||
<HistogramStartDate>2025-07-02</HistogramStartDate>
|
||||
<HistogramStopTime>14:55:08</HistogramStopTime>
|
||||
<HistogramStopDate>2025-07-02</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.3 Volts</BatteryLevel>
|
||||
<Calibration>April 29, 2025 by Instantel</Calibration>
|
||||
<Units>in/s and dB(L)</Units>
|
||||
<Location>Test Loc</Location>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>2.430</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>0.940</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>1.900</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>13</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>>100</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>5.8</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>14:55:08</TranPeakTime>
|
||||
<TranPeakDate>2025-07-02</TranPeakDate>
|
||||
<VertPeakTime>14:55:08</VertPeakTime>
|
||||
<VertPeakDate>2025-07-02</VertPeakDate>
|
||||
<LongPeakTime>14:55:08</LongPeakTime>
|
||||
<LongPeakDate>2025-07-02</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>3.095</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>14:55:08</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2025-07-02</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>106.0</Value>
|
||||
<Units>dB(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>14:55:08</MicLTime>
|
||||
<MicLDate>2025-07-02</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>51</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.5 Hz.</TranTestFreq>
|
||||
<TranTestRatio>4.0</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.6 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.7</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.2 Hz.</LongTestFreq>
|
||||
<LongTestRatio>4.0</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Check</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2025-07-02 14:54:39 - 2025-07-02 14:55:08 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2025-07-02 14:55:08</Time>
|
||||
<Row>
|
||||
<Cell>2.430</Cell><Cell>13</Cell><Cell>0.940</Cell><Cell>>100</Cell><Cell>1.900</Cell><Cell>5.8</Cell><Cell>3.095</Cell><Cell>0.001</Cell><Cell>106.0</Cell><Cell>51</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+98
@@ -0,0 +1,98 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE16352</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>R352HFZ7.530H</FileName>
|
||||
<HistogramStartTime>21:17:27</HistogramStartTime>
|
||||
<HistogramStartDate>2018-06-04</HistogramStartDate>
|
||||
<HistogramStopTime>21:17:39</HistogramStopTime>
|
||||
<HistogramStopDate>2018-06-04</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.7 Volts</BatteryLevel>
|
||||
<Calibration>September 13, 2017 by Instantel</Calibration>
|
||||
<Units>in/s</Units>
|
||||
<Project>JV 241 - 1425 Spanlers Mill Rad</Project>
|
||||
<Client>Walsh Granite JV</Client>
|
||||
<UserName>Terra-Mechanics Inc- D. Harrison</UserName>
|
||||
<Seis.Loc>Loc #1 - 1425 Spanlers Mill Rd</Seis.Loc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.355</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>2.475</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>0.770</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>73</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>30</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>24</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>21:17:39</TranPeakTime>
|
||||
<TranPeakDate>2018-06-04</TranPeakDate>
|
||||
<VertPeakTime>21:17:39</VertPeakTime>
|
||||
<VertPeakDate>2018-06-04</VertPeakDate>
|
||||
<LongPeakTime>21:17:39</LongPeakTime>
|
||||
<LongPeakDate>2018-06-04</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>2.552</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>21:17:39</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2018-06-04</PeakVectorSumDate>
|
||||
<TranTestFreq>7.5 Hz.</TranTestFreq>
|
||||
<TranTestRatio>3.7</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.4 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.6</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.6 Hz.</LongTestFreq>
|
||||
<LongTestRatio>3.6</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2018-06-04 21:17:26 - 2018-06-04 21:17:39 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2018-06-04 21:17:39</Time>
|
||||
<Row>
|
||||
<Cell>0.355</Cell><Cell>73</Cell><Cell>2.475</Cell><Cell>30</Cell><Cell>0.770</Cell><Cell>24</Cell><Cell>2.552</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+3968
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+116
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Event>
|
||||
<FileVersion>8.0</FileVersion>
|
||||
<EventType>Full Histogram</EventType>
|
||||
<SerialNumber>BE18004</SerialNumber>
|
||||
<Version>V 10.72-8.17 MiniMate Plus</Version>
|
||||
<FileName>T004JTRF.ME0H</FileName>
|
||||
<HistogramStartTime>12:49:26</HistogramStartTime>
|
||||
<HistogramStartDate>2022-12-28</HistogramStartDate>
|
||||
<HistogramStopTime>12:49:33</HistogramStopTime>
|
||||
<HistogramStopDate>2022-12-28</HistogramStopDate>
|
||||
<Channels>
|
||||
<Channel>Tran</Channel>
|
||||
<Channel>Vert</Channel>
|
||||
<Channel>Long</Channel>
|
||||
<Channel>MicL</Channel>
|
||||
</Channels>
|
||||
<NumberofIntervals>1.00</NumberofIntervals>
|
||||
<IntervalSize>1 minute</IntervalSize>
|
||||
<SampleRate>1024 sps</SampleRate>
|
||||
<BatteryLevel>6.3 Volts</BatteryLevel>
|
||||
<Calibration>June 24, 2022 by Instantel</Calibration>
|
||||
<Units>in/s and psi(L)</Units>
|
||||
<Project>Robinson Run Bridge No 3-201 Marshall</Project>
|
||||
<Client>Mele & Mele & Sons, Inc.</Client>
|
||||
<UserName>Terra-Mechanics Inc. - D. Harrison</UserName>
|
||||
<SeisLoc>Location #1 - 201 Marshall Road</SeisLoc>
|
||||
<GeoRange>
|
||||
<Value>10.000</Value>
|
||||
<Units>in/s</Units>
|
||||
</GeoRange>
|
||||
<TranPPV>
|
||||
<Value>0.940</Value>
|
||||
<Units>in/s</Units>
|
||||
</TranPPV>
|
||||
<VertPPV>
|
||||
<Value>1.095</Value>
|
||||
<Units>in/s</Units>
|
||||
</VertPPV>
|
||||
<LongPPV>
|
||||
<Value>1.045</Value>
|
||||
<Units>in/s</Units>
|
||||
</LongPPV>
|
||||
<TranZCFreq>
|
||||
<Value>32</Value>
|
||||
<Units>Hz</Units>
|
||||
</TranZCFreq>
|
||||
<VertZCFreq>
|
||||
<Value>47</Value>
|
||||
<Units>Hz</Units>
|
||||
</VertZCFreq>
|
||||
<LongZCFreq>
|
||||
<Value>14</Value>
|
||||
<Units>Hz</Units>
|
||||
</LongZCFreq>
|
||||
<TranPeakTime>12:49:33</TranPeakTime>
|
||||
<TranPeakDate>2022-12-28</TranPeakDate>
|
||||
<VertPeakTime>12:49:33</VertPeakTime>
|
||||
<VertPeakDate>2022-12-28</VertPeakDate>
|
||||
<LongPeakTime>12:49:33</LongPeakTime>
|
||||
<LongPeakDate>2022-12-28</LongPeakDate>
|
||||
<PeakVectorSum>
|
||||
<Value>1.358</Value>
|
||||
<Units>in/s</Units>
|
||||
</PeakVectorSum>
|
||||
<PeakVectorSumTime>12:49:33</PeakVectorSumTime>
|
||||
<PeakVectorSumDate>2022-12-28</PeakVectorSumDate>
|
||||
<Microphone>Linear Weighting</Microphone>
|
||||
<MicLPSPL>
|
||||
<Value>0.0</Value>
|
||||
<Units>psi(L)</Units>
|
||||
</MicLPSPL>
|
||||
<MicLTime>12:49:33</MicLTime>
|
||||
<MicLDate>2022-12-28</MicLDate>
|
||||
<MicLZCFreq>
|
||||
<Value>47</Value>
|
||||
<Units>Hz</Units>
|
||||
</MicLZCFreq>
|
||||
<TranTestFreq>7.4 Hz.</TranTestFreq>
|
||||
<TranTestRatio>3.7</TranTestRatio>
|
||||
<TranTestResults>Passed</TranTestResults>
|
||||
<VertTestFreq>7.5 Hz.</VertTestFreq>
|
||||
<VertTestRatio>3.6</VertTestRatio>
|
||||
<VertTestResults>Passed</VertTestResults>
|
||||
<LongTestFreq>7.5 Hz.</LongTestFreq>
|
||||
<LongTestRatio>4.1</LongTestRatio>
|
||||
<LongTestResults>Passed</LongTestResults>
|
||||
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
|
||||
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
|
||||
<MicLTestResults>Check</MicLTestResults>
|
||||
<UsbSummaryChannels>
|
||||
</UsbSummaryChannels>
|
||||
<MonitorLog>2022-12-28 12:49:25 - 2022-12-28 12:49:33 "Event Recorded Modem Exit"</MonitorLog>
|
||||
<HistogramData>
|
||||
<HistogramDataColumnTitle>
|
||||
<ColumnTitle> Tran Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Tran Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Vert Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Vert Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Long Peak in/s </ColumnTitle>
|
||||
<ColumnTitle> Long Freq Hz </ColumnTitle>
|
||||
<ColumnTitle> Geo PVS in/s </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
|
||||
<ColumnTitle> MicL Freq Hz </ColumnTitle>
|
||||
</HistogramDataColumnTitle>
|
||||
<HistogramDataIntervals>
|
||||
<Time>2022-12-28 12:49:33</Time>
|
||||
<Row>
|
||||
<Cell>0.940</Cell><Cell>32</Cell><Cell>1.095</Cell><Cell>47</Cell><Cell>1.045</Cell><Cell>14</Cell><Cell>1.358</Cell><Cell>0.001</Cell><Cell>104.9</Cell><Cell>47</Cell></Row>
|
||||
</HistogramDataIntervals>
|
||||
</HistogramData>
|
||||
<HistogramDataUsbChannels>
|
||||
</HistogramDataUsbChannels>
|
||||
|
||||
</Event>
|
||||
BIN
Binary file not shown.
+3204
File diff suppressed because it is too large.
Load diff
BIN
Binary file not shown.
+7049
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
Blastware's `_XML.XML` event report, parsed (decode checker, Task 1).
|
||||
|
||||
Expected values are copied from the fixture XML files themselves.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from minimateplus.bw_xml_report import parse_xml_report, parse_xml_report_file
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
|
||||
|
||||
|
||||
def test_scalars_units_and_special_text():
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert r.scalars["SampleRate"] == "1024 sps"
|
||||
assert r.scalars["RecordTime"] == "1.0 sec."
|
||||
assert r.scalars["TranPPV"] == "0.005" and r.units["TranPPV"] == "in/s"
|
||||
assert r.scalars["VertZCFreq"] == ">100" # entity unescaped
|
||||
assert r.scalars["TranZCFreq"] == "N/A"
|
||||
assert r.scalars["TranTestResults"] == "Check"
|
||||
assert r.scalars["BatteryLevel"] == "6.7 Volts"
|
||||
assert r.job_number == "1" and r.notes == []
|
||||
assert r.channels == ["Tran", "Vert", "Long", "MicL"]
|
||||
|
||||
|
||||
def test_waveform_sample_rows():
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert len(r.sample_rows) == 1024
|
||||
assert r.sample_rows[0] == ["-0.005", "0.000", "0.000", "81.94"]
|
||||
assert r.intervals is None
|
||||
|
||||
|
||||
def test_ragged_rows_are_kept_as_printed():
|
||||
r = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML")
|
||||
assert len(r.sample_rows) == 2304
|
||||
assert r.sample_rows[-4] == ["-0.185", "0.235", "-0.255", "-87.96"]
|
||||
assert r.sample_rows[-1] == ["-0.245"] # only Long still running
|
||||
|
||||
|
||||
def test_relabelled_notes_keep_their_tags_in_order():
|
||||
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
|
||||
assert r.notes == [("Location", "Test Loc")]
|
||||
r = parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML")
|
||||
assert r.notes[1] == ("Client", "Mele & Mele & Sons, Inc.")
|
||||
assert r.event_units == "in/s and psi(L)"
|
||||
|
||||
|
||||
def test_notes_and_job_number_are_not_scalars():
|
||||
r = parse_xml_report_file(FIX / "T004JTRF_ME0H_XML.XML")
|
||||
assert "Project" not in r.scalars and "SeisLoc" not in r.scalars
|
||||
r = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
assert "JobNumber" not in r.scalars
|
||||
|
||||
|
||||
def test_histogram_intervals_and_columns():
|
||||
r = parse_xml_report_file(FIX / "M529L4XQ_R30H_XML.XML")
|
||||
assert r.interval_columns[0] == "Tran Peak in/s" and len(r.interval_columns) == 10
|
||||
assert r.intervals == [("2025-07-02 14:55:08",
|
||||
["2.430", "13", "0.940", ">100", "1.900", "5.8", "3.095", "0.001", "106.0", "51"])]
|
||||
assert r.sample_rows is None
|
||||
|
||||
|
||||
def test_no_mic_histogram_has_seven_columns():
|
||||
r = parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML")
|
||||
assert r.event_units == "in/s"
|
||||
assert r.channels == ["Tran", "Vert", "Long"]
|
||||
assert len(r.interval_columns) == 7 and len(r.intervals[0][1]) == 7
|
||||
|
||||
|
||||
def test_oorange_and_range_values():
|
||||
r = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML")
|
||||
assert r.scalars["TranPPV"] == "OORANGE"
|
||||
assert r.scalars["GeoRange"] == "1.250" and r.units["GeoRange"] == "in/s"
|
||||
|
||||
|
||||
def test_truncated_xml_raises_valueerror():
|
||||
data = (FIX / "M529L4XQ_R30H_XML.XML").read_bytes()
|
||||
with pytest.raises(ValueError):
|
||||
parse_xml_report(data[: len(data) // 2])
|
||||
@@ -0,0 +1,173 @@
|
||||
"""
|
||||
The decode checker's runner and reports (decode checker, Tasks 5-7).
|
||||
|
||||
Runs on the fixture folder, which holds the binaries and their XML reports
|
||||
side by side.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
run = importlib.import_module("scratch.check_s3_decode")
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
|
||||
|
||||
|
||||
def test_find_pairs_dedupes_and_pairs(tmp_path):
|
||||
(tmp_path / "Sent").mkdir()
|
||||
for n in ("R352HIUI.F40W", "Sent/R352HIUI.F40W", "UM11719_20240404193109.IDFH"):
|
||||
(tmp_path / n).write_bytes(b"x")
|
||||
pairs = run.find_pairs(tmp_path, FIX)
|
||||
assert [p[0] for p in pairs] == ["R352HIUI.F40W"]
|
||||
assert pairs[0][2].name == "R352HIUI_F40W_XML.XML"
|
||||
|
||||
|
||||
def test_check_event_rows_and_attrs():
|
||||
out = run.check_event("M007HVWF.K30W", str(FIX / "M007HVWF.K30W"), str(FIX / "M007HVWF_K30W_XML.XML"))
|
||||
assert out["attrs"]["range"] == "1.250" and out["attrs"]["model"] == "MiniMate Plus"
|
||||
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 = run.check_event(bad.name, str(bad), str(FIX / "R352HIUI_F40W_XML.XML"))
|
||||
assert out["results"] == [["event", "error", None, None, out["results"][0][4], None]]
|
||||
|
||||
|
||||
def test_missing_reference_is_one_no_reference_row():
|
||||
out = run.check_event("R352HIUI.F40W", str(FIX / "R352HIUI.F40W"), None)
|
||||
assert [r[:2] for r in out["results"]] == [["event", "no_reference"]]
|
||||
|
||||
|
||||
def test_cli_writes_results(tmp_path):
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1"]) == 0
|
||||
lines = gzip.open(tmp_path / "run/results.jsonl.gz", "rt").read().splitlines()
|
||||
assert len(lines) == 7
|
||||
assert json.loads((tmp_path / "run/run.json").read_text())["events"] == 7
|
||||
|
||||
|
||||
def test_field_filter_keeps_only_matching_rows(tmp_path):
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1",
|
||||
"--field", "samples."]) == 0
|
||||
for line in gzip.open(tmp_path / "run/results.jsonl.gz", "rt"):
|
||||
assert all(r[0].startswith("samples.") for r in json.loads(line)["results"])
|
||||
|
||||
|
||||
# ── Task 6: summary and detailed report ─────────────────────────────────────
|
||||
|
||||
report = importlib.import_module("scratch.decode_check_report")
|
||||
|
||||
|
||||
def _write_results(path, events):
|
||||
with gzip.open(path, "wt") as fh:
|
||||
for ev in events:
|
||||
fh.write(json.dumps(ev) + "\n")
|
||||
|
||||
|
||||
def _ev(name, sr, verdict):
|
||||
return {"file": name, "attrs": {"sample_rate": sr, "year": "2024"},
|
||||
"results": [["SampleRate", verdict, sr + " sps", "1024", "", None]]}
|
||||
|
||||
|
||||
def test_details_group_failures_by_what_they_share(tmp_path):
|
||||
res = tmp_path / "results.jsonl.gz"
|
||||
_write_results(res, [_ev("A.W", "2048", "mismatch"), _ev("B.W", "2048", "mismatch"),
|
||||
_ev("C.W", "1024", "match")])
|
||||
agg = report.aggregate(res)
|
||||
report.write_details(agg, tmp_path / "details.json")
|
||||
d = json.loads((tmp_path / "details.json").read_text())["SampleRate|mismatch"]
|
||||
assert d["total"] == 2
|
||||
assert d["groups"]["sample_rate"] == [
|
||||
{"value": "2048", "failing": 2, "compared": 2, "rate": 1.0, "concentrated": True}]
|
||||
assert d["examples"] and all("--file" in e["rerun"] for e in d["examples"])
|
||||
|
||||
|
||||
def test_summary_counts_fields_fully_matching(tmp_path):
|
||||
res = tmp_path / "results.jsonl.gz"
|
||||
_write_results(res, [_ev("A.W", "2048", "mismatch"), _ev("C.W", "1024", "match")])
|
||||
report.write_summary(report.aggregate(res), tmp_path / "summary.md")
|
||||
text = (tmp_path / "summary.md").read_text()
|
||||
assert "0 of 1 fields fully matching" in text and "| SampleRate |" in text
|
||||
|
||||
|
||||
def test_a_run_writes_both_reports(tmp_path):
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "run"), "--jobs", "1"]) == 0
|
||||
assert (tmp_path / "run/summary.md").exists() and (tmp_path / "run/details.json").exists()
|
||||
|
||||
|
||||
# ── Task 7: run-to-run changes and the one-event view ───────────────────────
|
||||
|
||||
def _one(name, field, verdict):
|
||||
return {"file": name, "attrs": {}, "results": [[field, verdict, "x", "y", "", None]]}
|
||||
|
||||
|
||||
def test_compare_runs_finds_regressions_and_fixes(tmp_path):
|
||||
prev, cur = tmp_path / "prev.jsonl.gz", tmp_path / "cur.jsonl.gz"
|
||||
_write_results(prev, [_one("A.W", "SampleRate", "match"), _one("B.W", "notes", "sfm_blank")])
|
||||
_write_results(cur, [_one("A.W", "SampleRate", "mismatch"), _one("B.W", "notes", "match")])
|
||||
chg = report.compare_runs(prev, cur)
|
||||
assert chg["regressions"] == [{"file": "A.W", "field": "SampleRate",
|
||||
"before": "match", "after": "mismatch"}]
|
||||
assert chg["fixed"] == 1
|
||||
report.write_changes(chg, tmp_path / "changes.md")
|
||||
assert "A.W" in (tmp_path / "changes.md").read_text()
|
||||
|
||||
|
||||
def test_compare_to_marks_the_summary(tmp_path):
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "a"), "--jobs", "1"]) == 0
|
||||
assert run.main([str(FIX), str(FIX), "--out", str(tmp_path / "b"), "--jobs", "1",
|
||||
"--compare-to", str(tmp_path / "a")]) == 0
|
||||
assert "**0 regressions**" in (tmp_path / "b/summary.md").read_text()
|
||||
assert (tmp_path / "b/changes.md").exists()
|
||||
|
||||
|
||||
def test_file_prints_one_event(tmp_path, capsys):
|
||||
assert run.main([str(FIX), str(FIX), "--file", "M007HVWF.K30W"]) == 0
|
||||
out = capsys.readouterr().out
|
||||
assert any("TranPPV" in line and "mismatch" in line for line in out.splitlines())
|
||||
|
||||
|
||||
# ── Final review fixes ──────────────────────────────────────────────────────
|
||||
|
||||
def test_a_matching_event_that_now_errors_is_a_regression(tmp_path):
|
||||
prev, cur = tmp_path / "prev.jsonl.gz", tmp_path / "cur.jsonl.gz"
|
||||
_write_results(prev, [_one("A.W", "SampleRate", "match"), _one("B.W", "notes", "match")])
|
||||
_write_results(cur, [_one("A.W", "event", "error"), _one("B.W", "notes", "match")])
|
||||
chg = report.compare_runs(prev, cur)
|
||||
assert chg["regressions"] == [{"file": "A.W", "field": "SampleRate",
|
||||
"before": "match", "after": "error"}]
|
||||
|
||||
|
||||
def test_counts_moved_cover_only_shared_events(tmp_path):
|
||||
prev, cur = tmp_path / "prev.jsonl.gz", tmp_path / "cur.jsonl.gz"
|
||||
_write_results(prev, [_one("A.W", "SampleRate", "match")])
|
||||
_write_results(cur, [_one("A.W", "SampleRate", "match"), _one("B.W", "SampleRate", "match")])
|
||||
assert report.compare_runs(prev, cur)["fields"]["SampleRate"]["match"] == [1, 1]
|
||||
|
||||
|
||||
def test_default_comparison_is_the_newest_completed_run_of_the_same_scope(tmp_path, monkeypatch):
|
||||
runs = tmp_path / "runs"
|
||||
monkeypatch.setattr(run, "RUNS_DIR", runs)
|
||||
base = [str(FIX), str(FIX), "--jobs", "1"]
|
||||
assert run.main(base + ["--out", str(runs / "20990101-000001")]) == 0 # same scope
|
||||
assert run.main(base + ["--out", str(runs / "20990101-000002"), "--type", "W"]) == 0 # narrower
|
||||
(runs / "20990101-000003").mkdir() # never finished
|
||||
assert run.main(base + ["--out", str(runs / "20990101-000004")]) == 0
|
||||
assert "20990101-000001" in (runs / "20990101-000004/changes.md").read_text().splitlines()[0]
|
||||
|
||||
|
||||
def test_fields_fully_matching_need_a_match_and_skip_the_event_row(tmp_path):
|
||||
res = tmp_path / "results.jsonl.gz"
|
||||
_write_results(res, [
|
||||
{"file": "A.W", "attrs": {}, "results": [["SampleRate", "match", "1", "1", "", None],
|
||||
["UsbSummaryChannels", "no_reference", "", None, "", None]]},
|
||||
{"file": "B.W", "attrs": {}, "results": [["event", "no_reference", None, None, "no XML report", None]]},
|
||||
])
|
||||
report.write_summary(report.aggregate(res), tmp_path / "summary.md")
|
||||
text = (tmp_path / "summary.md").read_text()
|
||||
assert "1 of 2 fields fully matching" in text
|
||||
assert "1 event without a report" in text and "| event |" not in text
|
||||
@@ -0,0 +1,145 @@
|
||||
"""
|
||||
The decode checker's SFM side and comparison (decode checker, Tasks 2-4).
|
||||
|
||||
Expected values come from the fixtures' Blastware XML reports. SFM's side is
|
||||
built from the event bytes alone -- no filename, no report.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from minimateplus.decode_check import sfm_side
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
|
||||
|
||||
|
||||
def test_waveform_side_from_bytes():
|
||||
s = sfm_side((FIX / "R352HIUI.F40W").read_bytes())
|
||||
assert s.values["SampleRate"] == 1024 and s.values["RecordTime"] == pytest.approx(1.0)
|
||||
assert s.values["Pre-triggerLength"] == pytest.approx(-253 / 1024)
|
||||
assert (s.values["EventDate"], s.values["EventTime"]) == ("2018-07-30", "16:13:52")
|
||||
assert s.notes == ["JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV",
|
||||
"Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"]
|
||||
assert len(s.counts["Tran"]) == 1277 and s.job_number is None
|
||||
|
||||
|
||||
def test_histogram_interval_peak_in_counts():
|
||||
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
|
||||
# Blastware: Tran interval peak 2.430 in/s = 7776 counts at 10/32000 in/s per count
|
||||
assert s.counts["Tran"] == [7776] and s.values["NumberofIntervals"] == 1
|
||||
|
||||
|
||||
def test_no_filename_reaches_the_decoder():
|
||||
# The type must come from the bytes; today they can't tell it (#41), so this
|
||||
# histogram reads as a waveform. Update to "Full Histogram" when #41 lands.
|
||||
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
|
||||
|
||||
|
||||
# ── Task 3: the comparison ──────────────────────────────────────────────────
|
||||
|
||||
from minimateplus.bw_xml_report import parse_xml_report_file # noqa: E402
|
||||
from minimateplus.decode_check import compare, matches_printed # noqa: E402
|
||||
|
||||
|
||||
def _results(stem, carveouts=()):
|
||||
raw = (FIX / stem).read_bytes()
|
||||
ref = parse_xml_report_file(FIX / (stem.replace(".", "_") + "_XML.XML"))
|
||||
return {r.field: r for r in compare(sfm_side(raw), ref, carveouts)}
|
||||
|
||||
|
||||
def test_matches_printed_rounds_half_away():
|
||||
assert matches_printed(-0.0625, "-0.063") and matches_printed(0.0015, "0.002")
|
||||
assert not matches_printed(0.0026, "0.002")
|
||||
|
||||
|
||||
def test_full_waveform_row_verdicts():
|
||||
res = _results("R352HIUI.F40W")
|
||||
for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime",
|
||||
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
|
||||
assert res[f].verdict == "match", (f, res[f])
|
||||
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
|
||||
assert res["BatteryLevel"].verdict == "sfm_blank"
|
||||
assert "FileName" not in res
|
||||
|
||||
|
||||
def test_ragged_rows_match_by_running_channels():
|
||||
# Tran/Vert/MicL end 3 samples before Long, in SFM and in Blastware's table alike
|
||||
res = _results("T438HGTZ.B30W")
|
||||
for ch in ("Tran", "Vert", "Long"):
|
||||
assert res[f"samples.{ch}"].verdict == "match", res[f"samples.{ch}"]
|
||||
|
||||
|
||||
def test_an_extra_reference_row_is_a_mismatch_with_detail():
|
||||
raw = (FIX / "T1905KDW.5F0W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
|
||||
ref.sample_rows.append(["0.000", "0.000", "0.000", "0.000"])
|
||||
res = {r.field: r for r in compare(sfm_side(raw), ref)}
|
||||
assert res["samples.Tran"].verdict == "mismatch"
|
||||
assert "row_length_disagreements=1" in res["samples.Tran"].detail
|
||||
|
||||
|
||||
def test_job_number_na_and_above_range():
|
||||
res = _results("T1905KDW.5F0W")
|
||||
assert res["JobNumber"].verdict == "sfm_blank"
|
||||
assert res["TranZCFreq"].verdict == "no_reference" # N/A
|
||||
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
|
||||
|
||||
|
||||
def test_mic_units_pick_the_conversion():
|
||||
res = _results("T004JTRF.ME0H") # psi(L)
|
||||
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
|
||||
assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank"
|
||||
fields = set(_results("R352HFZ7.530H")) # no mic
|
||||
assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields)
|
||||
|
||||
|
||||
# ── Task 4: carve-outs ──────────────────────────────────────────────────────
|
||||
|
||||
from minimateplus.decode_check_carveouts import CARVEOUTS # noqa: E402
|
||||
|
||||
|
||||
def test_clipped_normal_range_is_accepted():
|
||||
# Blastware: Tran 5.445, Vert 6.310, Long OORANGE, PVS OORANGE; SFM Long 10.005, PVS 11.55
|
||||
res = _results("T438HGTZ.B30W", CARVEOUTS)
|
||||
assert res["TranPPV"].verdict == "match" and res["VertPPV"].verdict == "match"
|
||||
for f in ("LongPPV", "PeakVectorSum"):
|
||||
assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation")
|
||||
|
||||
|
||||
def test_sensitive_range_8x_stays_a_mismatch():
|
||||
res = _results("M007HVWF.K30W", CARVEOUTS)
|
||||
assert res["TranPPV"].verdict == "mismatch" and res["samples.Tran"].verdict == "mismatch"
|
||||
assert res["PeakVectorSum"].verdict == "mismatch"
|
||||
|
||||
|
||||
def test_every_carveout_has_evidence():
|
||||
assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS)
|
||||
|
||||
|
||||
def test_pvs_carveout_needs_oorange_from_blastware():
|
||||
raw = (FIX / "T438HGTZ.B30W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML")
|
||||
ref.scalars["PeakVectorSum"] = "10.392" # a vector sum may exceed the range unclipped
|
||||
res = {r.field: r for r in compare(sfm_side(raw), ref, CARVEOUTS)}
|
||||
assert res["PeakVectorSum"].verdict == "mismatch"
|
||||
|
||||
|
||||
def test_pvs_carveout_needs_the_clipped_channel_at_the_ceiling():
|
||||
# 1.250 range, Blastware PVS OORANGE; an UNclipped channel's 8x value happens to land
|
||||
# in the 1.250 band -- that must not let SFM's 8x vector sum through.
|
||||
raw = (FIX / "M007HVWF.K30W").read_bytes()
|
||||
ref = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML")
|
||||
ref.scalars["TranPPV"] = "0.157"
|
||||
side = sfm_side(raw)
|
||||
side.values["TranPPV"] = 1.256
|
||||
res = {r.field: r for r in compare(side, ref, CARVEOUTS)}
|
||||
assert res["PeakVectorSum"].verdict == "mismatch"
|
||||
Reference in new issue
Block a user