""" histogram_codec.py — decoder for MiniMate Plus histogram-mode event bodies. FULLY DECODED 2026-05-20. Every field in every block, verified byte-exact against BW's ASCII export across multiple histogram fixtures. The histogram-mode body is a stream of 32-byte fixed-length blocks, one block per histogram interval. Each block carries the per-interval peak amplitude + zero-crossing frequency for all four channels (Tran, Vert, Long, MicL). ──────────────────────────────────────────────────────────────────────────── Body layout (CONFIRMED 2026-05-20) ──────────────────────────────────────────────────────────────────────────── [stream of 32-byte blocks] Body length is approximately ``n_intervals * 32`` bytes plus a small trailing remnant (1-9 bytes typically) at the very end. Walker should iterate 32-stride and stop before the tail. ──────────────────────────────────────────────────────────────────────────── 32-byte block layout ──────────────────────────────────────────────────────────────────────────── [0] 0x00 always-zero tag [1] segment_id (uint8) 0x00..0x03 - 256 blocks per segment [2:4] block_ctr (uint16 LE) resets each segment (0x0100, 0x0101, ...) [4] 0x0a (uint8) constant marker (= 10) [5:7] T_peak_count uint16 BE Tran peak (count x 0.005 -> in/s) [7:9] T_halfperiod uint16 BE Tran half-period in samples (freq = 512 / halfp) [9:11] V_peak_count uint16 BE [11:13] V_halfperiod uint16 BE [13:15] L_peak_count uint16 BE [15:17] L_halfperiod uint16 BE [17:19] M_peak_count uint16 BE MicL peak (count -> dB via mic_count_to_db) [19:21] M_halfperiod uint16 BE MicL half-period in samples [21:23] 0x00 0x00 constant on standard blocks [24:28] 4-byte variable purpose unknown (possibly CRC or timestamp delta) [28:32] block-end signature see "Two block tails" below ⚠ CORRECTED 2026-10-30 (measured): [21:25] is the interval's peak vector sum SQUARED, uint32 BE in 0.005 in/s units. sqrt([21:25]) x 0.005 is the "Geo PVS" Blastware prints for the interval, on 1,668,073 / 1,668,074 standard DL2 intervals checked against the _XML.XML reports. [21:23] is zero only while the square is below 65,536 (PVS < 1.28 in/s), which is why it looked constant; only [25:28] is still unexplained. `interval_pvs` reads it. **Every per-channel field is uint16 BIG-endian** (confirmed 2026-08-25). Only ``block_ctr`` at [2:4] is little-endian. HISTORY - two earlier readings of this block were wrong in ways that cancelled out on quiet data: 1. *peak as uint16 LE at [6:8]* - produced 268 in/s peaks on any interval whose next byte was non-zero. 2. *peak as uint8 at [6] with an "annotation" byte at [7]* - correct for every peak below 256 counts (1.275 in/s), but it silently **clipped larger peaks**: the final interval of BE18193/T193LQ9K.OE0H reads 8.270 in/s in BW's export (1654 counts = 0x0676) and decoded as 0x76 = 118 = 0.590 in/s. The "annotation" byte was never an annotation - it is the high byte of the big-endian half-period, which is why it was non-zero exactly on the sub-Hz intervals BW renders as "<1.0". Both readings also forced ``block[5] == 0`` via a bogus ``uint16 LE`` marker check at [4:6], which is what capped the peak at one byte. The marker is ``block[4]`` alone. Verified 2026-08-25 against 1211 production histograms paired with their Blastware ASCII exports: **1211/1211 decode exactly** (interval count plus every per-interval peak), and 842,442 per-interval frequency comparisons match with **zero** mismatches. Two block tails --------------- Standard blocks end with ``1e 0a 00 00``. The **final block of the stream** ends with ``9c 06 00 42`` instead, and carries arbitrary bytes at [21:23]. Rejecting it dropped the last interval of nearly every histogram - and the last interval is frequently the one holding the event peak, so the file's reported PPV came out low. Observed in 1206 of 1211 production histograms, always positioned after every standard-tail block. Block-identification anchor: ``block[0] == 0x00`` AND ``block[4] == 0x0A`` AND the tail is one of the two signatures above; standard-tail blocks additionally require ``block[22] == 0x00``. ──────────────────────────────────────────────────────────────────────────── Per-channel encoding ──────────────────────────────────────────────────────────────────────────── Geophone channels (Tran, Vert, Long): - peak_count × 0.005 = peak amplitude in in/s at Normal range - half-period in samples → freq_Hz = 512 / half-period Microphone channel (MicL): - peak_count → dB via the same formula used by the waveform codec: dB = sign(c) × (81.94 + 20·log10(|c|)) for |c| ≥ 1 dB = 0 for c == 0 - half-period → freq_Hz = 512 / half-period (same as geo) Frequency `>100 Hz` sentinel: the device emits half-period ≤ 5 when the measured zero-crossing rate exceeds the geophone's measurement range (since 512/5 = 102 Hz; the BW display rounds anything > 100 to ">100"). ──────────────────────────────────────────────────────────────────────────── Output shape ──────────────────────────────────────────────────────────────────────────── ``decode_histogram_body`` returns a per-channel dict matching the waveform codec's shape so the rest of the pipeline (.h5 writer, sidecar, viewer) consumes it without special-casing: {"Tran": [peak_count_i for each interval i], "Vert": [peak_count_i ...], "Long": [peak_count_i ...], "MicL": [peak_count_i ...]} Values are in **16-count units for geo** (LSB = 0.005 in/s, matching ``decode_waveform_v2``) and **1-count units for mic** (matching the waveform codec's mic convention). Run through ``waveform_codec.decoded_to_adc_counts`` to scale geo to 1-count ADC. Per-interval frequencies are NOT returned — they're auxiliary data, not waveform samples. Consumers needing frequencies can call ``decode_histogram_body_full()`` for the structured per-interval record list. """ from __future__ import annotations import math import struct from typing import List, Optional, Tuple # Block-end signature: constant `1e 0a 00 00` in bytes [28:32] of every # real data block. More distinctive than the byte-22 `00 00` (which # matches many false positives), so we anchor on this. _BLOCK_TAIL = b"\x1e\x0a\x00\x00" # The final block of a histogram stream ends with this instead. It is a # real data block - same layout - and holds the last interval. See the # module docstring, "Two block tails". _BLOCK_TAIL_TERMINAL = b"\x9c\x06\x00\x42" _BLOCK_SIZE = 32 # Marker byte at block[4:6] of every histogram data block. Used as # additional validation that we're looking at a real block. _BLOCK_MARKER = 10 # Geo peak scaling: stored as "count × 0.005 in/s" where 1 count = one # 0.005 in/s display quantum. Equivalent to the waveform codec's # 16-count-unit output (1 unit = 0.005 in/s = 16 ADC counts). _GEO_LSB_INS = 0.005 # Frequency formula: freq_Hz = (sample_rate / 2) / half_period_samples. # ⚠ RETRACTED 2026-11-03 (#50): "a fixed numerator of 512". 512 is sample_rate # / 2 at 1024 sps only; at 2048 sps it halved every frequency. Measured on DL2: # 527,915 / 527,915 cells at 1024 sps and 1,725 / 1,725 at 2048. _FREQ_NUMERATOR = 512 # sample_rate / 2 at the default 1024 sps def _is_data_block(block: bytes) -> bool: """Tight identification of a histogram data block. Accepts both tail signatures. ``block[4]`` alone is the marker - ``block[5]`` is the high byte of the Tran peak and is non-zero on any interval above 1.275 in/s, so it must not be part of the marker test. The ``block[22] == 0`` constraint is what keeps trailer content out, but it applies only to standard-tail blocks: terminal blocks carry arbitrary bytes there. """ if len(block) < _BLOCK_SIZE: return False if block[0] != 0x00: return False if block[4] != _BLOCK_MARKER: return False # The 4-byte tail plus block[0]==0 and block[4]==0x0A is already six bytes # of constraint — enough to keep trailer content out. There is NO extra # test on block[22]: it was documented as a constant 0x00 but carries data # on loud blocks, and rejecting those threw away the interval holding the # event peak. BE18350/T350L7HR.NL0H is the proof: its block 92 has # block[22]=0x26 and a Tran peak of 0x0563 = 1379 counts = 6.895 in/s, # exactly the device-reported PPV, while the file decoded to 0.015 in/s. return block[28:32] in (_BLOCK_TAIL, _BLOCK_TAIL_TERMINAL) def _decode_block(block: bytes) -> Optional[dict]: """Decode one 32-byte histogram block. Caller must have validated with ``_is_data_block`` first. Returns a record with per-channel peak counts (uint8) and half-periods (uint16 LE). """ # Every per-channel field is uint16 BIG-endian; only block_ctr is LE. # See the module docstring for the two superseded readings and why # each looked correct on quiet data. def _be16(i: int) -> int: return (block[i] << 8) | block[i + 1] t_peak = _be16(5) t_halfp = _be16(7) v_peak = _be16(9) v_halfp = _be16(11) l_peak = _be16(13) l_halfp = _be16(15) m_peak = _be16(17) m_halfp = _be16(19) segment_id = block[1] block_ctr = block[2] | (block[3] << 8) var_meta = bytes(block[24:28]) return { "segment_id": segment_id, "block_ctr": block_ctr, "t_peak": t_peak, "t_halfp": t_halfp, "v_peak": v_peak, "v_halfp": v_halfp, "l_peak": l_peak, "l_halfp": l_halfp, "m_peak": m_peak, "m_halfp": m_halfp, "meta_var": var_meta, "pvs_sq": int.from_bytes(block[21:25], "big"), "is_terminal": block[28:32] == _BLOCK_TAIL_TERMINAL, } def walk_body(body: bytes) -> List[dict]: """Walk the body and return one dict per histogram interval. Iterates 32-byte strides from offset 0. Yields a decoded record for every block that passes ``_is_data_block`` validation. Stops when the remaining bytes are too short to form a complete block. In Histogram+Continuous mode the body interleaves data blocks with other 32-byte content (likely continuous-mode waveform blocks) that fail the data-block validation; the walker naturally skips them without losing 32-byte alignment. Use ``block_ctr`` from each returned record to map back to the original interval index — the record list is sparse when other block types are interleaved. """ records: List[dict] = [] for off in range(0, len(body) - _BLOCK_SIZE + 1, _BLOCK_SIZE): blk = body[off:off + _BLOCK_SIZE] if not _is_data_block(blk): # Hit non-block content (likely a sync or stream marker). # Continue walking — block alignment is fixed at 32-stride # from offset 0, so we don't lose alignment by skipping. continue decoded = _decode_block(blk) if decoded is None: # Block validated as a histogram block but had peak fields # outside the plausible range — undocumented extension. # Skip rather than propagating bogus PVS contributions. continue records.append(decoded) return records def _walk_auto(body: bytes) -> List[dict]: """Pick the block model by signature strength, not by which returns first. 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. """ 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 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]: """Decode a histogram-mode body into per-channel peak-sample arrays. Returns ``{"Tran": [...], "Vert": [...], "Long": [...], "MicL": [...]}`` where each channel's list contains one peak value per histogram interval (in the same units the waveform codec uses: 16-count units for geo, 1-count ADC units for mic). Returns ``None`` if the body doesn't contain any valid histogram blocks. To convert to physical units: - Geo channels: ``count * 0.005`` = peak in in/s at Normal range (or run through ``waveform_codec.decoded_to_adc_counts`` first to get 1-count ADC values, then ``count / 32767 * 10.0`` for in/s) - Mic channel: use ``waveform_codec.mic_count_to_db(count)`` """ return channels_from_records(_walk_auto(body)) def channels_from_records(records: Optional[List[dict]]) -> Optional[dict]: """``decode_histogram_body``'s per-channel peaks, from records already walked.""" if not records: return None return { "Tran": [r["t_peak"] for r in records], "Vert": [r["v_peak"] for r in records], "Long": [r["l_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], } def decode_histogram_body_full(body: bytes) -> Optional[List[dict]]: """Decode a histogram-mode body into the full per-interval record list. Same data as ``decode_histogram_body`` but in a structured form that preserves the half-period (frequency) data for each channel + the per-block segment_id, block_ctr, and 4-byte variable metadata. Useful for diagnostic tools, sidecar enrichment, and future-codec work. Returns ``None`` if the body has no valid blocks. """ records = _walk_auto(body) return records if records else None def interval_pvs(body: bytes) -> Optional[List[float]]: """Each interval's peak vector sum, in the geo peak units (0.005 in/s at Normal range): the square root of the square the device stores with every interval. This is the vector sum at an instant, as Blastware prints it -- not the magnitude of the three channel peaks, which can come from different moments. None when the body has no valid blocks.""" records = _walk_auto(body) return [math.sqrt(r["pvs_sq"]) for r in records] if records else None def half_period_to_hz(halfp: int, sample_rate: int = 1024) -> Optional[float]: """Convert a half-period in samples to frequency in Hz: ``(sample_rate / 2) / halfp``. Returns ``None`` for half-period ≤ 5 — the device emits values in that range when the measured zero-crossing rate exceeds 100 Hz at 1024 sps (the BW display reports `>100`, `>200` at 2048 sps). Callers can treat ``None`` as that sentinel. A half-period of 0 is Blastware's "N/A"; it also returns None. """ if halfp <= 5: return None return (sample_rate / 2) / halfp def geo_count_to_ins(count: int) -> float: """Convert a histogram geo peak count to in/s at Normal range.""" return count * _GEO_LSB_INS # ── Multi-interval blocks (CONFIRMED 2026-08-26; re-read 2026-10-26) ───────── # # When the histogram interval is SHORTER than one minute, the device packs one # minute of intervals into each block: # # 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 + per_block * record, record = 4 * channels + 4 # # Block layout (measured 2026-10-26, issues #47 and #49): # [0] 0x00 # [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). Measured 2026-10-30: those # 4 bytes are the interval's peak vector sum SQUARED, uint32 BE in # 0.005 in/s units -- sqrt matches Blastware's "Geo PVS" on 34.5 M # DL2 sub-minute intervals; the 0x0000 is its high word # [-7:] trailer: 3 bytes, then the 4-byte tail -- 9c 06 00 42 on the # stream's LAST block # # 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. # # ⚠ 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. # # 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 = 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. 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) def _ctr(body: bytes, off: int) -> int: return body[off + 2] | (body[off + 3] << 8) 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 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): 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. 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 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 # 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]), "pvs_sq": int.from_bytes(body[q + z:q + z + 4], "big"), "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. ``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] = [] 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): 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) break 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