"""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)