From 2b698e74cff7189518d20d6dcac457c07744e4fa Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 3 Nov 2026 17:34:27 -0500 Subject: [PATCH 1/2] feat(decode): a histogram's interval detail -- frequencies (#50), vector sums, interval size, stop Group B of the file-only decode, measured on DL2 2026-11-03: - Frequency = (sample rate / 2) / half-period: 527,915 / 527,915 cells at 1024 sps and 1,725 / 1,725 at 2048. #50: half_period_to_hz took a fixed 512 and halved every 2048-sps frequency; it now takes the rate (default 1024). Blastware prints 'N/A' for a half-period of 0, '>100' ('>200' at 2048) at 5 samples or fewer, '<1.0' below 1 Hz. - Each interval's vector sum, sqrt(PVS^2) at the event's range: 771,354 / 771,354. - Interval size: uint16 seconds at k - 40 (Series IV [8:10]). - Stop: the footer's (2,995 / 2,999 sampled; 4 print a second earlier). Event gains histogram_interval_sec, interval_half_periods, interval_pvs and stop_time; the .h5 gains /intervals/half_period/, /intervals/pvs_ips and a histogram_interval_sec attr. The decoder walks a histogram once (histogram_codec.channels_from_records) and takes the event's PVS from the same records. The checker compares each interval column, number or Blastware's word; the test that pinned Tran Freq Hz as blank now pins the match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9 --- minimateplus/decode_check.py | 60 +++++++-- minimateplus/event_file_io.py | 41 +++++-- minimateplus/histogram_codec.py | 29 +++-- minimateplus/models.py | 5 + sfm/event_hdf5.py | 21 ++++ .../T190LD42.T00H | Bin 0 -> 1550 bytes .../T190LD42_T00H_XML.XML | 116 ++++++++++++++++++ tests/test_bw_file_fields.py | 42 +++++++ tests/test_decode_check.py | 23 +++- tests/test_histogram_codec.py | 7 ++ 10 files changed, 312 insertions(+), 32 deletions(-) create mode 100755 tests/fixtures/histogram-intervals-11-03-26/T190LD42.T00H create mode 100755 tests/fixtures/histogram-intervals-11-03-26/T190LD42_T00H_XML.XML diff --git a/minimateplus/decode_check.py b/minimateplus/decode_check.py index e3d396b..5904375 100644 --- a/minimateplus/decode_check.py +++ b/minimateplus/decode_check.py @@ -15,12 +15,13 @@ from __future__ import annotations import math import re -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Callable, Optional, Sequence from .bw_xml_report import XmlReport from .event_file_io import (_GEO_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT, decode_blastware_bytes) +from .histogram_codec import half_period_to_hz from .models import Event from .waveform_codec import mic_count_to_db @@ -85,6 +86,26 @@ class SfmSide: channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order counts: dict[str, list[int]] # waveform samples or histogram interval peaks geo_ips_per_count: float = GEO_IPS_PER_COUNT # at the event's range, as SFM read it + # interval column -> SFM's value per interval (a number, or Blastware's word) + interval_values: dict[str, list[object]] = field(default_factory=dict) + + +def interval_frequency(halfp: int, sample_rate: int) -> object: + """An interval's frequency as Blastware prints it: "N/A" for a half-period + of 0, ">100" (">200" at 2048 sps) at 5 samples or fewer, "<1.0" below 1 Hz, + else (sample rate / 2) / half-period in Hz. Measured on ~3.1 M DL2 cells, + 2026-11-03 (#50: the rate, not a fixed 512).""" + if halfp == 0: + return "N/A" + hz = half_period_to_hz(halfp, sample_rate) + if hz is None: + return f">{round(100 * sample_rate / 1024)}" + return "<1.0" if hz < 1.0 else hz + + +def _interval_size(seconds: int) -> str: + n, unit = (seconds // 60, "minute") if seconds % 60 == 0 else (seconds, "second") + return f"{n} {unit}{'' if n == 1 else 's'}" def sfm_side(raw: bytes) -> SfmSide: @@ -118,6 +139,17 @@ def sfm_side(raw: bytes) -> SfmSide: values["MicLPSPL dB(L)"] = mic_count_to_db(max(abs(c) for c in counts["MicL"])) values["MicLPSPL psi(L)"] = pv.micl if pv is not None else None values.update(_setup_values(ev)) + if ev.stop_time is not None: + values.update(HistogramStopDate=ev.stop_time.strftime("%Y-%m-%d"), + HistogramStopTime=ev.stop_time.strftime("%H:%M:%S")) + if ev.histogram_interval_sec: + values["IntervalSize"] = _interval_size(ev.histogram_interval_sec) + interval_values: dict[str, list[object]] = {} + if ev.interval_half_periods and ev.sample_rate: + for ch, hps in ev.interval_half_periods.items(): + interval_values[f"{ch} Freq Hz"] = [interval_frequency(h, ev.sample_rate) for h in hps] + if ev.interval_pvs: + interval_values["Geo PVS in/s"] = list(ev.interval_pvs) return SfmSide( event=ev, @@ -128,6 +160,7 @@ def sfm_side(raw: bytes) -> SfmSide: channels=[ch for ch in _CHANNELS if counts[ch]], counts=counts, geo_ips_per_count=_GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) / _GEO_INT16_FS, + interval_values=interval_values, ) @@ -214,9 +247,11 @@ def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> Fie return FieldResult(tag, "match" if ok else "mismatch", printed, _render(value, printed)) -def _cell_diff(value: float, printed: str) -> Optional[float]: +def _cell_diff(value: object, printed: str) -> Optional[float]: """|value - printed| when the cell disagrees, else None; inf for a cell that - is not a number.""" + is not a number. A word on SFM's side (">100", "N/A") must be printed.""" + if isinstance(value, str): + return None if _same_text(value, printed) else float("inf") p = _printed_number(printed) if p is None: return float("inf") @@ -285,14 +320,19 @@ def series_pairs(sfm: SfmSide, ref: XmlReport, if field.startswith("intervals."): title = field[len("intervals."):] columns = ref.interval_columns or [] - convert = _interval_converter(title, sfm) - counts = sfm.counts.get(title.partition(" ")[0], []) - if convert is None or not counts or title not in columns: + if title not in columns: return None i = columns.index(title) cells = [row[i] if i < len(row) else "" for _, row in (ref.intervals or [])] - pairs = [(j, cell, convert(c)) for j, (cell, c) in enumerate(zip(cells, counts))] - return pairs, abs(len(cells) - len(counts)) + values = sfm.interval_values.get(title) + if values is None: + convert = _interval_converter(title, sfm) + counts = sfm.counts.get(title.partition(" ")[0], []) + if convert is None or not counts: + return None + values = [convert(c) for c in counts] + pairs = [(j, cell, v) for j, (cell, v) in enumerate(zip(cells, values))] + return pairs, abs(len(cells) - len(values)) return None @@ -302,7 +342,9 @@ def _compare_series(field: str, n_bw: int, sfm: SfmSide, ref: XmlReport) -> Fiel return FieldResult(field, "sfm_blank", f"{n_bw} rows", None) pairs, row_len = got diffs = [(j, d) for j, cell, v in pairs if (d := _cell_diff(v, cell)) is not None] - n_sfm = len(sfm.counts.get(field.split(".", 1)[1].partition(" ")[0], [])) + title = field.split(".", 1)[1] + n_sfm = (len(sfm.interval_values[title]) if title in sfm.interval_values + else len(sfm.counts.get(title.partition(" ")[0], []))) return _series_result(field, n_bw, n_sfm, diffs, row_len) diff --git a/minimateplus/event_file_io.py b/minimateplus/event_file_io.py index 8cf6d17..f86311a 100644 --- a/minimateplus/event_file_io.py +++ b/minimateplus/event_file_io.py @@ -19,6 +19,7 @@ import datetime import hashlib import json import logging +import math import os import re import struct @@ -30,7 +31,7 @@ from . import blastware_file as _bw # avoid circular reference at module load from .bw_ascii_report import BwAsciiReport from . import waveform_codec as _wc from .waveform_codec import decode_waveform_v2, decoded_to_adc_counts -from .histogram_codec import decode_histogram_body, interval_pvs +from .histogram_codec import channels_from_records, decode_histogram_body, decode_histogram_body_full # Reference pressure for dB(L) → psi conversion (20 µPa expressed in psi). # Same constant as sfm/sfm_webapp.html so server-side and browser-side @@ -862,6 +863,7 @@ _RECTIME_OFFSET_BEFORE_MARKER = 30 # 2026-10-29). Offsets are from the first byte of the name. _SETUP_NAME_RE = re.compile(rb"\x1c\x08([\x20-\x7e]{1,40})\x00") _SAMPLE_RATE_BEFORE_NAME = 42 # uint16 BE, samples per second +_INTERVAL_BEFORE_NAME = 40 # uint16 BE, histogram interval in seconds (2 / 5 / 15 / 60 / 300) _PRETRIG_BEFORE_NAME = 36 # float32 BE, seconds, negative (-0.25, -0.0625 ...) _RECTIME_BEFORE_NAME = 30 # float32 BE, seconds (the marker's offset above) _SAMPLE_RATES = (1024, 2048, 4096) @@ -1277,8 +1279,10 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event: problems = [] if record_type is None: problems.append(f"unknown record type byte 0x{type_byte:02x} at STRT[18]") + hist_records = None if record_type == "Histogram": - decoded = decode_histogram_body(body) + hist_records = decode_histogram_body_full(body) + decoded = channels_from_records(hist_records) is_waveform_body = False elif record_type == "Waveform": decoded = decode_waveform_v2(body) @@ -1287,7 +1291,8 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event: decoded = decode_waveform_v2(body) is_waveform_body = decoded is not None if decoded is None: - decoded = decode_histogram_body(body) + hist_records = decode_histogram_body_full(body) + decoded = channels_from_records(hist_records) if decoded is None: log.warning( "%s: body codec failed to decode (body starts %s) — " @@ -1414,14 +1419,28 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event: # The geophone full scale is the file's range; Normal when it wasn't read. geo_fs = _GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) ev.peak_values = _peaks_from_samples(samples, geo_fs) if has_samples else None - if not is_waveform_body and ev.peak_values is not None: - # A histogram stores each interval's vector sum (squared); the event's - # is the largest. Combining the channel peaks instead read high on 86% - # of DL2's histograms -- they can come from different moments. - pvs = interval_pvs(body) - if pvs: - ev.peak_values.peak_vector_sum = ( - max(pvs) * _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS) + ev.stop_time = ts2 + if hist_records: + # A histogram stores each interval's vector sum (squared), and each + # channel's half-period: Blastware's per-interval Geo PVS (771,354 / + # 771,354 DL2 cells) and frequency, (sample rate / 2) / half-period. + unit_ins = _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS + ev.interval_pvs = [math.sqrt(r["pvs_sq"]) * unit_ins for r in hist_records] + ev.interval_half_periods = { + ch: [r[key] for r in hist_records if r[key] is not None] + for ch, key in (("Tran", "t_halfp"), ("Vert", "v_halfp"), + ("Long", "l_halfp"), ("MicL", "m_halfp"))} + if not ev.interval_half_periods["MicL"]: + del ev.interval_half_periods["MicL"] + k = _setup_name_at(raw) + if k is not None and k >= _INTERVAL_BEFORE_NAME: + ev.histogram_interval_sec = int.from_bytes( + raw[k - _INTERVAL_BEFORE_NAME:k - _INTERVAL_BEFORE_NAME + 2], "big") or None + if not is_waveform_body and ev.peak_values is not None and ev.interval_pvs: + # The event's vector sum is the largest interval's. Combining the + # channel peaks instead read high on 86% of DL2's histograms -- they + # can come from different moments. + ev.peak_values.peak_vector_sum = max(ev.interval_pvs) ev._a5_frames = None # not recoverable from BW file return ev diff --git a/minimateplus/histogram_codec.py b/minimateplus/histogram_codec.py index 3a4f7e6..16b6f0f 100644 --- a/minimateplus/histogram_codec.py +++ b/minimateplus/histogram_codec.py @@ -156,10 +156,11 @@ _BLOCK_MARKER = 10 # 16-count-unit output (1 unit = 0.005 in/s = 16 ADC counts). _GEO_LSB_INS = 0.005 -# Frequency formula: freq_Hz = _FREQ_NUMERATOR / half_period_samples. -# Empirically determined to be 512 (= sample_rate / 2, where sample rate -# is 1024 sps for the standard MiniMate Plus configuration). -_FREQ_NUMERATOR = 512 +# 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: @@ -300,7 +301,11 @@ def decode_histogram_body(body: bytes) -> Optional[dict]: to get 1-count ADC values, then ``count / 32767 * 10.0`` for in/s) - Mic channel: use ``waveform_codec.mic_count_to_db(count)`` """ - records = _walk_auto(body) + 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 { @@ -338,17 +343,19 @@ def interval_pvs(body: bytes) -> Optional[List[float]]: return [math.sqrt(r["pvs_sq"]) for r in records] if records else None -def half_period_to_hz(halfp: int) -> Optional[float]: - """Convert a half-period in samples to frequency in Hz. +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 - (the BW display reports `>100 Hz` for such cases). Callers can - treat ``None`` as the `>100 Hz` sentinel. + 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 _FREQ_NUMERATOR / halfp + return (sample_rate / 2) / halfp def geo_count_to_ins(count: int) -> float: diff --git a/minimateplus/models.py b/minimateplus/models.py index 99b0b62..f65e00c 100644 --- a/minimateplus/models.py +++ b/minimateplus/models.py @@ -561,6 +561,11 @@ class Event: trigger_level_mic_psi: Optional[float] = None record_stop_mode: Optional[int] = None # 0 = Fixed mic_type: Optional[int] = None # 2 = Linear Weighting (as Series IV) + stop_time: Optional[datetime.datetime] = None # the footer's stop + # A histogram's per-interval detail (2026-11-03); None for a waveform. + histogram_interval_sec: Optional[int] = None # as ComplianceConfig.histogram_interval_sec + interval_half_periods: Optional[dict] = None # channel -> half-period per interval, samples + interval_pvs: Optional[list] = None # each interval's vector sum, in/s # Sensor self-check traces keyed by channel label — the short diagnostic # waveforms the unit records when it pulses each sensor before monitoring diff --git a/sfm/event_hdf5.py b/sfm/event_hdf5.py index 6c76be5..a40c559 100644 --- a/sfm/event_hdf5.py +++ b/sfm/event_hdf5.py @@ -38,6 +38,10 @@ Layout written to `.h5`: trigger_level_mic_psi, firmware_version, dsp_version, model, calibration_date (ISO), calibrated_by (each only when read from the event file) + histogram_interval_sec int (histograms) + /intervals (histograms, when read) + half_period/ uint16 samples per interval; Hz = (sample rate / 2) / it + pvs_ips float32 each interval's vector sum, in/s peak_tran_ips float (from 0C; authoritative) peak_vert_ips float peak_long_ips float @@ -273,6 +277,7 @@ def write_event_hdf5( ("trigger_sources", getattr(event, "trigger_sources", None)), ("trigger_level_geo_ips", getattr(event, "trigger_level_geo", None)), ("trigger_level_mic_psi", getattr(event, "trigger_level_mic_psi", None)), + ("histogram_interval_sec", getattr(event, "histogram_interval_sec", None)), ): if value is not None: attrs[attr] = value @@ -304,6 +309,22 @@ def write_event_hdf5( compression="gzip", compression_opts=4, shuffle=True, ) + # /intervals — a histogram's per-interval detail as the file holds it: + # each channel's half-period in samples (frequency = (sample rate / 2) + # / half-period; 0 is Blastware's "N/A") and each interval's vector sum. + half_periods = getattr(event, "interval_half_periods", None) + interval_pvs = getattr(event, "interval_pvs", None) + if half_periods or interval_pvs: + igrp_iv = f.create_group("intervals") + if half_periods: + hgrp = igrp_iv.create_group("half_period") + for ch, hps in half_periods.items(): + hgrp.create_dataset(ch, data=np.asarray(hps, dtype="uint16"), + compression="gzip", compression_opts=4, shuffle=True) + if interval_pvs: + igrp_iv.create_dataset("pvs_ips", data=np.asarray(interval_pvs, dtype="float32"), + compression="gzip", compression_opts=4, shuffle=True) + # /samples_int16 — optional raw ADC counts (preserved for analysis # tools that want pre-conversion data). Cheap to include. if include_int16: diff --git a/tests/fixtures/histogram-intervals-11-03-26/T190LD42.T00H b/tests/fixtures/histogram-intervals-11-03-26/T190LD42.T00H new file mode 100755 index 0000000000000000000000000000000000000000..8fb7ec07c7af581ff68ef9608be99031fde329c7 GIT binary patch literal 1550 zcma)+Uu;uV9LK-+(zSQ}chBv*p$6r2WM-h9+ghZI4aVk(Bi*v>4>9qn>8_(%Zs%=5 z@rgu)`#YCGI01BP$y7v3sd3nzg=Z562Kxt%RY9?~3JM^#;VC;z33dVK5FKEcK?^+a z!qQoEJdU$gbaXX^nszthbp?WW&YTR$=k}cd_R}A;->9_=1OlOkrd>c&W5cdyxU9At z|DA>cHxraP-WNZbT#tMEJ?yXm771wmchEcuHbEBbu(hST-fH{o&^0=* zaCrh(wnzh%i{Xeq%=^`7LLZK4BYZ$j9UVoVo_JM_rdrVL4>kIG6ME_}KakL0^Y7Qy z2oLy!&o}qSqK7Foc`O!J;~bswn5t30fyi;*nK&{U(T-y%sp`Bpazt&xpsMQ;e~(Hr zS}dC6-CDH4&tHt_dMugHFrdbgJe-KOfL?rCi2M24PMo&l|Jy6B^8Q3*n4{~>l&TG@ z!@M_&?77bG;;%hY1+3n&F!Y`-*+CqoOzCE8- zTpCTr(0V>ptPgKT;xg(hV8QC&lGAnrt|uQ`>+8&_q;=M{`A5_=!vIc}hdO|#f1+R8 z&K^Kb0IO3}(WV$sAEN%uD|M&|!uXh~+*Av&^(E>(zdu0DP8bVR`KG+oE>g2SxQcJ6 zxTxZB5IfA(LEa<*70sY95lJFhypv+wFF`98SBV(k@Ao&1z+R>I;EdpHPyE zg~H@yHk%=(Gnp)DGM~>Eip7P6g_2RC8^GEb6oD4f{GwbF&lQ6Vc4<+>M*J3Z>hNcb4z2FlkEM z`34VG+D#rNo4XN+msIVouJ(GXyk)92B$vzOaMtL literal 0 HcmV?d00001 diff --git a/tests/fixtures/histogram-intervals-11-03-26/T190LD42_T00H_XML.XML b/tests/fixtures/histogram-intervals-11-03-26/T190LD42_T00H_XML.XML new file mode 100755 index 0000000..9984619 --- /dev/null +++ b/tests/fixtures/histogram-intervals-11-03-26/T190LD42_T00H_XML.XML @@ -0,0 +1,116 @@ + + +8.0 +Full Histogram +BE18190 +V 10.72-8.17 MiniMate Plus +T190LD42.T00H +13:29:24 +2025-12-08 +13:29:37 +2025-12-08 + +Tran +Vert +Long +MicL + +1.00 +1 minute +2048 sps +6.7 Volts +June 13, 2025 by Instantel +in/s and dB(L) +I-80-North Fork-Area 3-462Richardsvilel +Fay Company +Terra-Mechanics Inc.- Harrison +Loc #8 - Area 3- 462 Richardsville Road + +10.000 +in/s + + +1.280 +in/s + + +2.615 +in/s + + +1.120 +in/s + + +15.5 +Hz + + +64 +Hz + + +17.7 +Hz + +13:29:37 +2025-12-08 +13:29:37 +2025-12-08 +13:29:37 +2025-12-08 + +2.644 +in/s + +13:29:37 +2025-12-08 +Linear Weighting + +107.0 +dB(L) + +13:29:37 +2025-12-08 + +51 +Hz + +7.4 Hz. +4.2 +Passed +7.6 Hz. +3.4 +Passed +7.3 Hz. +3.7 +Passed +0.0 Hz. +0 mv +Check + + +2025-12-08 13:29:23 - 2025-12-08 13:29:37 "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 + + + + +1.28015.52.615641.12017.72.6440.001107.051 + + + + + + diff --git a/tests/test_bw_file_fields.py b/tests/test_bw_file_fields.py index 934741c..401182d 100644 --- a/tests/test_bw_file_fields.py +++ b/tests/test_bw_file_fields.py @@ -429,3 +429,45 @@ def test_the_h5_carries_the_setup_fields(tmp_path): assert abs(float(a["trigger_level_mic_psi"]) - ev.trigger_level_mic_psi) < 1e-9 assert (str(a["firmware_version"]), str(a["dsp_version"]), str(a["calibration_date"])) == ( "S338.17", "10.72", "2019-02-20") + + +# ── Group B: histogram interval detail ────────────────────────────────────── +# Interval size is the setup's uint16 seconds at k - 40 (Series IV [8:10]); the +# stop is the footer's. Each interval keeps its half-periods and its vector sum +# (PVS^2). Frequency = (sample rate / 2) / half-period: 527,915 / 527,915 cells +# at 1024 sps and 1,725 / 1,725 at 2048 (#50: the old fixed 512 halved every +# 2048-sps frequency). Measured 2026-11-03. +from minimateplus.histogram_codec import half_period_to_hz # noqa: E402 + +_HB = "histogram-intervals-11-03-26" + + +@pytest.mark.parametrize("rel,sr,freqs,pvs,stop", [ + # Blastware: 1 minute; Tran 32, Vert 47, Long 14, MicL 47 Hz; PVS 1.358; stop 12:49:33 + ("decode-checker-10-29-26/T004JTRF.ME0H", 1024, + {"Tran": 32, "Vert": 47, "Long": 14, "MicL": 47}, 1.358, (2022, 12, 28, 12, 49, 33)), + # Blastware: 1 minute at 2048 sps; Tran 15.5, Vert 64, Long 17.7, MicL 51 Hz; PVS 2.644 + (f"{_HB}/T190LD42.T00H", 2048, + {"Tran": 15.5, "Vert": 64, "Long": 17.7, "MicL": 51}, 2.644, (2025, 12, 8, 13, 29, 37)), +]) +def test_histogram_interval_detail_comes_from_the_file(rel, sr, freqs, pvs, stop): + ev = read_blastware_file(_FIX / rel) + assert (ev.sample_rate, ev.histogram_interval_sec) == (sr, 60) + for ch, hz in freqs.items(): + got = half_period_to_hz(ev.interval_half_periods[ch][0], ev.sample_rate) + d = 1 if isinstance(hz, float) else 0 + assert abs(got - hz) <= 0.5 * 10 ** -d + 1e-9, (ch, got, hz) + assert abs(ev.interval_pvs[0] - pvs) <= 0.0005 + 1e-9 + t = ev.stop_time + assert (t.year, t.month, t.day, t.hour, t.minute, t.second) == stop + + +def test_the_h5_carries_the_interval_detail(tmp_path): + import h5py + from sfm import event_hdf5 + ev = read_blastware_file(_FIX / _HB / "T190LD42.T00H") + event_hdf5.write_event_hdf5(tmp_path / "e.h5", ev, serial="BE18190") + with h5py.File(tmp_path / "e.h5", "r") as f: + assert int(f.attrs["histogram_interval_sec"]) == 60 + assert list(f["intervals/half_period/Vert"][:]) == ev.interval_half_periods["Vert"] + assert abs(float(f["intervals/pvs_ips"][0]) - 2.644) <= 0.0005 + 1e-9 diff --git a/tests/test_decode_check.py b/tests/test_decode_check.py index da1eca3..503023a 100644 --- a/tests/test_decode_check.py +++ b/tests/test_decode_check.py @@ -96,7 +96,7 @@ def test_zc_frequency_na_and_above_range(): 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" + assert res["intervals.Tran Freq Hz"].verdict == "match" # read since 2026-11-03 fields = set(_results("R352HFZ7.530H")) # no mic assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields) @@ -279,3 +279,24 @@ def test_a_mic_trigger_level_is_read_in_the_unit_it_is_printed_in(): ref.event_units = "in/s and psi(L)" res = {r.field: r for r in compare(sfm_side((sf / "T189HUD6.QE0W").read_bytes()), ref, CARVEOUTS)} assert res["MicTriggerLevel"].verdict == "match", res["MicTriggerLevel"] + + +@pytest.mark.parametrize("path", [FIX / "T004JTRF.ME0H", + FIX.parent / "histogram-intervals-11-03-26" / "T190LD42.T00H"]) +def test_histogram_interval_detail_matches_blastware(path): + ref = parse_xml_report_file(path.with_name(path.name.replace(".", "_", 1) + "_XML.XML")) + res = {r.field: r for r in compare(sfm_side(path.read_bytes()), ref, CARVEOUTS)} + for f in ("IntervalSize", "HistogramStopDate", "HistogramStopTime", "intervals.Tran Freq Hz", + "intervals.Vert Freq Hz", "intervals.Long Freq Hz", "intervals.MicL Freq Hz", + "intervals.Geo PVS in/s"): + assert res[f].verdict == "match", (f, res[f]) + + +@pytest.mark.parametrize("halfp,sr,want", [ + (0, 1024, "N/A"), (5, 1024, ">100"), (5, 2048, ">200"), (1024, 1024, "<1.0"), +]) +def test_blastwares_interval_frequency_words(halfp, sr, want): + # N/A for a half-period of 0, ">100" / ">200" at 5 samples or fewer, "<1.0" + # below 1 Hz -- on ~3.1 M DL2 cells, 2026-11-03. + from minimateplus.decode_check import interval_frequency + assert interval_frequency(halfp, sr) == want diff --git a/tests/test_histogram_codec.py b/tests/test_histogram_codec.py index 9b6522a..3236ef2 100644 --- a/tests/test_histogram_codec.py +++ b/tests/test_histogram_codec.py @@ -695,3 +695,10 @@ def test_third_block_still_rejects_a_mismatched_counter(): + _mk_multi_block(ivs, ctr=257) + _mk_multi_block(ivs, ctr=999)) # counter jumps — not consecutive assert detect_multi_interval_stride(body) != 12 + 20 * 4 + + +def test_half_period_to_hz_follows_the_sample_rate(): + """#50: (sample rate / 2) / half-period, measured on 1,725 / 1,725 cells at + 2048 sps; the old fixed 512 halved them.""" + assert half_period_to_hz(6, 2048) == pytest.approx(1024 / 6) + assert half_period_to_hz(6) == pytest.approx(512 / 6) # 1024 sps by default From 13f2769736fc05628c235c71ff8600354074aa76 Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 3 Nov 2026 18:02:51 -0500 Subject: [PATCH 2/2] feat(decode_check): an OORANGE interval vector sum is saturation Blastware prints OORANGE for an interval's vector sum when it exceeds the range in an interval where Blastware also clamped a channel: 17 / 17 DL2 cells, SFM's sum 10.01 .. 17.33 in/s (sqrt 3 x 10.005). The saturation carve-out now covers intervals.Geo PVS in/s with that rule, per interval, as it already did for PeakVectorSum. The 4 other cells left mismatching sit 4e-6 past a rounding boundary (Blastware's arithmetic is a hair lower) and stay mismatches. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9 --- minimateplus/decode_check_carveouts.py | 22 +++- .../T190LD5Q.LD0H | Bin 0 -> 1838 bytes .../T190LD5Q_LD0H_XML.XML | 116 ++++++++++++++++++ tests/test_decode_check.py | 25 ++++ 4 files changed, 161 insertions(+), 2 deletions(-) create mode 100755 tests/fixtures/histogram-intervals-11-03-26/T190LD5Q.LD0H create mode 100755 tests/fixtures/histogram-intervals-11-03-26/T190LD5Q_LD0H_XML.XML diff --git a/minimateplus/decode_check_carveouts.py b/minimateplus/decode_check_carveouts.py index 1bf3d75..e1d05c9 100644 --- a/minimateplus/decode_check_carveouts.py +++ b/minimateplus/decode_check_carveouts.py @@ -68,6 +68,21 @@ def _saturation(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool: got = series_pairs(sfm, ref, res.field) if got is None or got[1]: return False + if res.field == "intervals.Geo PVS in/s": + # Per interval, as PeakVectorSum: an OORANGE vector sum, SFM's sum within + # three channels at the ceiling, and a channel Blastware itself clamped in + # that interval. 17 / 17 DL2 cells, SFM 10.01 .. 17.33 (2026-11-03). + cols = ref.interval_columns or [] + peaks = [cols.index(c) for c in ("Tran Peak in/s", "Vert Peak in/s", "Long Peak in/s") + if c in cols] + rows = ref.intervals or [] + differing = [(j, cell, v) for j, cell, v in got[0] + if isinstance(v, str) or not matches_printed(v, cell)] + return bool(differing) and all( + cell.strip() == "OORANGE" and not isinstance(v, str) + and r - _TOL <= v <= 3 ** 0.5 * r * 1.01 + and any(_clamped(rows[j][1][p], r) for p in peaks if p < len(rows[j][1])) + for j, cell, v in differing) differing = [(cell, v) for _, cell, v in got[0] if not matches_printed(v, cell)] return bool(differing) and all( _clamped(cell, r) and _at_ceiling(v, r) @@ -79,10 +94,13 @@ SATURATION = Carveout( id="saturation", fields=("TranPPV", "VertPPV", "LongPPV", "PeakVectorSum", "samples.Tran", "samples.Vert", "samples.Long", - "intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s"), + "intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s", + "intervals.Geo PVS in/s"), evidence=("Blastware clamps a clipped channel to the range maximum and prints OORANGE; " "the file holds counts past full scale (32016 counts = 10.005 in/s observed). " - "scratch/verify_against_ascii.py, 2026-08-28."), + "scratch/verify_against_ascii.py, 2026-08-28. An interval's vector sum prints " + "OORANGE when it exceeds the range in an interval with a clamped channel: 17 / 17 " + "DL2 cells, 2026-11-03."), applies=_saturation, ) diff --git a/tests/fixtures/histogram-intervals-11-03-26/T190LD5Q.LD0H b/tests/fixtures/histogram-intervals-11-03-26/T190LD5Q.LD0H new file mode 100755 index 0000000000000000000000000000000000000000..238a9b8e1bccfb2c4c91bb91dd694cd035037c46 GIT binary patch literal 1838 zcma)-TW}Lq7{|X&(`1{=UXrCc*r_K)pchioG(apAiUqWqV(kTo@j+v2;!MFo(iQ}P0!i8irYMs2JDY+!!vo)*vzu(b z+wc6(ZUkVq1GFizcuJx-ML4L2Nv9l&s^N&TiFC>Ft$om;M&Fi0@g`_<`#tXUQ8m7qtc$Ae zxL2!kkTkk|OTC?u&}Iycy%*_~dkM7mMq~v8)&;kb*65bLpt22mVzNrs2e-&g&@HQK z(A_R$j1mdONShL>cas-_sv3z!73h*9F%pP|ngCB^o}akMY$bxF$bV|}%A_+I3=>%U zL0neCa+s`-#^o63vS}6It42M#)u4jh40ND&)iB3U!WeNCpykxQ`v5Bg$y7wC*Hv1K z%XfS;_-fF5gRI6MKdNRE_-ZjK5LGrkepLNy;HyLT_DCpz7XzFIFZOORoMkRRDL}J- z0}HVH+tR~*u?Va<;LlbEY9RUpRF{Gg3U|tE<_WMu!|ZjrzAG`&1N-l}rvL69b8%nve|4-(=;B8!WzI7qR3$OhbD*&4iIqP z!@a|Brn$%xfO!T^XK^!bfdys~pCeMiz{$^ceR*smJ$!C#d>n};Zr;jH z=5No;{PnkB9Cr|ZDH4@gZ8nbMXjz>{lB78}oRWlCNToAz93t6@NM>)D3K_-Tn>k;N}n$JnX+L)9ZEp27K82_fKw}r zL~XE;Dd0u9FLVYNa&U-x`gtMpoDh_rAn7Ni+w z`@o&?k;f>CyRV$Q9Jt*hQRFKs@LIaP*)IPkPRd3)=Dhx6-&*ZfMh)Ctxne S&b~)H58o#){P%!s3;qE{> + +8.0 +Full Histogram +BE18190 +V 10.72-8.17 MiniMate Plus +T190LD5Q.LD0H +11:00:49 +2025-12-09 +11:00:59 +2025-12-09 + +Tran +Vert +Long +MicL + +1.00 +1 minute +1024 sps +6.9 Volts +June 13, 2025 by Instantel +in/s and dB(L) +I-80-North Fork-Area 3-462Richardsvilel +Fay Company +Terra-Mechanics Inc.- Harrison +Loc #8 - Area 3- 462 Richardsville Road + +10.000 +in/s + + +2.140 +in/s + + +OORANGE +in/s + + +2.830 +in/s + + +>100 +Hz + + +85 +Hz + + +34 +Hz + +11:00:59 +2025-12-09 +11:00:59 +2025-12-09 +11:00:59 +2025-12-09 + +OORANGE +in/s + +11:00:59 +2025-12-09 +Linear Weighting + +106.0 +dB(L) + +11:00:59 +2025-12-09 + +85 +Hz + +7.4 Hz. +4.4 +Passed +7.6 Hz. +3.5 +Passed +7.3 Hz. +3.9 +Passed +20.5 Hz. +691 mv +Passed + + +2025-12-09 11:00:48 - 2025-12-09 11:00:59 "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 + + + + +2.140>100OORANGE852.83034OORANGE0.001106.085 + + + + + + diff --git a/tests/test_decode_check.py b/tests/test_decode_check.py index 503023a..8edaca6 100644 --- a/tests/test_decode_check.py +++ b/tests/test_decode_check.py @@ -300,3 +300,28 @@ def test_blastwares_interval_frequency_words(halfp, sr, want): # below 1 Hz -- on ~3.1 M DL2 cells, 2026-11-03. from minimateplus.decode_check import interval_frequency assert interval_frequency(halfp, sr) == want + + +def _pvs_oorange(unclamp=False): + hb = FIX.parent / "histogram-intervals-11-03-26" + ref = parse_xml_report_file(hb / "T190LD5Q_LD0H_XML.XML") # Geo PVS OORANGE, Vert OORANGE + if unclamp: + cols = ref.interval_columns + t, row = ref.intervals[0] + row = list(row) + row[cols.index("Vert Peak in/s")] = "0.500" + ref.intervals[0] = (t, row) + res = {r.field: r for r in compare(sfm_side((hb / "T190LD5Q.LD0H").read_bytes()), ref, CARVEOUTS)} + return res["intervals.Geo PVS in/s"] + + +def test_an_oorange_interval_vector_sum_is_saturation(): + # Blastware prints OORANGE for an interval's vector sum above the range when + # it clamped a channel in that interval: 17 / 17 DL2 cells, SFM's sum + # 10.01 .. 17.33 (= sqrt 3 x 10.005). + r = _pvs_oorange() + assert (r.verdict, r.carveout) == ("accepted", "saturation") + + +def test_an_oorange_vector_sum_needs_a_clamped_channel_in_that_interval(): + assert _pvs_oorange(unclamp=True).verdict == "mismatch"