Files
seismo-relay/tests/test_decode_check.py
T
serversdownandClaude Opus 5.5 aec4a38473 fix(decode): histograms go to the histogram codec, and a loud interval no longer hides a short one
Three causes behind the histograms the checker found decoding wrongly:

1. The file decoder tried the waveform codec first, whatever the record
   type.  It accepted BE9440 / BE9557 / BE17354's 2018 5 s histograms and
   returned ~5x too many 'samples' (K440HDXX.XH0H: SFM 44,504, Blastware
   6,976).  The codec now follows STRT[18] (0x46 / 0x0A on 70,041 /
   70,041 DL2 files); only an unknown type falls back to trial order, and a
   chosen codec that fails is a decode problem rather than a silent switch.

2. The sub-minute layout check required each record's 'zero word' to be
   0000.  It is the high word of the interval's PVS squared, non-zero above
   1.28 in/s, so a one-block histogram with a loud interval was not
   recognised (T193KR5M.X90H, K440HA3C.JM0H, R352HFZ7.530H decoded to
   nothing).  The check is now the measured relation peak <= PVS <=
   sqrt(3) * peak, which holds on 34,502,955 / 34,502,955 DL2 sub-minute
   intervals.  The no-terminal-tail trim uses the same test.  Two test
   builders wrote PVS bytes no real record has (one still in the retracted
   little-endian layout); they now write peak^2 in the measured layout, and
   the retraction test keeps a legacy builder of its own.

3. Checker carve-out interval-count-is-duration: Blastware's Number of
   Intervals is (stop - start) / interval from the footer times, and its
   own interval table lists one block fewer when the unit never wrote the
   last minute.  SFM matches the table (T193KSWP.FF0H: 2,880 vs 2,850).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-02 16:20:32 -05:00

224 lines
9.9 KiB
Python

"""
The decode checker's SFM side and comparison (decode checker, Tasks 2-4).
Expected values come from the fixtures' Blastware XML reports. SFM's side is
built from the event bytes alone -- no filename, no report.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from minimateplus.decode_check import sfm_side
FIX = Path(__file__).parent / "fixtures/decode-checker-10-29-26"
def test_waveform_side_from_bytes():
s = sfm_side((FIX / "R352HIUI.F40W").read_bytes())
assert s.values["SampleRate"] == 1024 and s.values["RecordTime"] == pytest.approx(1.0)
assert s.values["Pre-triggerLength"] == pytest.approx(-253 / 1024)
assert (s.values["EventDate"], s.values["EventTime"]) == ("2018-07-30", "16:13:52")
assert s.notes == ["JV 241 - 1425 Spanlers Mill Rad", "Walsh Granite JV",
"Terra-Mechanics Inc- D. Harrison", "Loc #1 - 1425 Spanlers Mill Rd"]
assert len(s.counts["Tran"]) == 1277 and s.job_number is None
def test_histogram_interval_peak_in_counts():
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
# Blastware: Tran interval peak 2.430 in/s = 7776 counts at 10/32000 in/s per count
assert s.counts["Tran"] == [7776] and s.values["NumberofIntervals"] == 1
def test_event_type_comes_from_the_bytes():
# No filename reaches the decoder; the type is the STRT record-type byte (#41).
s = sfm_side((FIX / "M529L4XQ.R30H").read_bytes())
assert s.values["EventType"] == "Full Histogram"
def test_report_fields_stay_blank():
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"):
assert s.values.get(tag) is None
# ── Task 3: the comparison ──────────────────────────────────────────────────
from minimateplus.bw_xml_report import parse_xml_report_file # noqa: E402
from minimateplus.decode_check import compare, matches_printed # noqa: E402
def _results(stem, carveouts=()):
raw = (FIX / stem).read_bytes()
ref = parse_xml_report_file(FIX / (stem.replace(".", "_") + "_XML.XML"))
return {r.field: r for r in compare(sfm_side(raw), ref, carveouts)}
def test_matches_printed_rounds_half_away():
assert matches_printed(-0.0625, "-0.063") and matches_printed(0.0015, "0.002")
assert not matches_printed(0.0026, "0.002")
def test_full_waveform_row_verdicts():
res = _results("R352HIUI.F40W")
for f in ("SampleRate", "RecordTime", "Pre-triggerLength", "EventDate", "EventTime",
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
assert res[f].verdict == "match", (f, res[f])
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
assert res["BatteryLevel"].verdict == "sfm_blank"
assert "FileName" not in res
def test_ragged_rows_match_by_running_channels():
# Tran/Vert/MicL end 3 samples before Long, in SFM and in Blastware's table alike
res = _results("T438HGTZ.B30W")
for ch in ("Tran", "Vert", "Long"):
assert res[f"samples.{ch}"].verdict == "match", res[f"samples.{ch}"]
def test_an_extra_reference_row_is_a_mismatch_with_detail():
raw = (FIX / "T1905KDW.5F0W").read_bytes()
ref = parse_xml_report_file(FIX / "T1905KDW_5F0W_XML.XML")
ref.sample_rows.append(["0.000", "0.000", "0.000", "0.000"])
res = {r.field: r for r in compare(sfm_side(raw), ref)}
assert res["samples.Tran"].verdict == "mismatch"
assert "row_length_disagreements=1" in res["samples.Tran"].detail
def test_zc_frequency_na_and_above_range():
res = _results("T1905KDW.5F0W") # its JobNumber: test_the_job_number_matches_blastware
assert res["TranZCFreq"].verdict == "no_reference" # N/A
assert res["VertZCFreq"].verdict == "sfm_blank" # >100, SFM has no flag yet
def test_mic_units_pick_the_conversion():
res = _results("T004JTRF.ME0H") # psi(L)
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank"
fields = set(_results("R352HFZ7.530H")) # no mic
assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields)
# ── Task 4: carve-outs ──────────────────────────────────────────────────────
from minimateplus.decode_check_carveouts import CARVEOUTS # noqa: E402
def test_clipped_normal_range_is_accepted():
# Blastware: Tran 5.445, Vert 6.310, Long OORANGE, PVS OORANGE; SFM Long 10.005, PVS 11.55
res = _results("T438HGTZ.B30W", CARVEOUTS)
assert res["TranPPV"].verdict == "match" and res["VertPPV"].verdict == "match"
for f in ("LongPPV", "PeakVectorSum"):
assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation")
def test_a_clipped_sensitive_event_is_accepted_at_its_own_ceiling():
# SFM reads the 1.250 range from the file; the clipped channels sit at 1.2506.
res = _results("M007HVWF.K30W", CARVEOUTS)
assert res["GeoRange"].verdict == "match" and res["samples.Tran"].verdict == "match"
for f in ("TranPPV", "PeakVectorSum"):
assert (res[f].verdict, res[f].carveout) == ("accepted", "saturation")
def test_the_carveout_never_accepts_an_8x_value():
# What SFM produced while it assumed Normal on a Sensitive unit: 8x high.
# The saturation rule must leave it a mismatch.
raw = (FIX / "M007HVWF.K30W").read_bytes()
side = sfm_side(raw)
side.values.update(TranPPV=10.005, VertPPV=10.005, LongPPV=10.005, PeakVectorSum=17.33)
side.geo_ips_per_count = 10.0 / 32000
res = {r.field: r for r in compare(side, parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML"),
CARVEOUTS)}
assert res["TranPPV"].verdict == "mismatch" and res["samples.Tran"].verdict == "mismatch"
assert res["PeakVectorSum"].verdict == "mismatch"
def test_every_carveout_has_evidence():
assert all(c.id and c.fields and len(c.evidence) > 40 for c in CARVEOUTS)
def test_pvs_carveout_needs_oorange_from_blastware():
raw = (FIX / "T438HGTZ.B30W").read_bytes()
ref = parse_xml_report_file(FIX / "T438HGTZ_B30W_XML.XML")
ref.scalars["PeakVectorSum"] = "10.392" # a vector sum may exceed the range unclipped
res = {r.field: r for r in compare(sfm_side(raw), ref, CARVEOUTS)}
assert res["PeakVectorSum"].verdict == "mismatch"
def test_pvs_carveout_needs_the_clipped_channel_at_the_ceiling():
# 1.250 range, Blastware PVS OORANGE, but no channel Blastware clamped: an
# UNclipped channel's 8x value landing in the 1.250 band must not let a vector
# sum through, even one inside the sqrt(3) bound.
raw = (FIX / "M007HVWF.K30W").read_bytes()
ref = parse_xml_report_file(FIX / "M007HVWF_K30W_XML.XML")
ref.scalars.update(TranPPV="0.157", VertPPV="0.157", LongPPV="0.157")
side = sfm_side(raw)
side.values.update(TranPPV=1.256, PeakVectorSum=2.0)
res = {r.field: r for r in compare(side, ref, CARVEOUTS)}
assert res["PeakVectorSum"].verdict == "mismatch"
def test_interval_mic_psi_matches():
# psi(L) report: every interval's "MicL Peak psi(L)" now converts right
assert _results("T004JTRF.ME0H")["intervals.MicL Peak psi(L)"].verdict == "match"
def test_a_sensitive_range_event_now_matches():
gr = FIX.parent / "geo-range-11-01-26"
raw = (gr / "K557J1KB.RQ0W").read_bytes()
res = {r.field: r for r in compare(sfm_side(raw), parse_xml_report_file(gr / "K557J1KB_RQ0W_XML.XML"))}
for f in ("GeoRange", "TranPPV", "VertPPV", "LongPPV", "PeakVectorSum",
"samples.Tran", "samples.Vert", "samples.Long"):
assert res[f].verdict == "match", (f, res[f])
def test_the_job_number_matches_blastware():
assert _results("T1905KDW.5F0W", CARVEOUTS)["JobNumber"].verdict == "match"
def test_a_hidden_job_number_is_not_reported():
# Flag off: Blastware prints no JobNumber, and SFM's side reports none either.
assert sfm_side((FIX / "R352HFZ7.530H").read_bytes()).job_number is None
def test_a_job_number_only_sfm_shows_is_a_mismatch():
side = sfm_side((FIX / "R352HFZ7.530H").read_bytes())
side.job_number = "1"
res = {r.field: r for r in compare(side, parse_xml_report_file(FIX / "R352HFZ7_530H_XML.XML"))}
assert res["JobNumber"].verdict == "mismatch"
@pytest.mark.parametrize("stem", ["T193KR5M.X90H", "K440HA3C.JM0H"])
def test_a_loud_short_histogram_matches_blastware(stem):
hd = FIX.parent / "histogram-decode-11-02-26"
res = {r.field: r for r in compare(sfm_side((hd / stem).read_bytes()),
parse_xml_report_file(hd / (stem.replace(".", "_", 1) + "_XML.XML")),
CARVEOUTS)}
for f in ("NumberofIntervals", "intervals.Tran Peak in/s", "intervals.Vert Peak in/s",
"intervals.Long Peak in/s"):
assert res[f].verdict == "match", (f, res[f])
def _count_case(extra, drop_rows=0):
jf = FIX.parent / "job-number-11-02-26"
ref = parse_xml_report_file(jf / "T438I4V5_DJ0H_XML.XML")
rows = len(ref.intervals)
ref.scalars["NumberofIntervals"] = f"{rows + extra}.00"
if drop_rows:
ref.intervals = ref.intervals[:-drop_rows]
side = sfm_side((jf / "T438I4V5.DJ0H").read_bytes())
return {r.field: r for r in compare(side, ref, CARVEOUTS)}["NumberofIntervals"]
def test_blastware_counting_the_monitoring_time_is_accepted():
# Blastware's Number of Intervals is (stop - start) / interval. When the
# unit never wrote the last minute, Blastware's own table lists one block
# fewer, and SFM matches the table (T193KSWP.FF0H: 2,880 against 2,850 rows).
r = _count_case(30)
assert (r.verdict, r.carveout) == ("accepted", "interval-count-is-duration")
def test_the_count_carveout_needs_blastwares_own_table_to_agree_with_sfm():
assert _count_case(30, drop_rows=1).verdict == "mismatch"