diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index c335b080..21a12b98 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -2390,6 +2390,60 @@ class _SingleSegmentReadResult(typing.NamedTuple): return_res: int +class _LoadedSignalValues(typing.NamedTuple): + """Signal values with explicit physical/digital and frame layout modes.""" + + values: "np.ndarray | list[np.ndarray]" + physical: bool + expanded: bool + + def set_on_record(self, record: Record) -> None: + """Validate the mode and fill only its matching legacy signal field.""" + if self.expanded: + if not isinstance(self.values, list) or len(self.values) != record.n_sig: + raise ValueError("Expanded signals must have one array per channel") + arrays = self.values + dimensions = 1 + else: + if not isinstance(self.values, np.ndarray): + raise ValueError("Uniform signals must be a two-dimensional array") + arrays = [self.values] + dimensions = 2 + kind = "f" if self.physical else "iu" + if any( + not isinstance(array, np.ndarray) + or array.ndim != dimensions + or array.dtype.kind not in kind + for array in arrays + ): + raise ValueError("Signal values do not match their loaded mode") + if self.expanded: + spf = record.samps_per_frame + if spf is None or len(spf) != record.n_sig: + raise ValueError("Expanded signals need samples per frame") + for ch, (array, samples_per_frame) in enumerate(zip(arrays, spf)): + expected = record.sig_len * ( + 1 if samples_per_frame is None else samples_per_frame + ) + if len(array) != expected: + raise ValueError( + f"Expanded signal {ch} has {len(array)} samples; " + f"expected {expected}" + ) + elif self.values.shape != (record.sig_len, record.n_sig): + raise ValueError( + f"Uniform signal shape {self.values.shape} does not match " + f"({record.sig_len}, {record.n_sig})" + ) + + field = ("e_" if self.expanded else "") + ( + "p_signal" if self.physical else "d_signal" + ) + for name in ("p_signal", "d_signal", "e_p_signal", "e_d_signal"): + setattr(record, name, None) + setattr(record, field, self.values) + + def _record_from_single_segment_read(read: _SingleSegmentReadResult) -> Record: """Build a selected `Record` without changing its source header.""" record = read.record @@ -2400,12 +2454,13 @@ def _record_from_single_segment_read(read: _SingleSegmentReadResult) -> Record: smooth_frames=read.smooth_frames, ) + expanded = not read.smooth_frames if read.physical: - record.dac( - expanded=not read.smooth_frames, - return_res=read.return_res, - inplace=True, - ) + record.dac(expanded=expanded, return_res=read.return_res, inplace=True) + values = record.e_p_signal if expanded else record.p_signal + else: + values = record.e_d_signal if expanded else record.d_signal + _LoadedSignalValues(values, read.physical, expanded).set_on_record(record) if not read.ignore_skew and record.skew is not None and any(record.skew): record._applied_skew = list(record.skew) diff --git a/tests/test_record_signal_modes.py b/tests/test_record_signal_modes.py new file mode 100644 index 00000000..f878d674 --- /dev/null +++ b/tests/test_record_signal_modes.py @@ -0,0 +1,74 @@ +"""Loaded signal value layouts for single-segment reads.""" + +import numpy as np +import pytest + +import wfdb +from wfdb.io.record import _LoadedSignalValues + + +@pytest.mark.parametrize("physical", [False, True]) +@pytest.mark.parametrize("expanded", [False, True]) +def test_multifrequency_record_uses_one_signal_field(physical, expanded): + """Unit and frame choices select one field with the expected shape.""" + record = wfdb.rdrecord( + "sample-data/mixedsignals", + sampto=3, + physical=physical, + smooth_frames=not expanded, + return_res=32, + ) + field = ("e_" if expanded else "") + ("p_signal" if physical else "d_signal") + fields = ("p_signal", "d_signal", "e_p_signal", "e_d_signal") + + assert (record.sig_len, record.n_sig) == (3, 6) + assert [name for name in fields if getattr(record, name) is not None] == [field] + values = getattr(record, field) + if expanded: + assert isinstance(values, list) + assert [len(signal) for signal in values] == [12, 12, 12, 6, 6, 3] + assert all( + signal.dtype == f"{'float' if physical else 'int'}32" for signal in values + ) + else: + assert values.shape == (3, 6) + assert values.dtype == f"{'float' if physical else 'int'}32" + + +@pytest.mark.parametrize("smooth_frames", [False, True]) +def test_physical_values_keep_missing_samples_after_skew(smooth_frames): + """Digital missing markers become NaNs while other values are calibrated.""" + path = "sample-data/100skew" + options = {"sampfrom": 649995, "sampto": 650000, "smooth_frames": smooth_frames} + digital = wfdb.rdrecord(path, physical=False, **options) + physical = wfdb.rdrecord(path, physical=True, **options) + digital_values = digital.d_signal[:, 1] if smooth_frames else digital.e_d_signal[1] + physical_values = ( + physical.p_signal[:, 1] if smooth_frames else physical.e_p_signal[1] + ) + + np.testing.assert_allclose( + physical_values[:-3], + (digital_values[:-3] - digital.baseline[1]) / digital.adc_gain[1], + ) + assert np.isnan(physical_values[-3:]).all() + + +def test_uniform_mode_rejects_wrong_channel_count(): + """A uniform array must match both the frame and channel counts.""" + record = wfdb.Record(sig_len=3, n_sig=2) + values = _LoadedSignalValues(np.zeros((3, 1), dtype=np.int16), False, False) + + with pytest.raises(ValueError, match="Uniform signal shape"): + values.set_on_record(record) + assert record.d_signal is None + + +def test_expanded_mode_rejects_wrong_sample_count(): + """Expanded channels must contain their frame count times their rate.""" + record = wfdb.Record(sig_len=3, n_sig=1, samps_per_frame=[2]) + values = _LoadedSignalValues([np.zeros(2, dtype=np.int16)], False, True) + + with pytest.raises(ValueError, match="expected 6"): + values.set_on_record(record) + assert record.e_d_signal is None