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/<ch>,
/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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-03 17:34:27 -05:00
1 parent 67b3ef8d0a
commit 2b698e74cf
10 files changed
+312 -32

No files matched your search

+51 -9
View File
@@ -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)
+30 -11
View File
@@ -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
+18 -11
View File
@@ -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:
+5
View File
@@ -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
+21
View File
@@ -38,6 +38,10 @@ Layout written to `<filename>.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/<ch> 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:
Binary file not shown.
+116
View File
@@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<Event>
<FileVersion>8.0</FileVersion>
<EventType>Full Histogram</EventType>
<SerialNumber>BE18190</SerialNumber>
<Version>V 10.72-8.17 MiniMate Plus</Version>
<FileName>T190LD42.T00H</FileName>
<HistogramStartTime>13:29:24</HistogramStartTime>
<HistogramStartDate>2025-12-08</HistogramStartDate>
<HistogramStopTime>13:29:37</HistogramStopTime>
<HistogramStopDate>2025-12-08</HistogramStopDate>
<Channels>
<Channel>Tran</Channel>
<Channel>Vert</Channel>
<Channel>Long</Channel>
<Channel>MicL</Channel>
</Channels>
<NumberofIntervals>1.00</NumberofIntervals>
<IntervalSize>1 minute</IntervalSize>
<SampleRate>2048 sps</SampleRate>
<BatteryLevel>6.7 Volts</BatteryLevel>
<Calibration>June 13, 2025 by Instantel</Calibration>
<Units>in/s and dB(L)</Units>
<Project>I-80-North Fork-Area 3-462Richardsvilel</Project>
<Client>Fay Company</Client>
<UserName>Terra-Mechanics Inc.- Harrison</UserName>
<SeisLoc>Loc #8 - Area 3- 462 Richardsville Road</SeisLoc>
<GeoRange>
<Value>10.000</Value>
<Units>in/s</Units>
</GeoRange>
<TranPPV>
<Value>1.280</Value>
<Units>in/s</Units>
</TranPPV>
<VertPPV>
<Value>2.615</Value>
<Units>in/s</Units>
</VertPPV>
<LongPPV>
<Value>1.120</Value>
<Units>in/s</Units>
</LongPPV>
<TranZCFreq>
<Value>15.5</Value>
<Units>Hz</Units>
</TranZCFreq>
<VertZCFreq>
<Value>64</Value>
<Units>Hz</Units>
</VertZCFreq>
<LongZCFreq>
<Value>17.7</Value>
<Units>Hz</Units>
</LongZCFreq>
<TranPeakTime>13:29:37</TranPeakTime>
<TranPeakDate>2025-12-08</TranPeakDate>
<VertPeakTime>13:29:37</VertPeakTime>
<VertPeakDate>2025-12-08</VertPeakDate>
<LongPeakTime>13:29:37</LongPeakTime>
<LongPeakDate>2025-12-08</LongPeakDate>
<PeakVectorSum>
<Value>2.644</Value>
<Units>in/s</Units>
</PeakVectorSum>
<PeakVectorSumTime>13:29:37</PeakVectorSumTime>
<PeakVectorSumDate>2025-12-08</PeakVectorSumDate>
<Microphone>Linear Weighting</Microphone>
<MicLPSPL>
<Value>107.0</Value>
<Units>dB(L)</Units>
</MicLPSPL>
<MicLTime>13:29:37</MicLTime>
<MicLDate>2025-12-08</MicLDate>
<MicLZCFreq>
<Value>51</Value>
<Units>Hz</Units>
</MicLZCFreq>
<TranTestFreq>7.4 Hz.</TranTestFreq>
<TranTestRatio>4.2</TranTestRatio>
<TranTestResults>Passed</TranTestResults>
<VertTestFreq>7.6 Hz.</VertTestFreq>
<VertTestRatio>3.4</VertTestRatio>
<VertTestResults>Passed</VertTestResults>
<LongTestFreq>7.3 Hz.</LongTestFreq>
<LongTestRatio>3.7</LongTestRatio>
<LongTestResults>Passed</LongTestResults>
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
<MicLTestResults>Check</MicLTestResults>
<UsbSummaryChannels>
</UsbSummaryChannels>
<MonitorLog>2025-12-08 13:29:23 - 2025-12-08 13:29:37 &quot;Event Recorded Modem Exit&quot;</MonitorLog>
<HistogramData>
<HistogramDataColumnTitle>
<ColumnTitle> Tran Peak in/s </ColumnTitle>
<ColumnTitle> Tran Freq Hz </ColumnTitle>
<ColumnTitle> Vert Peak in/s </ColumnTitle>
<ColumnTitle> Vert Freq Hz </ColumnTitle>
<ColumnTitle> Long Peak in/s </ColumnTitle>
<ColumnTitle> Long Freq Hz </ColumnTitle>
<ColumnTitle> Geo PVS in/s </ColumnTitle>
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
<ColumnTitle> MicL Freq Hz </ColumnTitle>
</HistogramDataColumnTitle>
<HistogramDataIntervals>
<Time>2025-12-08 13:29:37</Time>
<Row>
<Cell>1.280</Cell><Cell>15.5</Cell><Cell>2.615</Cell><Cell>64</Cell><Cell>1.120</Cell><Cell>17.7</Cell><Cell>2.644</Cell><Cell>0.001</Cell><Cell>107.0</Cell><Cell>51</Cell></Row>
</HistogramDataIntervals>
</HistogramData>
<HistogramDataUsbChannels>
</HistogramDataUsbChannels>
</Event>
+42
View File
@@ -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
+22 -1
View File
@@ -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
+7
View File
@@ -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