merge: sub-minute histograms read big-endian from byte 5, mic on and off -- issues #47, #49

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-26 18:35:12 -04:00
commit 6ed46dc3a3
5 files changed
+410 -140

No files matched your search

+184 -134
View File
@@ -255,18 +255,25 @@ def walk_body(body: bytes) -> List[dict]:
def _walk_auto(body: bytes) -> List[dict]:
"""Pick the block model by signature strength, not by which returns first.
The multi-interval variant announces itself with consecutive block headers
at an exact ``12 + 20*n`` stride — far stronger evidence than a handful of
scattered standard-tail blocks, which a multi-interval body will also yield
by coincidence. Dispatching on "whichever decoder returns something"
handed 193 BE18193 files to the standard walker and produced peaks of
149 in/s against a 10 in/s full scale.
A multi-interval body announces itself with consecutive block headers at an
exact ``12 + record * n`` stride -- far stronger evidence than a handful of
scattered standard-tail blocks, which it will also yield by coincidence.
Dispatching on "whichever decoder returns something" handed 193 BE18193
files to the standard walker and produced peaks of 149 in/s against a
10 in/s full scale. A single short block (under a minute of intervals) has
no second header; it is tried after the standard walker, which a one-block
standard body satisfies with the same values.
"""
if detect_multi_interval_stride(body):
layout = detect_multi_interval_layout(body)
if layout and (_is_multi_header(body, _stride(*layout))
or layout[0] == 16):
recs = walk_multi_interval_blocks(body)
if recs:
return recs
return walk_body(body)
recs = walk_body(body)
if recs:
return recs
return walk_multi_interval_blocks(body) if layout else []
def decode_histogram_body(body: bytes) -> Optional[dict]:
@@ -291,7 +298,9 @@ def decode_histogram_body(body: bytes) -> Optional[dict]:
"Tran": [r["t_peak"] for r in records],
"Vert": [r["v_peak"] for r in records],
"Long": [r["l_peak"] for r in records],
"MicL": [r["m_peak"] for r in records],
# A mic-off histogram has no mic channel: an empty list, as a mic-off
# waveform's decode gives.
"MicL": [r["m_peak"] for r in records if r["m_peak"] is not None],
}
@@ -328,160 +337,201 @@ def geo_count_to_ins(count: int) -> float:
return count * _GEO_LSB_INS
# ── Multi-interval block variant (CONFIRMED 2026-08-26) ─────────────────────
# ── Multi-interval blocks (CONFIRMED 2026-08-26; re-read 2026-10-26) ─────────
#
# When the histogram interval is SHORTER than one minute, the device packs
# several intervals into a single block so that every block still covers
# exactly one minute of data:
# When the histogram interval is SHORTER than one minute, the device packs one
# minute of intervals into each block:
#
# interval size intervals/block stride
# 1 minute 1 32 <- the standard block above
# 15 seconds 4 92
# 2 seconds 30 612
# interval per block stride, mic on (20 B records) mic off (16 B)
# 1 minute 1 32 <- the standard block above 28 (inferred)
# 15 s 4 92 76 (inferred)
# 2 s 30 612 492 (inferred)
#
# stride = 12 + n_intervals * 20
# stride = 12 + per_block * record, record = 4 * channels + 4
#
# Block layout:
# Block layout (measured 2026-10-26, issues #47 and #49):
# [0] 0x00
# [1] segment_id (256 blocks per segment, same as the standard block)
# [2:4] block_ctr uint16 LE (0x0100.., resets each segment)
# [4] 0x0a marker
# [5] 0x00
# [6 ...] n x 20-byte interval records, each carrying 8 x uint16
# LITTLE-endian values:
# T_peak, T_halfperiod, V_peak, V_halfperiod,
# L_peak, L_halfperiod, M_peak, M_halfperiod
# then 2 more words; the first is 0x0000 on every real interval.
# [-6:] 6-byte block trailer
# [1] segment_id (256 blocks per segment, as in the standard block)
# [2:4] block_ctr uint16 LE
# [4] 0x0a
# [5 ...] one record per interval: per channel a BIG-endian uint16 peak and
# half-period (Tran, Vert, Long[, MicL]), then 0x0000, then one more
# word ("meta_var" keeps those 4 bytes)
# [-7:] trailer: 3 bytes, then the 4-byte tail -- 9c 06 00 42 on the
# stream's LAST block
#
# ⚠ ENDIANNESS: the standard 32-byte block is BIG-endian. This variant is
# LITTLE-endian. Do not share the accessor.
# The last block is SHORT, not padded: it holds only the intervals recorded and
# ends on 9c 06 00 42 (K440L3AQ.T70H: 1,427 x 4 + 2 = 5,710, Blastware's count;
# T193L0XM.CI0H: 30 + 21 = 51). Reading it at full stride ran into the setup
# data that follows, which is what the old "garbage slot" trimming cleaned up;
# that trimming survives only as the fallback for a stream with no 9c 06 00 42.
#
# These files previously decoded to nothing at all — 415 of them in the
# production snapshot, 216 on BE18193 (2 s intervals) and 199 on BE9440
# (15 s). Before that they were being accepted by the WAVEFORM codec, which
# returned garbage peaking up to 400x the device-reported PPV.
# ⚠ RETRACTED 2026-10-26: "8 x uint16 LITTLE-endian from byte 6, a 6-byte
# header with [5] == 0". That is the same bytes shifted by one: identical while
# every high byte is zero, which is why it matched Blastware on 10,715,314 of the
# 770 archive files' intervals -- and wrong on the 1 that was not (K440KZP4.560H
# #4764: a Long half-period of 1 read as 257, ">100 Hz" read as ~2 Hz). And
# byte 5 is the first record's Tran peak high byte, so a block whose first
# interval exceeded 1.275 in/s ended the old walk.
#
# Ground truth: BE9440/K440L3AQ.T70H (15 s intervals, 5,710 of them) decodes
# against its Blastware ASCII export with 17,130/17,130 geo peak counts,
# 22,840/22,840 frequencies and 5,710/5,710 mic dB(L) values matching exactly.
# Mic off (#47): BE9441's K441LTOK.QZ0 (2 s, 22 intervals, one short block)
# matches its Blastware export on 66/66 peaks and 66/66 frequencies. The mic-off
# strides above follow from the same layout; only the 2 s short block is
# measured.
#
# Ground truth, mic on: BE9440/K440L3AQ.T70H (15 s, 5,710 intervals) --
# 17,130 / 22,840 / 5,710 geo peaks, frequencies and mic dB(L), all exact.
_MULTI_HEADER_LEN = 6
_MULTI_RECORD_LEN = 20
_MULTI_TRAILER_LEN = 6
# At least 2 records: a 1-record block would have stride 12 + 20 = 32, which
# collides with the standard big-endian block and mis-decodes it.
_MULTI_MIN_RECORDS = 2
_MULTI_MAX_RECORDS = 64
_MULTI_HEADER_LEN = 5
_MULTI_TRAILER_LEN = 7
_MULTI_MAX_RECORDS = 64
_RECORD_LENS = (20, 16) # mic on (4 channels), mic off (3 channels)
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. A peak above
# this is physically impossible and marks buffer garbage in a partial block.
# Geo full scale in 16-count units: 10.000 in/s / 0.005 = 2000. Used only by
# the fallback trim of a stream with no terminal tail.
_GEO_MAX_COUNTS = 2000
def _is_multi_header(body: bytes, off: int) -> bool:
return (off + _MULTI_HEADER_LEN <= len(body)
and body[off] == 0x00
and body[off + 4] == 0x0A
and body[off + 5] == 0x00)
and body[off + 4] == 0x0A)
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
"""Block stride of a multi-interval histogram body, or None.
def _ctr(body: bytes, off: int) -> int:
return body[off + 2] | (body[off + 3] << 8)
Found by locating the second block header; validated against
``stride = 12 + n * 20`` and confirmed on a third block where present.
def _follows(body: bytes, off: int, nxt: int) -> bool:
"""A block header at ``nxt`` that continues the block at ``off``: block_ctr
one higher, or -- every 256 blocks -- the next segment (block_ctr restarts)."""
if not _is_multi_header(body, nxt):
return False
if body[nxt + 1] == body[off + 1]:
return (_ctr(body, nxt) - _ctr(body, off)) & 0xFFFF == 1
return body[nxt + 1] == (body[off + 1] + 1) & 0xFF
def _stride(rec: int, n: int) -> int:
return _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + rec * n
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)."""
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]:
return False
return True
def detect_multi_interval_layout(body: bytes) -> Optional[Tuple[int, int]]:
"""``(record_len, per_block)`` of a multi-interval body, or None.
Found from the second block header (block_ctr one higher), confirmed on a
third when present; a single short block is found from its terminal tail.
"""
if not _is_multi_header(body, 0):
return None
lo = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MIN_RECORDS
hi = _MULTI_HEADER_LEN + _MULTI_TRAILER_LEN + _MULTI_RECORD_LEN * _MULTI_MAX_RECORDS
for stride in range(lo, min(hi, len(body)) + 1, 2):
if (stride - 12) % _MULTI_RECORD_LEN:
continue
if not _is_multi_header(body, stride):
continue
# DECISIVE CHECK: consecutive blocks differ by exactly 1 in block_ctr.
# Without it this false-positives on ordinary standard-block bodies:
# those carry a header every 32 bytes, and 192 = 12 + 20*9 and
# 512 = 12 + 20*25 are both multiples of 32, so a stride "fits" while
# actually skipping 6 or 16 real blocks. Sampling a standard body at
# stride 192 handed 9,082 files to the wrong decoder and produced peaks
# of 149 in/s against a 10 in/s full scale.
def _ctr(o: int) -> int:
return body[o + 2] | (body[o + 3] << 8)
if (_ctr(stride) - _ctr(0)) & 0xFFFF != 1:
continue
# Confirm on a third block WHEN ONE IS ACTUALLY PRESENT. A body can
# be longer than two strides and still hold only two real blocks: a
# final *partial* block leaves trailing padding. E.g. 51 intervals at
# 2 s = one full 30-interval block + a 21-interval remainder, in a
# 2787-byte body — long enough to demand a third header at 1224 that
# does not exist. Requiring it unconditionally threw away the correct
# stride and the file decoded to nothing (BE18193 T193L0XM.CI0H).
# The block-counter check above is the decisive anti-false-positive
# test; this one is corroboration, so a missing third header means
# end-of-stream, not disqualification.
if (2 * stride + _MULTI_HEADER_LEN <= len(body)
and _is_multi_header(body, 2 * stride)):
if (_ctr(2 * stride) - _ctr(stride)) & 0xFFFF != 1:
for rec in _RECORD_LENS:
# A 20-byte record with one interval per block IS the standard 32-byte
# block, which walk_body reads; the mic-off one-minute block is not.
for n in range(2 if rec == 20 else 1, _MULTI_MAX_RECORDS + 1):
s = _stride(rec, n)
if s + _MULTI_HEADER_LEN > len(body):
break
if not _follows(body, 0, s):
continue
return stride
# The block-counter step is the decisive test: a standard body has a
# header every 32 bytes, and 192 = 12 + 20x9 skips 6 of them. A third
# block, when there is one, must follow too.
if (_is_multi_header(body, 2 * s) and not _follows(body, s, 2 * s)
and body[2 * s - 4:2 * s] != _BLOCK_TAIL_TERMINAL):
continue
if not _records_plausible(body, 0, rec, n):
continue
return rec, n
# One block only (a histogram shorter than a minute): bounded by its tail.
t = body.find(_BLOCK_TAIL_TERMINAL)
while t >= 0:
for rec in _RECORD_LENS:
span = t + 4 - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN
if span > 0 and span % rec == 0 and span // rec <= _MULTI_MAX_RECORDS \
and _records_plausible(body, 0, rec, span // rec):
return rec, span // rec
t = body.find(_BLOCK_TAIL_TERMINAL, t + 1)
return None
def detect_multi_interval_stride(body: bytes) -> Optional[int]:
"""Block stride of a multi-interval histogram body, or None."""
layout = detect_multi_interval_layout(body)
return _stride(*layout) if layout else None
def _decode_record(body: bytes, q: int, rec: int, off: int) -> dict:
def be16(p: int) -> int:
return (body[p] << 8) | body[p + 1]
mic = rec == 20
z = rec - 4
return {
"segment_id": body[off + 1],
"block_ctr": _ctr(body, off),
"t_peak": be16(q), "t_halfp": be16(q + 2),
"v_peak": be16(q + 4), "v_halfp": be16(q + 6),
"l_peak": be16(q + 8), "l_halfp": be16(q + 10),
"m_peak": be16(q + 12) if mic else None,
"m_halfp": be16(q + 14) if mic else None,
"meta_var": bytes(body[q + z:q + z + 4]),
"is_terminal": False,
}
def walk_multi_interval_blocks(body: bytes,
stride: Optional[int] = None) -> List[dict]:
"""Decode a multi-interval histogram body into per-interval records."""
if stride is None:
stride = detect_multi_interval_stride(body)
if not stride:
return []
n_per_block = (stride - _MULTI_HEADER_LEN - _MULTI_TRAILER_LEN) // _MULTI_RECORD_LEN
if n_per_block < 1:
return []
def u16le(p: int) -> int:
return body[p] | (body[p + 1] << 8)
"""Decode a multi-interval histogram body into per-interval records.
``stride`` is accepted for compatibility and ignored: the record size is
detected, and each block's own length is read from the stream.
"""
layout = detect_multi_interval_layout(body)
if not layout:
return []
rec, n = layout
s = _stride(rec, n)
out: List[dict] = []
for off in range(0, len(body) - stride + 1, stride):
if not _is_multi_header(body, off):
break # end of the block run; trailer follows
for k in range(n_per_block):
q = off + _MULTI_HEADER_LEN + _MULTI_RECORD_LEN * k
out.append({
"_tail0": u16le(q + 16),
"segment_id": body[off + 1],
"block_ctr": u16le(off + 2),
"t_peak": u16le(q), "t_halfp": u16le(q + 2),
"v_peak": u16le(q + 4), "v_halfp": u16le(q + 6),
"l_peak": u16le(q + 8), "l_halfp": u16le(q + 10),
"m_peak": u16le(q + 12), "m_halfp": u16le(q + 14),
"meta_var": bytes(body[q + 16:q + 20]),
"is_terminal": False,
})
# A session ending mid-block leaves the remaining slots of the FINAL block
# filled with whatever was in the buffer. Those decoded as peaks thousands
# of times the device-reported PPV, so they have to go — but only from the
# final block: a non-zero tail word occurs mid-file on real intervals, and
# trimming on that alone truncated four BE9440 files by up to 2,800
# intervals, while trimming purely from the end left garbage stranded
# behind one slot that happened to have a zero tail word.
#
# Within the final block, stop at the first slot that is not plausibly
# real: a non-zero tail word, or a geo peak above full scale. 16-count
# units put Normal-range full scale (10.000 in/s) at 2000 counts, so
# anything beyond that is physically impossible.
if out:
last_block_start = ((len(out) - 1) // n_per_block) * n_per_block
for i in range(last_block_start, len(out)):
r = out[i]
if (r["_tail0"] != 0
or max(r["t_peak"], r["v_peak"], r["l_peak"]) > _GEO_MAX_COUNTS):
del out[i:]
off = 0
while _is_multi_header(body, off):
# The last block ends on the terminal tail, after however many intervals
# it holds; any other block runs the full stride to the next header.
m = next((k for k in range(1, n + 1)
if body[off + _stride(rec, k) - 4:off + _stride(rec, k)] == _BLOCK_TAIL_TERMINAL),
None)
last = m is not None
if not last:
nxt = off + s
if not _follows(body, off, nxt):
# No terminal tail and no next block: the stream just stops. Read
# what fits and trim implausible slots (the pre-2026-10-26 rule).
m, last = min(n, (len(body) - off - _MULTI_HEADER_LEN) // rec), True
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):
del recs[k:]
break
out.extend(recs)
break
for r in out:
r.pop("_tail0", None)
m = n
for k in range(m):
r = _decode_record(body, off + _MULTI_HEADER_LEN + rec * k, rec, off)
r["is_terminal"] = last
out.append(r)
if last:
break
off += s
return out
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