fix(histogram_codec): read multi-interval blocks big-endian from byte 5, mic on and off (#47, #49)

Measured 2026-10-26.  A sub-minute histogram block is [00][segment][ctr LE][0a]
(5 bytes), then one record per interval of BIG-endian peak / half-period pairs
per channel, then 0000 and one more word, then a 7-byte trailer.  A record is 20
bytes with the mic and 16 without (4 x channels + 4); the standard 32-byte block
is the same thing holding one record.  The last block is short, not padded: it
holds only the intervals recorded and ends on 9c 06 00 42.

#47: a mic-off histogram (16-byte records) decoded to nothing, so a Blastware
import carried no histogram data and SFM's download check would refuse it.
BE9441's K441LTOK.QZ0 (2 s, 22 intervals; fixture) now matches its Blastware
export on 66/66 peaks and 66/66 frequencies.

#49: the old reader took the mic-on records as little-endian from byte 6 -- the
same bytes shifted by one, identical while every high byte is zero.  It also
required byte 5 to be 0 (the first record's Tran peak high byte) and read the
last block at full stride, trimming what it overran.

Regression over every DL2 histogram with a Blastware ASCII export (13,089
files, interval counts + every geo peak, frequency and mic dB): old reader
13,087 exact, new 13,089.  The two the old one got wrong were one interval each:
K440KZP4.560H #4764 (Long half-period 1 read as 257, mic peak 389 as 133) and
M462KZUD.6R0H #145 (mic peak 6 read as 262).

Walk: blocks follow by block_ctr + 1, or the next segment every 256 blocks; the
last block is bounded by its terminal tail; with no terminal tail the old
trimming rule remains as the fallback.  Mic-off records give m_peak None and an
empty MicL channel, as a mic-off waveform does.  Inferred, not yet seen in a
file: mic-off 1-minute (28-byte) and 15 s / 5 s mic-off strides.

Not fixed here, noted on #47: half_period_to_hz assumes 1024 sps (512/hp); the
2048-sps histogram's frequencies are 1024/hp.

Operational: a decoder change -- needs a TOOL_VERSION bump at release, then
backfill_sidecars.py + backfill_event_shape.py (~2 h on the NAS) to regenerate
stored histograms.  No schema change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-26 18:30:09 -04:00
1 parent 6690434ecf
commit dfc5aefef7
5 files changed
+410 -140

No files matched your search

Binary file not shown.
@@ -0,0 +1,72 @@
"Event Type : Full Histogram"
"Serial Number : BE9441"
"Version : V 10.72-8.17 MiniMate Plus"
"File Name : K441LTOK.QZ0"
"Histogram Start Time : 16:06:35"
"Histogram Start Date : October 26, 2026"
"Histogram Stop Time : 16:07:21"
"Histogram Stop Date : October 26, 2026"
"Number of Intervals : 22.00"
"Interval Size : 2 seconds "
"Sample Rate : 2048 sps"
"Battery Level : 6.8 Volts"
"Calibration : October 6, 2026 by Instantel"
"Units : in/s and "
"Project: : TestUnit-Minimate"
"Client: : Terra-Mechanics"
"User Name: : Terra-Mechanics Inc. - Harrison"
"Seis. Loc: : Test unit 1"
"Geo Range : 10.000 in/s"
"Tran PPV : 0.250 in/s"
"Vert PPV : 1.080 in/s"
"Long PPV : 0.195 in/s"
"Tran ZC Freq : 16.8 Hz"
"Vert ZC Freq : 22 Hz"
"Long ZC Freq : 19.3 Hz"
"Tran Peak Time : 16:06:45"
"Tran Peak Date : October 26, 2026"
"Vert Peak Time : 16:06:49"
"Vert Peak Date : October 26, 2026"
"Long Peak Time : 16:06:43"
"Long Peak Date : October 26, 2026"
"Peak Vector Sum : 1.083 in/s"
"Peak Vector Sum Time : 16:06:49"
"Peak Vector Sum Date : October 26, 2026"
"Tran Test Freq : 7.3 Hz"
"Tran Test Ratio : 4.5"
"Tran Test Results : Passed"
"Vert Test Freq : 7.4 Hz"
"Vert Test Ratio : 3.5"
"Vert Test Results : Passed"
"Long Test Freq : 7.3 Hz"
"Long Test Ratio : 4.2"
"Long Test Results : Passed"
"Monitor Log(s)"
"Oct 26 /26 16:06:34 Oct 26 /26 16:07:21 Event recorded. (Keyboard Exit)"
"PC SW Version : V 10.74"
Tran Tran Vert Vert Long Long Geo
PPV Freq PPV Freq PPV Freq PVS
Time in/s Hz in/s Hz in/s Hz in/s
October 26, 2026
16:06:37 0.040 21 0.060 21 0.025 21 0.065
16:06:39 0.030 12.8 0.030 16.5 0.015 73 0.034
16:06:41 0.010 >200 0.010 >200 0.010 >200 0.015
16:06:43 0.230 26 0.400 17.4 0.195 19.3 0.461
16:06:45 0.250 16.8 0.120 24 0.135 20 0.255
16:06:47 0.015 20 0.020 10.7 0.015 39 0.022
16:06:49 0.235 33 1.080 22 0.165 20 1.083
16:06:51 0.015 19.7 0.040 19.0 0.020 25 0.043
16:06:53 0.085 4.3 0.140 3.0 0.115 3.4 0.185
16:06:55 0.045 2.9 0.140 2.9 0.120 2.8 0.181
16:06:57 0.015 31 0.010 >200 0.010 >200 0.015
16:06:59 0.010 >200 0.010 >200 0.010 >200 0.015
16:07:01 0.010 >200 0.010 >200 0.010 >200 0.015
16:07:03 0.010 >200 0.010 >200 0.010 >200 0.015
16:07:05 0.015 114 0.010 >200 0.010 >200 0.016
16:07:07 0.010 >200 0.010 >200 0.010 >200 0.015
16:07:09 0.010 >200 0.010 >200 0.010 >200 0.015
16:07:11 0.010 >200 0.010 >200 0.010 >200 0.015
16:07:13 0.045 4.0 0.055 3.4 0.055 5.7 0.066
16:07:15 0.055 5.0 0.070 3.0 0.075 2.2 0.111
16:07:17 0.010 >200 0.010 >200 0.010 >200 0.015
16:07:19 0.010 >200 0.010 >200 0.010 >200 0.015
+13 -6
View File
@@ -509,8 +509,10 @@ def test_marker_is_single_byte_not_uint16():
# followed by 2 words (first is 0x0000)
# [-6:] 6-byte block trailer
#
# NOTE the endianness flip: the standard 32-byte block is big-endian, this
# variant is little-endian.
# ⚠ RETRACTED 2026-10-26 (#49): "the standard block is big-endian, this variant
# little-endian" -- both are big-endian from byte 5 (histogram_codec.py). The
# builder below writes little-endian from byte 6, which reads identically while
# every value is under 256.
#
# Ground truth: BE9440/K440L3AQ.T70H (15 s intervals, 5,710 of them) decodes
# with 17,130/17,130 geo peak counts, 22,840/22,840 frequencies and
@@ -556,14 +558,19 @@ def test_multi_interval_block_decodes_all_four_channels():
assert recs[1]["t_peak"] == 5 and recs[1]["m_halfp"] == 12
def test_multi_interval_values_are_little_endian():
"""The standard 32-byte block is big-endian; this variant is not.
def test_multi_interval_values_are_not_little_endian_from_byte_6():
"""RETRACTED 2026-10-26 (#49): the records are BIG-endian from byte 5.
A peak of 0x0100 must decode as 256, not 1.
This test once pinned "a peak of 0x0100 written little-endian from byte 6
decodes as 256". Those bytes (``00 | 00 01``) read big-endian from byte 5
are a Tran peak of 0 and a half-period of 1 -- the right reading, per
Blastware. The two models agree whenever the high bytes are zero, which
is why this builder's other tests pass under both; see
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)
assert walk_multi_interval_blocks(body)[0]["t_peak"] == 0x0100
assert walk_multi_interval_blocks(body)[0]["t_peak"] != 0x0100
def test_decode_histogram_body_falls_back_to_the_variant():
+141
View File
@@ -0,0 +1,141 @@
"""Multi-interval histogram blocks, mic on and mic off (issues #47, #49).
Measured 2026-10-26:
* A sub-minute histogram packs one minute of intervals per block:
``[00][segment][ctr LE][0a]`` (5 bytes), then one record per interval of
BIG-endian peak / half-period pairs per channel, then ``0000`` and one more
word, then a 7-byte trailer. A record is 20 bytes with the mic and 16
without (``4 * channels + 4``); the standard 32-byte block is the same thing
with one record.
* The last block is SHORT, not padded: it holds only the intervals recorded and
ends in ``9c 06 00 42`` (K440L3AQ: 1,427 x 4 + 2 = 5,710, Blastware's count).
* #47: BE9441's mic-off 2-second histogram (fixture) decoded to nothing. Read
as above, its 22 intervals match Blastware's export: 66/66 peaks, 66/66
frequencies.
* #49: the old reader took the mic-on records as little-endian from byte 6 --
the same bytes shifted by one, identical whenever the high bytes are zero.
Across the 770 archive histograms with an export it disagreed with Blastware
on exactly 1 of 10,715,315 intervals (K440KZP4.560H #4764).
"""
from __future__ import annotations
import os
import re
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.histogram_codec import ( # noqa: E402
decode_histogram_body,
decode_histogram_body_full,
walk_multi_interval_blocks,
)
FIX = Path(__file__).parent / "fixtures" / "histogram-mic-off-10-26-26"
TERMINAL = b"\x9c\x06\x00\x42"
def _body(path: Path) -> bytes:
raw = path.read_bytes()
return raw[raw.find(b"STRT") + 21:]
def _ascii_rows(path: Path) -> list:
return [line.split() for line in path.read_text(errors="replace").splitlines()
if re.match(r"^\d\d:\d\d:\d\d\s", line)]
def _block(records, *, ctr=0x0100, seg=0, mic=True, last=False) -> bytes:
"""One block: records are (T, Tf, V, Vf, L, Lf[, M, Mf]) tuples, BIG-endian."""
b = bytearray([0x00, seg, ctr & 0xFF, ctr >> 8, 0x0A])
for r in records:
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 += b"\xfc\xf3\x00" + (TERMINAL if last else b"\x5a\x0a\x00\x00")
return bytes(b)
# -- #47: mic off -------------------------------------------------------------
def test_the_mic_off_histogram_matches_blastwares_export():
recs = decode_histogram_body_full(_body(FIX / "K441LTOK.QZ0"))
rows = _ascii_rows(FIX / "K441LTOK_QZ0_ASCII.TXT")
assert recs is not None and len(recs) == len(rows) == 22
num = 2048 / 2 # "Sample Rate : 2048 sps"
for r, row in zip(recs, rows):
for c, ch in enumerate("tvl"):
assert r[f"{ch}_peak"] * 0.005 == pytest.approx(float(row[1 + 2 * c]), abs=1e-9)
f, want = num / r[f"{ch}_halfp"], row[2 + 2 * c]
if want.startswith(">"):
assert f > 200
else:
assert f == pytest.approx(float(want), rel=0.051)
assert r["m_peak"] is None and r["m_halfp"] is None
def test_a_mic_off_histogram_has_no_mic_channel():
ch = decode_histogram_body(_body(FIX / "K441LTOK.QZ0"))
assert ch is not None
assert [len(ch[c]) for c in ("Tran", "Vert", "Long", "MicL")] == [22, 22, 22, 0]
assert max(ch["Vert"]) * 0.005 == pytest.approx(1.080) # Blastware's Vert PPV
def test_mic_off_blocks_walk_in_sixteen_byte_records():
a = [(1, 2, 3, 4, 5, 6)] * 30
body = _block(a, mic=False) + _block([(7, 8, 9, 10, 11, 12)] * 3, ctr=0x0101, mic=False,
last=True) + b"setup block follows"
recs = walk_multi_interval_blocks(body)
assert len(recs) == 33
assert (recs[30]["t_peak"], recs[30]["l_halfp"]) == (7, 12)
# -- #49: mic on, big-endian from byte 5 ---------------------------------------
def test_mic_on_records_are_big_endian():
# K440KZP4.560H #4764's shape: a mic peak >= 256 next to a Long half-period of 1.
# Read little-endian from byte 6, that half-period came out 257 (~2 Hz, not >100).
iv = [(10, 2, 11, 1, 10, 1, 0x0123, 4)] * 4
body = _block(iv) + _block(iv, ctr=0x0101, last=True)
r = walk_multi_interval_blocks(body)[0]
assert (r["l_halfp"], r["m_peak"], r["m_halfp"]) == (1, 0x0123, 4)
def test_a_loud_first_interval_does_not_end_the_walk():
# byte 5 is the first record's Tran peak high byte, not a constant 0
iv = [(0x0150, 9, 1, 1, 1, 1, 1, 1)] + [(1, 1, 1, 1, 1, 1, 1, 1)] * 3
body = _block(iv) + _block(iv, ctr=0x0101) + _block(iv, ctr=0x0102, last=True)
recs = walk_multi_interval_blocks(body)
assert len(recs) == 12 and recs[8]["t_peak"] == 0x0150
# -- the last block is short, bounded by its terminal tail ---------------------
def test_the_last_block_holds_only_its_intervals():
iv = [(1, 1, 2, 2, 3, 3, 4, 4)]
tail = [(5, 5, 6, 6, 7, 7, 8, 8)] * 2
body = (_block(iv * 4) + _block(tail, ctr=0x0101, last=True)
+ bytes([0x00, 0x00, 0x01, 0x01, 0x0A]) + b"\x07" * 60) # setup data after it
recs = walk_multi_interval_blocks(body)
assert len(recs) == 6
assert recs[-1]["t_peak"] == 5
def test_a_single_short_block_decodes():
body = _block([(4, 9, 4, 9, 4, 9, 2, 2)] * 7, last=True) + b"\x00" * 40
recs = walk_multi_interval_blocks(body)
assert len(recs) == 7 and recs[0]["m_peak"] == 2
def test_the_walk_crosses_a_segment_boundary():
# 256 blocks per segment: block_ctr restarts at 0x0100 and segment_id steps.
iv = [(1, 1, 2, 2, 3, 3, 4, 4)] * 4
body = (_block(iv, ctr=0x01FE) + _block(iv, ctr=0x01FF)
+ _block(iv, ctr=0x0100, seg=1) + _block(iv, ctr=0x0101, seg=1, last=True))
recs = walk_multi_interval_blocks(body)
assert len(recs) == 16 and recs[-1]["segment_id"] == 1