fix(sfm): Thor .h5 samples use Thor's LSB, not the MiniMate count scale (#42)
Every idf-import .h5 converted Thor's raw geo counts with the MiniMate body-codec scale, full_scale / _GEO_INT16_FS. A Thor count is 0.000310308 in/s (micromate.idf_file._GEO_LSB_IPS), so the float samples disagreed with the event's own peak by a constant: 10/32768 (until686ab6e, 2026-08-25) samples -1.65% 10/32000 (since) samples +0.71% v0.30.0's LSB fix (726c2ce) never reached this path. It corrected the decoder's peaks, which were already right in the DB, sidecar and h5 peak attrs. The sample arrays go through the shared .h5 writer instead. write_event_hdf5 now takes geo_ips_per_count. save_imported_idf and backfill_thor_events (which replays the same bridge with its own write) both pass _GEO_LSB_IPS. MiniMate callers are unchanged. Measured: all 8 thor-idf fixtures (4 IDFW + 4 IDFH, 24 channels) go from max|sample| / peak = 1.00706 to 1.00000 through the real ingest path. Operational consequence: no schema change, no migration, TOOL_VERSION not bumped here. Existing idf-import .h5 files keep the wrong scale until regenerated: scripts/backfill_thor_events.py (--force, or bump TOOL_VERSION at release), then backfill_event_shape.py, because the offset detector reads these samples. Series-3 files are unaffected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
618fcb7770
commit
e506bcff9b
5 files changed
+124
-10
No files matched your search
@@ -287,7 +287,7 @@ def main(argv=None) -> int:
|
|||||||
if is_histogram and idf_intervals:
|
if is_histogram and idf_intervals:
|
||||||
# 1 sample per interval per channel — same
|
# 1 sample per interval per channel — same
|
||||||
# synthesis save_imported_idf uses. The h5
|
# synthesis save_imported_idf uses. The h5
|
||||||
# writer's count×geo_fs/32768 conversion turns
|
# writer's count×_GEO_LSB_IPS conversion turns
|
||||||
# each peak-ADC-count into the bar's physical
|
# each peak-ADC-count into the bar's physical
|
||||||
# value.
|
# value.
|
||||||
ev.raw_samples = {
|
ev.raw_samples = {
|
||||||
@@ -311,12 +311,15 @@ def main(argv=None) -> int:
|
|||||||
from micromate.sensor_check import decode_idf_sensor_check
|
from micromate.sensor_check import decode_idf_sensor_check
|
||||||
ev.sensor_check = decode_idf_sensor_check(binary_bytes) or None
|
ev.sensor_check = decode_idf_sensor_check(binary_bytes) or None
|
||||||
|
|
||||||
|
# Thor counts, not MiniMate counts (issue #42).
|
||||||
|
from micromate.idf_file import _GEO_LSB_IPS
|
||||||
event_hdf5.write_event_hdf5(
|
event_hdf5.write_event_hdf5(
|
||||||
hdf5_path, ev,
|
hdf5_path, ev,
|
||||||
serial=serial,
|
serial=serial,
|
||||||
geo_range="normal",
|
geo_range="normal",
|
||||||
source_kind="idf-import",
|
source_kind="idf-import",
|
||||||
tool_version=event_file_io.TOOL_VERSION,
|
tool_version=event_file_io.TOOL_VERSION,
|
||||||
|
geo_ips_per_count=_GEO_LSB_IPS,
|
||||||
)
|
)
|
||||||
h5_written += 1
|
h5_written += 1
|
||||||
log.debug("%s/%s — .h5 written (%s)",
|
log.debug("%s/%s — .h5 written (%s)",
|
||||||
|
|||||||
+16
-3
@@ -139,17 +139,23 @@ def _ts_iso(ts) -> str:
|
|||||||
def _samples_to_float(
|
def _samples_to_float(
|
||||||
samples_int16: list[int],
|
samples_int16: list[int],
|
||||||
full_scale: float,
|
full_scale: float,
|
||||||
|
*,
|
||||||
|
ips_per_count: Optional[float] = None,
|
||||||
) -> np.ndarray:
|
) -> np.ndarray:
|
||||||
"""Convert int16 ADC counts → float32 physical units.
|
"""Convert int16 ADC counts → float32 physical units.
|
||||||
|
|
||||||
Uses _GEO_INT16_FS=32000 (see the constant's rationale): one decoder
|
Uses _GEO_INT16_FS=32000 (see the constant's rationale): one decoder
|
||||||
unit (16 ADC counts) is exactly 0.005 in/s, so full scale is 32000
|
unit (16 ADC counts) is exactly 0.005 in/s, so full scale is 32000
|
||||||
counts, not 32768.
|
counts, not 32768. That is the MiniMate body codec's count; a source
|
||||||
|
with a different count scale passes ``ips_per_count`` instead (Thor:
|
||||||
|
``micromate.idf_file._GEO_LSB_IPS``).
|
||||||
"""
|
"""
|
||||||
if not samples_int16:
|
if not samples_int16:
|
||||||
return np.array([], dtype=np.float32)
|
return np.array([], dtype=np.float32)
|
||||||
|
if ips_per_count is None:
|
||||||
|
ips_per_count = full_scale / _GEO_INT16_FS
|
||||||
arr = np.asarray(samples_int16, dtype=np.int32) # int32 to avoid overflow during scale
|
arr = np.asarray(samples_int16, dtype=np.int32) # int32 to avoid overflow during scale
|
||||||
return (arr.astype(np.float32) * (full_scale / _GEO_INT16_FS)).astype(np.float32)
|
return (arr.astype(np.float32) * ips_per_count).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
def _mic_scale_factor(
|
def _mic_scale_factor(
|
||||||
@@ -179,10 +185,15 @@ def write_event_hdf5(
|
|||||||
tool_version: Optional[str] = None,
|
tool_version: Optional[str] = None,
|
||||||
captured_at: Optional[datetime.datetime] = None,
|
captured_at: Optional[datetime.datetime] = None,
|
||||||
include_int16: bool = True,
|
include_int16: bool = True,
|
||||||
|
geo_ips_per_count: Optional[float] = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""
|
"""
|
||||||
Persist a decoded Event as an HDF5 file with samples in physical units.
|
Persist a decoded Event as an HDF5 file with samples in physical units.
|
||||||
|
|
||||||
|
``geo_ips_per_count`` overrides the range-derived MiniMate count scale
|
||||||
|
for sources whose counts differ — Thor IDF imports pass
|
||||||
|
``micromate.idf_file._GEO_LSB_IPS`` (issue #42).
|
||||||
|
|
||||||
Returns a small summary dict suitable for logging:
|
Returns a small summary dict suitable for logging:
|
||||||
{"path": Path, "n_samples": int, "geo_full_scale_ips": float}
|
{"path": Path, "n_samples": int, "geo_full_scale_ips": float}
|
||||||
"""
|
"""
|
||||||
@@ -199,7 +210,9 @@ def write_event_hdf5(
|
|||||||
# Per-channel float32 arrays in physical units.
|
# Per-channel float32 arrays in physical units.
|
||||||
geo_arrays = {}
|
geo_arrays = {}
|
||||||
for ch in ("Tran", "Vert", "Long"):
|
for ch in ("Tran", "Vert", "Long"):
|
||||||
geo_arrays[ch] = _samples_to_float(raw.get(ch, []), geo_fs)
|
geo_arrays[ch] = _samples_to_float(
|
||||||
|
raw.get(ch, []), geo_fs, ips_per_count=geo_ips_per_count,
|
||||||
|
)
|
||||||
|
|
||||||
# Mic channel — the per-count factor is resolved from the device-reported
|
# Mic channel — the per-count factor is resolved from the device-reported
|
||||||
# peak when available so the plot peaks the BW value exactly.
|
# peak when available so the plot peaks the BW value exactly.
|
||||||
|
|||||||
@@ -653,11 +653,9 @@ class WaveformStore:
|
|||||||
# caveats of this bridge (mic units, missing fields → sidecar).
|
# caveats of this bridge (mic units, missing fields → sidecar).
|
||||||
ev = idf_event.to_minimateplus_event(waveform_key)
|
ev = idf_event.to_minimateplus_event(waveform_key)
|
||||||
|
|
||||||
# Attach the decoded sample arrays. Thor's decoder counts use
|
# Attach the decoded sample arrays. These are raw Thor counts at
|
||||||
# LSB = 0.0003 in/s for geo (vs BW's 16-count units at 0.005 in/s)
|
# _GEO_LSB_IPS = 0.000310308 in/s, not the MiniMate's 10/32000;
|
||||||
# — the .h5 writer's geo_range="normal" yields LSB = 10/32768
|
# the .h5 write below passes that scale explicitly (issue #42).
|
||||||
# ≈ 0.000305 in/s, so plotted samples come out ~1.7% high.
|
|
||||||
# Acceptable known offset; refine with a Thor-aware h5 path later.
|
|
||||||
if idf_samples is not None:
|
if idf_samples is not None:
|
||||||
ev.raw_samples = idf_samples
|
ev.raw_samples = idf_samples
|
||||||
n_samples = max((len(idf_samples.get(ch, [])) for ch in ("Tran", "Vert", "Long", "MicL")), default=0)
|
n_samples = max((len(idf_samples.get(ch, [])) for ch in ("Tran", "Vert", "Long", "MicL")), default=0)
|
||||||
@@ -673,7 +671,7 @@ class WaveformStore:
|
|||||||
# a 1-sample-per-interval array so the existing h5+renderer pipeline
|
# a 1-sample-per-interval array so the existing h5+renderer pipeline
|
||||||
# (which groups samples down to ``n_intervals`` bars via max-per-group)
|
# (which groups samples down to ``n_intervals`` bars via max-per-group)
|
||||||
# produces a non-blank histogram chart. Each "sample" is the peak ADC
|
# produces a non-blank histogram chart. Each "sample" is the peak ADC
|
||||||
# count for that interval, so the h5 writer's ``count × geo_fs/32768``
|
# count for that interval, so the h5 writer's ``count × _GEO_LSB_IPS``
|
||||||
# conversion yields the right physical value for the bar height.
|
# conversion yields the right physical value for the bar height.
|
||||||
if is_histogram and idf_intervals:
|
if is_histogram and idf_intervals:
|
||||||
hist_samples = {
|
hist_samples = {
|
||||||
@@ -692,11 +690,13 @@ class WaveformStore:
|
|||||||
if ev.raw_samples:
|
if ev.raw_samples:
|
||||||
hdf5_path = self.hdf5_path_for(serial, filename)
|
hdf5_path = self.hdf5_path_for(serial, filename)
|
||||||
try:
|
try:
|
||||||
|
from micromate.idf_file import _GEO_LSB_IPS
|
||||||
event_hdf5.write_event_hdf5(
|
event_hdf5.write_event_hdf5(
|
||||||
hdf5_path, ev,
|
hdf5_path, ev,
|
||||||
serial=serial,
|
serial=serial,
|
||||||
geo_range="normal", # Thor's geo full scale is also 10 in/s (Normal)
|
geo_range="normal", # Thor's geo full scale is also 10 in/s (Normal)
|
||||||
source_kind="idf-import",
|
source_kind="idf-import",
|
||||||
|
geo_ips_per_count=_GEO_LSB_IPS,
|
||||||
)
|
)
|
||||||
hdf5_filename = hdf5_path.name
|
hdf5_filename = hdf5_path.name
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
|
|||||||
@@ -132,6 +132,26 @@ def test_hdf5_samples_in_physical_units_sensitive_range(tmp_path: Path):
|
|||||||
assert abs(max(vert) - expected_peak) < 1e-4
|
assert abs(max(vert) - expected_peak) < 1e-4
|
||||||
|
|
||||||
|
|
||||||
|
def test_hdf5_geo_ips_per_count_replaces_range_scale(tmp_path: Path):
|
||||||
|
"""A source whose counts have their own scale passes it explicitly.
|
||||||
|
|
||||||
|
The range-derived ``full_scale / 32000`` is the MiniMate body codec's
|
||||||
|
count; a Thor count is 0.000310308 in/s. Using the MiniMate scale for
|
||||||
|
Thor counts read every sample 0.71% high (issue #42)."""
|
||||||
|
ev = _make_event_with_samples()
|
||||||
|
h5 = tmp_path / "t.h5"
|
||||||
|
event_hdf5.write_event_hdf5(
|
||||||
|
h5, ev, serial="UM12947", geo_range="normal",
|
||||||
|
geo_ips_per_count=0.000310308,
|
||||||
|
)
|
||||||
|
data = event_hdf5.read_event_hdf5(h5)
|
||||||
|
|
||||||
|
vert = data["samples"]["Vert"]
|
||||||
|
assert abs(max(vert) - 32767 * 0.000310308) < 1e-5
|
||||||
|
# The range attrs still describe the range, not the count scale.
|
||||||
|
assert data["attrs"]["geo_full_scale_ips"] == 10.0
|
||||||
|
|
||||||
|
|
||||||
def test_hdf5_includes_int16_samples(tmp_path: Path):
|
def test_hdf5_includes_int16_samples(tmp_path: Path):
|
||||||
ev = _make_event_with_samples()
|
ev = _make_event_with_samples()
|
||||||
h5 = tmp_path / "i.h5"
|
h5 = tmp_path / "i.h5"
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Thor (Micromate) .h5 samples are scaled with Thor's own LSB (issue #42).
|
||||||
|
|
||||||
|
A Thor geo count is 0.000310308 in/s (``micromate.idf_file._GEO_LSB_IPS``).
|
||||||
|
The .h5 writer used to convert Thor counts with the MiniMate body-codec scale
|
||||||
|
instead -- 10/32768 until 2026-08-25 (samples -1.65%), 10/32000 after
|
||||||
|
(+0.71%). Stored peaks were right; every float sample disagreed with them
|
||||||
|
by that constant, so waveform plots, FFT magnitudes and the offset detector
|
||||||
|
all read off-scale for Series-4 events.
|
||||||
|
|
||||||
|
The invariant tested: for an idf-import .h5, max|float32 sample| equals the
|
||||||
|
event's peak to float32 precision, and every sample is count x Thor LSB.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import h5py
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from micromate.idf_file import _GEO_LSB_IPS
|
||||||
|
from sfm.waveform_store import WaveformStore
|
||||||
|
|
||||||
|
_FIXDIR = Path(__file__).parent / "fixtures"
|
||||||
|
_IDFW = sorted((_FIXDIR / "thor-idf-sc").glob("*.IDFW")) # tracked
|
||||||
|
_IDFH = sorted((_FIXDIR / "thor-idf").glob("*.IDFH")) # untracked on dev
|
||||||
|
_GEO = ("Tran", "Vert", "Long")
|
||||||
|
|
||||||
|
|
||||||
|
def _ingest(tmp_path: Path, src: Path) -> tuple[WaveformStore, Path]:
|
||||||
|
store = WaveformStore(tmp_path / "waveforms")
|
||||||
|
store.save_imported_idf(src.read_bytes(), src)
|
||||||
|
serial = src.name.split("_")[0]
|
||||||
|
return store, store.hdf5_path_for(serial, src.name)
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_thor_scaled(h5_path: Path) -> None:
|
||||||
|
with h5py.File(h5_path, "r") as f:
|
||||||
|
for ch in _GEO:
|
||||||
|
counts = f["samples_int16"][ch][()]
|
||||||
|
v = f["samples"][ch][()]
|
||||||
|
np.testing.assert_allclose(v, counts * _GEO_LSB_IPS, rtol=1e-6)
|
||||||
|
peak = float(f.attrs[f"peak_{ch.lower()}_ips"])
|
||||||
|
assert float(np.max(np.abs(v))) == pytest.approx(peak, rel=1e-6), ch
|
||||||
|
|
||||||
|
|
||||||
|
def test_fixtures_present():
|
||||||
|
# Guards the parametrised tests below from silently collecting nothing.
|
||||||
|
assert len(_IDFW) == 4
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("src", _IDFW, ids=lambda p: p.name)
|
||||||
|
def test_idfw_ingest_samples_use_thor_lsb(tmp_path, src):
|
||||||
|
_, h5_path = _ingest(tmp_path, src)
|
||||||
|
_assert_thor_scaled(h5_path)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.skipif(not _IDFH, reason="tests/fixtures/thor-idf/*.IDFH not present")
|
||||||
|
@pytest.mark.parametrize("src", _IDFH, ids=lambda p: p.name)
|
||||||
|
def test_idfh_ingest_interval_peaks_use_thor_lsb(tmp_path, src):
|
||||||
|
_, h5_path = _ingest(tmp_path, src)
|
||||||
|
_assert_thor_scaled(h5_path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_backfill_thor_events_regenerates_with_thor_lsb(tmp_path):
|
||||||
|
# The backfill replays save_imported_idf's bridge with its own
|
||||||
|
# write_event_hdf5 call, so it has to be held to the same scale.
|
||||||
|
from scripts.backfill_thor_events import main as backfill_main
|
||||||
|
|
||||||
|
src = _IDFW[0]
|
||||||
|
store, h5_path = _ingest(tmp_path, src)
|
||||||
|
h5_path.unlink()
|
||||||
|
|
||||||
|
rc = backfill_main(["--store-root", str(store.root), "--force"])
|
||||||
|
|
||||||
|
assert rc == 0
|
||||||
|
assert h5_path.exists()
|
||||||
|
_assert_thor_scaled(h5_path)
|
||||||
Reference in new issue
Block a user