Release v0.33.0 — SFM reads Series-3 events from the file alone #56

Merged
serversdown merged 34 commits from dev into main 2026-11-01 14:33:01 -05:00
3 changed files with 32 additions and 159 deletions
Showing only changes of commit e9d352ad99 - Show all commits

No files matched your search

+24
View File
@@ -14,6 +14,30 @@ 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 sums interval peaks, Blastware takes the per-interval
vector sum
- mic psi conversion
- mic dB off by 0.05–0.1 on ~1,000 events
- ~37 sub-minute histograms decode wrongly
- 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
+8
View File
@@ -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.
-159
View File
@@ -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())