diff --git a/minimateplus/decode_check_carveouts.py b/minimateplus/decode_check_carveouts.py index 7122f57..244edd2 100644 --- a/minimateplus/decode_check_carveouts.py +++ b/minimateplus/decode_check_carveouts.py @@ -86,4 +86,24 @@ SATURATION = Carveout( applies=_saturation, ) -CARVEOUTS: tuple[Carveout, ...] = (SATURATION,) +def _interval_count_is_duration(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool: + """Blastware's count exceeds the intervals in its own table, and SFM decoded + exactly the table's.""" + p = _printed_number(res.bw or "") + n = sfm.values.get("NumberofIntervals") + rows = len(ref.intervals or []) + return p is not None and n is not None and rows == n and p[0] > n + + +INTERVAL_COUNT_IS_DURATION = Carveout( + id="interval-count-is-duration", + fields=("NumberofIntervals",), + evidence=("Blastware's Number of Intervals is (stop - start) / interval from the file's " + "footer times -- exact on T193KSWP.FF0H (2,880), M462KSWR.1R0H (1,650) and " + "T193KY0A.740H (6,390). Its own interval table lists the intervals the file " + "holds: one block (30 at 2 s) fewer when the unit never wrote the last minute. " + "2026-11-02."), + applies=_interval_count_is_duration, +) + +CARVEOUTS: tuple[Carveout, ...] = (SATURATION, INTERVAL_COUNT_IS_DURATION) diff --git a/minimateplus/event_file_io.py b/minimateplus/event_file_io.py index dd486b3..f2a6dfa 100644 --- a/minimateplus/event_file_io.py +++ b/minimateplus/event_file_io.py @@ -1170,18 +1170,37 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event: # mode, synthetic test input), fall back to empty channels — the # rest of the event (timestamp, waveform_key, project strings) is # still recoverable and useful. - decoded = decode_waveform_v2(body) - # Discriminator for the timestamp logic below: a waveform (trigger) event - # vs a histogram window. Keyed on the codec, not the filename — the - # save_imported_bw path passes a tmp ".bw" name whose extension lies. - is_waveform_body = decoded is not None - if decoded is None: + # + # The record type comes from the bytes: STRT[18] (#41), 0x46 / 0x0A on + # 70,041 / 70,041 DL2 files. It picks the codec. Trying the waveform codec + # first handed it BE9440 / BE9557 / BE17354's 2018 5 s histograms, which it + # accepted and returned ~5x too many "samples" for. Only an unknown type + # falls back to the old trial order. The filename's last letter is only a + # cross-check -- SFM's own downloads have no name, and a manual download's + # (".QZ0") carries no type at all. + type_byte = strt_raw[18] + record_type = _RECORD_TYPE_BY_STRT.get(type_byte) + problems = [] + if record_type is None: + problems.append(f"unknown record type byte 0x{type_byte:02x} at STRT[18]") + if record_type == "Histogram": decoded = decode_histogram_body(body) + is_waveform_body = False + elif record_type == "Waveform": + decoded = decode_waveform_v2(body) + is_waveform_body = True + else: + decoded = decode_waveform_v2(body) + is_waveform_body = decoded is not None + if decoded is None: + decoded = decode_histogram_body(body) if decoded is None: log.warning( "%s: body codec failed to decode (body starts %s) — " "raw_samples will be empty", label, body[:8].hex(" "), ) + if record_type is not None: + problems.append(f"the {record_type.lower()} codec could not decode the body") samples = {"Tran": [], "Vert": [], "Long": [], "MicL": []} else: samples = decoded_to_adc_counts(decoded) @@ -1190,13 +1209,8 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event: ev = Event(index=-1) if strt_fields.get("waveform_key"): ev._waveform_key = bytes.fromhex(strt_fields["waveform_key"]) - # The record type comes from the bytes: STRT[18] (#41). The filename's - # last letter is only a cross-check -- SFM's own downloads have no name, - # and a manual download's (".QZ0") carries no type at all. - type_byte = strt_raw[18] - ev.record_type = _RECORD_TYPE_BY_STRT.get(type_byte) - if ev.record_type is None: - ev.decode_problems.append(f"unknown record type byte 0x{type_byte:02x} at STRT[18]") + ev.record_type = record_type + ev.decode_problems.extend(problems) named_type = derive_record_type_from_filename(name, default=None) if name else None if named_type is not None and ev.record_type is not None and named_type != ev.record_type: log.warning("%s: record type %s from the file disagrees with the filename's %s; " diff --git a/minimateplus/histogram_codec.py b/minimateplus/histogram_codec.py index 6978806..3a4f7e6 100644 --- a/minimateplus/histogram_codec.py +++ b/minimateplus/histogram_codec.py @@ -439,16 +439,34 @@ def _stride(rec: int, n: int) -> int: def _records_plausible(body: bytes, off: int, rec: int, m: int) -> bool: - """Every record's zero word is 0000 -- what tells a 16-byte layout from a - 20-byte one when both strides happen to fit (492 = 12 + 16x30 = 12 + 20x24).""" + """Every record's last 4 bytes are its vector sum squared, consistent with + its channel peaks: at least the largest peak, at most sqrt(3) times it (one + unit of rounding either way). That is what tells a 16-byte layout from a + 20-byte one when both strides happen to fit (492 = 12 + 16x30 = 12 + 20x24); + misread, those bytes are other fields. Holds on 34,502,955 / 34,502,955 DL2 + sub-minute intervals (2026-11-02). + + ⚠ RETRACTED 2026-11-02: "every record's zero word is 0000". It is the high + word of the PVS², non-zero on any interval above 1.28 in/s, so a short + histogram with one loud interval was not recognised at all (T193KR5M.X90H, + K440HA3C.JM0H decoded to nothing).""" z = rec - 4 for k in range(m): q = off + _MULTI_HEADER_LEN + rec * k - if q + rec > len(body) or body[q + z] or body[q + z + 1]: + if q + rec > len(body): + return False + peak = max((body[q + i] << 8) | body[q + i + 1] for i in (0, 4, 8)) + if not _pvs_consistent(peak, int.from_bytes(body[q + z:q + z + 4], "big")): return False return True +def _pvs_consistent(peak: int, pvs_sq: int) -> bool: + """A record's vector sum squared against its largest geo peak, one unit of + rounding either way: peak <= PVS <= sqrt(3) * peak.""" + return max(peak - 1, 0) ** 2 <= pvs_sq <= 3 * (peak + 1) ** 2 + + def detect_multi_interval_layout(body: bytes) -> Optional[Tuple[int, int]]: """``(record_len, per_block)`` of a multi-interval body, or None. @@ -543,8 +561,8 @@ def walk_multi_interval_blocks(body: bytes, recs = [_decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off) for k in range(max(m, 0))] for k, r in enumerate(recs): - if (r["meta_var"][:2] != b"\x00\x00" - or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS): + peak = max(r["t_peak"], r["v_peak"], r["l_peak"]) + if not _pvs_consistent(peak, r["pvs_sq"]) or peak > _GEO_MAX_COUNTS: del recs[k:] break out.extend(recs) diff --git a/tests/fixtures/histogram-decode-11-02-26/K440HA3C.JM0H b/tests/fixtures/histogram-decode-11-02-26/K440HA3C.JM0H new file mode 100755 index 0000000..bd9bfbc Binary files /dev/null and b/tests/fixtures/histogram-decode-11-02-26/K440HA3C.JM0H differ diff --git a/tests/fixtures/histogram-decode-11-02-26/K440HA3C_JM0H_XML.XML b/tests/fixtures/histogram-decode-11-02-26/K440HA3C_JM0H_XML.XML new file mode 100755 index 0000000..1bab82a --- /dev/null +++ b/tests/fixtures/histogram-decode-11-02-26/K440HA3C_JM0H_XML.XML @@ -0,0 +1,137 @@ + + +8.0 +Full Histogram +BE9440 +V 10.72-8.17 MiniMate Plus +K440HA3C.JM0H +11:42:58 +2018-02-10 +11:43:34 +2018-02-10 + +Tran +Vert +Long +MicL + +8.00 +5 seconds +1024 sps +6.8 Volts +January 11, 2018 by Instantel +in/s and dB(L) +Villanova Stadium Station - Seis. Loc #2 +D'Angleo Brothers, Inc +Terra-Mechanics, Inc - D Harrison +Loc # 2 - OutBound Track + +10.000 +in/s + + +0.390 +in/s + + +2.645 +in/s + + +0.095 +in/s + + +85 +Hz + + +73 +Hz + + +43 +Hz + +11:43:33 +2018-02-10 +11:43:33 +2018-02-10 +11:43:33 +2018-02-10 + +2.656 +in/s + +11:43:33 +2018-02-10 +Linear Weighting + +126.4 +dB(L) + +11:43:18 +2018-02-10 + +>100 +Hz + +7.2 Hz. +4.3 +Passed +7.5 Hz. +3.7 +Passed +7.4 Hz. +4.1 +Passed +19.7 Hz. +634 mv +Passed + + +2018-02-10 11:42:57 - 2018-02-10 11:43:34 "Event Recorded Modem Exit" + + + Tran Peak in/s + Tran Freq Hz + Vert Peak in/s + Vert Freq Hz + Long Peak in/s + Long Freq Hz + Geo PVS in/s + MicL Peak psi(L) + MicL Peak dB(L) + MicL Freq Hz + + + + +0.005>1000.005>1000.005N/A0.0090.00091.4834 + + +0.005>1000.005>1000.005>1000.0090.000100.0>100 + + +0.005>1000.005>1000.005>1000.0090.00087.96>100 + + +0.010>1000.015>1000.010>1000.0160.006126.4>100 + + +0.005>1000.005>1000.005>1000.0090.004122.043 + + +0.005>1000.010>1000.005>1000.0110.00087.96>100 + + +0.390852.645730.095432.6560.00093.98>100 + + +0.005>1000.005>1000.005>1000.0070.00087.96>100 + + + + + + diff --git a/tests/fixtures/histogram-decode-11-02-26/K440HDXX.XH0H b/tests/fixtures/histogram-decode-11-02-26/K440HDXX.XH0H new file mode 100755 index 0000000..f50105a Binary files /dev/null and b/tests/fixtures/histogram-decode-11-02-26/K440HDXX.XH0H differ diff --git a/tests/fixtures/histogram-decode-11-02-26/T193KR5M.X90H b/tests/fixtures/histogram-decode-11-02-26/T193KR5M.X90H new file mode 100755 index 0000000..435b225 Binary files /dev/null and b/tests/fixtures/histogram-decode-11-02-26/T193KR5M.X90H differ diff --git a/tests/fixtures/histogram-decode-11-02-26/T193KR5M_X90H_XML.XML b/tests/fixtures/histogram-decode-11-02-26/T193KR5M_X90H_XML.XML new file mode 100755 index 0000000..ba2492c --- /dev/null +++ b/tests/fixtures/histogram-decode-11-02-26/T193KR5M_X90H_XML.XML @@ -0,0 +1,140 @@ + + +8.0 +Full Histogram +BE18193 +V 10.72-8.17 MiniMate Plus +T193KR5M.X90H +17:22:21 +2024-10-07 +17:22:38 +2024-10-07 + +Tran +Vert +Long +MicL + +9.00 +2 seconds +1024 sps +6.3 Volts +July 10, 2024 by Instantel +in/s and dB(L) +I-80- North Fork Bridges-543 Plank Rd +Fay Company +Terra-Mechanics Inc - Harrison +Loc #1 -Main Line- Area 2 - 543 Plank Rd + +10.000 +in/s + + +2.290 +in/s + + +5.515 +in/s + + +1.520 +in/s + + +11 +Hz + + +34 +Hz + + +18 +Hz + +17:22:37 +2024-10-07 +17:22:37 +2024-10-07 +17:22:37 +2024-10-07 + +5.818 +in/s + +17:22:37 +2024-10-07 +Linear Weighting + +108.0 +dB(L) + +17:22:37 +2024-10-07 + +57 +Hz + +7.6 Hz. +3.7 +Passed +7.7 Hz. +3.5 +Passed +7.5 Hz. +3.6 +Passed +0.0 Hz. +0 mv +Check + + +2024-10-07 17:22:20 - 2024-10-07 17:22:38 "Event Recorded Modem Exit" + + + Tran Peak in/s + Tran Freq Hz + Vert Peak in/s + Vert Freq Hz + Long Peak in/s + Long Freq Hz + Geo PVS in/s + MicL Peak psi(L) + MicL Peak dB(L) + MicL Freq Hz + + + + +0.005>1000.005>1000.010>1000.0110.000104.264 + + +0.005>1000.005>1000.005>1000.0090.000104.264 + + +0.005>1000.005>1000.005>1000.0090.000104.264 + + +0.005>1000.005>1000.005>1000.0090.000104.264 + + +0.005>1000.005>1000.005>1000.0090.000104.264 + + +0.005>1000.005>1000.005>1000.0090.000104.273 + + +0.005>1000.010>1000.005>1000.0110.000104.264 + + +2.290115.515341.520185.8180.001108.057 + + +0.010>1000.0202.90.005>1000.0220.001104.964 + + + + + + diff --git a/tests/test_bw_file_fields.py b/tests/test_bw_file_fields.py index 1dc7b6a..eb9f843 100644 --- a/tests/test_bw_file_fields.py +++ b/tests/test_bw_file_fields.py @@ -303,3 +303,35 @@ def test_the_h5_carries_the_job_number(tmp_path): event_hdf5.write_event_hdf5(tmp_path / "e.h5", ev, serial="BE9557") with h5py.File(tmp_path / "e.h5", "r") as f: assert (bool(f.attrs["job_number_enabled"]), int(f.attrs["job_number"])) == (False, 802) + + +# ── Histograms: the codec follows the record type, and loud short blocks ───── +_HD = "histogram-decode-11-02-26" + + +def test_a_histogram_body_goes_to_the_histogram_codec(): + # BE9440, 2018, 5 s intervals. The waveform codec accepted this body when + # it was tried first, and returned ~5x too many "samples". Blastware's + # report: 6,976 intervals, PPV 0.180 / 0.195 / 0.215, PVS 0.270, start + # 2018-04-26 07:53:41. + ev = read_blastware_file(_FIX / _HD / "K440HDXX.XH0H") + assert ev.record_type == "Histogram" + assert len(ev.raw_samples["Tran"]) == 6976 + pv = ev.peak_values + for got, want in zip((pv.tran, pv.vert, pv.long, pv.peak_vector_sum), + (0.180, 0.195, 0.215, 0.270)): + assert abs(got - want) <= 0.0005 + 1e-9, (got, want) + ts = ev.timestamp + assert (ts.year, ts.month, ts.day) == (2018, 4, 26) + + +@pytest.mark.parametrize("name,n", [ + ("T193KR5M.X90H", 9), # 2 s; its 8th interval is 5.8 in/s of vector sum + ("K440HA3C.JM0H", 8), # 5 s +]) +def test_a_loud_interval_does_not_hide_a_short_histogram(name, n): + # A short (one-block) sub-minute histogram is found by its record layout. + # An interval louder than 1.28 in/s has a vector sum squared above 65,535, + # which the old "first word is 0000" test rejected. + ev = read_blastware_file(_FIX / _HD / name) + assert len(ev.raw_samples["Tran"]) == n diff --git a/tests/test_decode_check.py b/tests/test_decode_check.py index b9848de..a37dca5 100644 --- a/tests/test_decode_check.py +++ b/tests/test_decode_check.py @@ -187,3 +187,37 @@ def test_a_job_number_only_sfm_shows_is_a_mismatch(): 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" diff --git a/tests/test_histogram_codec.py b/tests/test_histogram_codec.py index 74ed89c..9b6522a 100644 --- a/tests/test_histogram_codec.py +++ b/tests/test_histogram_codec.py @@ -525,18 +525,28 @@ from minimateplus.histogram_codec import ( # noqa: E402 def _mk_multi_block(intervals, seg=0, ctr=256): - """Build one multi-interval block from a list of 8-tuples.""" - b = bytearray() - b += bytes([0x00, seg]) - b += int(ctr).to_bytes(2, "little") - b += bytes([0x0A, 0x00]) + """Build one multi-interval block from a list of 8-tuples (T, Tf, V, Vf, L, + Lf, M, Mf) in the measured layout: big-endian from byte 5, each record ending + in its PVS squared -- here the largest geo peak squared, which every real + record is consistent with (34,502,955 / 34,502,955 DL2 intervals).""" + b = bytearray([0x00, seg]) + int(ctr).to_bytes(2, "little") + bytes([0x0A]) + for iv in intervals: + for v in iv: + b += int(v).to_bytes(2, "big") + b += (max(iv[0], iv[2], iv[4]) ** 2).to_bytes(4, "big") + b += bytes(7) + assert len(b) == 12 + 20 * len(intervals) + return bytes(b) + + +def _mk_legacy_le_block(intervals, seg=0, ctr=256): + """The retracted model's bytes: 8 x uint16 LITTLE-endian from byte 6.""" + b = bytearray([0x00, seg]) + int(ctr).to_bytes(2, "little") + bytes([0x0A, 0x00]) for iv in intervals: for v in iv: b += int(v).to_bytes(2, "little") - b += (0).to_bytes(2, "little") - b += (5).to_bytes(2, "little") + b += (0).to_bytes(2, "little") + (5).to_bytes(2, "little") b += bytes(6) - assert len(b) == 12 + 20 * len(intervals) return bytes(b) @@ -569,7 +579,7 @@ def test_multi_interval_values_are_not_little_endian_from_byte_6(): tests/test_histogram_multi_interval.py for the measured cases. """ ivs = [(0x0100, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1)] - body = _mk_multi_block(ivs) + _mk_multi_block(ivs, ctr=257) + body = _mk_legacy_le_block(ivs) + _mk_legacy_le_block(ivs, ctr=257) assert walk_multi_interval_blocks(body)[0]["t_peak"] != 0x0100 diff --git a/tests/test_histogram_multi_interval.py b/tests/test_histogram_multi_interval.py index 3a0511d..4547ac8 100644 --- a/tests/test_histogram_multi_interval.py +++ b/tests/test_histogram_multi_interval.py @@ -56,7 +56,7 @@ def _block(records, *, ctr=0x0100, seg=0, mic=True, last=False) -> bytes: assert len(r) == (8 if mic else 6) for v in r: b += int(v).to_bytes(2, "big") - b += b"\x00\x00" + b"\x00\x2d" # the zero word, then one more + b += (max(r[0], r[2], r[4]) ** 2).to_bytes(4, "big") # PVS², consistent as on real data b += b"\xfc\xf3\x00" + (TERMINAL if last else b"\x5a\x0a\x00\x00") return bytes(b)