From 470405f54579377ac34354d84ee61c6d32c297d0 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 12:40:45 -0500 Subject: [PATCH 1/2] Handle missing skew tails in format 8 reads --- changelog.d/format8-skew-tail.rst | 7 ++ src/wfdb/io/_read_model.py | 38 ++++++++ src/wfdb/io/_signal.py | 9 +- src/wfdb/io/record.py | 11 +++ tests/test_format8_skew_tail.py | 145 ++++++++++++++++++++++++++++++ 5 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 changelog.d/format8-skew-tail.rst create mode 100644 tests/test_format8_skew_tail.py diff --git a/changelog.d/format8-skew-tail.rst b/changelog.d/format8-skew-tail.rst new file mode 100644 index 00000000..91ba92bd --- /dev/null +++ b/changelog.d/format8-skew-tail.rst @@ -0,0 +1,7 @@ +**Read skewed format-8 signals to the record end** + Aligned ``read_signals`` values now identify the unavailable tail of a + skewed format-8 signal with a digital mask or physical NaNs. This also + works in expanded and multi-segment reads. Legacy ``rdrecord`` raises a + clear ``ValueError`` for such a tail because format 8 has no digital + missing-sample marker; ``ignore_skew=True`` can read the raw values. + Expanded skewed reads now mark every sample in each missing frame. diff --git a/src/wfdb/io/_read_model.py b/src/wfdb/io/_read_model.py index 06655647..8ed47fb3 100644 --- a/src/wfdb/io/_read_model.py +++ b/src/wfdb/io/_read_model.py @@ -382,6 +382,15 @@ def read_single_segment( ) for index, (signal, checksum) in enumerate(zip(selected, checksums)) ) + # A format-8 file has no reserved integer marker for the samples beyond a + # skewed channel's end. The decoder uses zero in those positions; the view + # must identify them independently of their value. + missing_tail = [ + min(stop - start, max(0, stop + (signal.skew or 0) - length)) + if signal.fmt == "8" and signal_alignment == "aligned" + else 0 + for signal in selected + ] if kind == "physical": values = _dac_values( digital, @@ -393,6 +402,14 @@ def read_single_segment( ) if expanded: values = tuple(values) + for index, frames in enumerate(missing_tail): + if frames: + if expanded: + values[index][ + -frames * (selected[index].samps_per_frame or 1) : + ] = np.nan + else: + values[-frames:, index] = np.nan mask = None else: dtype = f"int{resolution}" @@ -409,6 +426,27 @@ def read_single_segment( converted.append(array) values = tuple(converted) if expanded else converted[0] mask = _digital_mask(values, selected, expanded) + if any(missing_tail): + if expanded: + mask = [ + np.zeros(len(array), dtype=bool) + if mask is None or mask[index] is np.ma.nomask + else mask[index].copy() + for index, array in enumerate(values) + ] + for index, frames in enumerate(missing_tail): + if frames: + mask[index][ + -frames * (selected[index].samps_per_frame or 1) : + ] = True + mask = tuple(mask) + else: + mask = ( + np.zeros(values.shape, dtype=bool) if mask is None else mask.copy() + ) + for index, frames in enumerate(missing_tail): + if frames: + mask[-frames:, index] = True base_date, base_time = _adjust_time( fields.base_date, fields.base_time, fields.fs, start ) diff --git a/src/wfdb/io/_signal.py b/src/wfdb/io/_signal.py index 5a956750..abebae5e 100644 --- a/src/wfdb/io/_signal.py +++ b/src/wfdb/io/_signal.py @@ -2034,7 +2034,11 @@ def _skew_sig(sig, skew, n_sig, read_len, fmt, nan_replace, samps_per_frame=None # Insert nans where skewed signal overran dat file for ch in range(n_sig): if nan_replace[ch] > 0: - sig[ch][-nan_replace[ch] :] = _digi_nan(fmt) + count = nan_replace[ch] * samps_per_frame[ch] + # Format 8 has no reserved missing value. The modern reader + # carries this tail in its mask; zero is only a placeholder. + marker = _digi_nan(fmt) + sig[ch][-count:] = 0 if marker is None else marker # Uniform array else: # Shift the channel samples @@ -2047,7 +2051,8 @@ def _skew_sig(sig, skew, n_sig, read_len, fmt, nan_replace, samps_per_frame=None # Insert nans where skewed signal overran dat file for ch in range(n_sig): if nan_replace[ch] > 0: - sig[-nan_replace[ch] :, ch] = _digi_nan(fmt) + marker = _digi_nan(fmt) + sig[-nan_replace[ch] :, ch] = 0 if marker is None else marker return sig diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 67869242..c781a287 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -4118,6 +4118,17 @@ def _rdrecord( # A single segment record elif isinstance(record, Record): + if not ignore_skew and any( + record.fmt[channel] == "8" + and sampto + (record.skew[channel] or 0) > record.sig_len + for channel in channels + ): + raise ValueError( + "Cannot represent the skewed tail of a format 8 signal in a " + "legacy Record: format 8 has no missing-sample marker. " + "Use read_signals for masked digital values or physical NaNs, " + "or set ignore_skew=True." + ) values = _signal._rd_segment( file_name=record.file_name, dir_name=dir_name, diff --git a/tests/test_format8_skew_tail.py b/tests/test_format8_skew_tail.py new file mode 100644 index 00000000..9f0d4830 --- /dev/null +++ b/tests/test_format8_skew_tail.py @@ -0,0 +1,145 @@ +"""Missing samples beyond the end of a skewed format-8 signal.""" + +import numpy as np +import pytest + +import wfdb + + +def _record(tmp_path, samples_per_frame): + """Create a short difference-encoded signal with a two-frame skew.""" + name = f"skew{samples_per_frame}" + (tmp_path / f"{name}.dat").write_bytes(bytes([1] * (8 * samples_per_frame))) + fmt = "8" if samples_per_frame == 1 else f"8x{samples_per_frame}" + (tmp_path / f"{name}.hea").write_text( + f"{name} 1 125 8\n{name}.dat {fmt}:2 200/mV 12 0 0 0 0 I\n" + ) + return tmp_path / name + + +def _channel(read, layout): + """Get the only channel's samples in either layout.""" + return read.signals.values[:, 0] if layout == "uniform" else read.signals.values[0] + + +@pytest.mark.parametrize("samples_per_frame", [1, 2]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_modern_skew_tail_has_mask_and_nan(tmp_path, samples_per_frame, layout): + """Aligned format-8 tails remain missing through read and conversion.""" + path = _record(tmp_path, samples_per_frame) + digital = wfdb.read_signals(path, kind="digital", layout=layout) + values = _channel(digital, layout) + factor = 1 if layout == "uniform" else samples_per_frame + expected_mask = [False] * (6 * factor) + [True] * (2 * factor) + np.testing.assert_array_equal(np.ma.getmaskarray(values), expected_mask) + expected_values = ( + np.arange(1, 7, dtype=values.dtype) * 2 + 4 + if layout == "uniform" and samples_per_frame == 2 + else np.arange(1, 6 * factor + 1, dtype=values.dtype) + 2 * samples_per_frame + ) + np.testing.assert_array_equal(values.compressed(), expected_values) + + physical = wfdb.read_signals(path, kind="physical", layout=layout) + np.testing.assert_array_equal(np.isnan(_channel(physical, layout)), expected_mask) + np.testing.assert_array_equal( + np.isnan(_channel(digital.to_physical(), layout)), expected_mask + ) + np.testing.assert_array_equal( + np.ma.getmaskarray(_channel(physical.to_digital(), layout)), expected_mask + ) + with pytest.raises(ValueError, match="format 8.*no missing-sample marker"): + digital.to_legacy_record() + + raw = wfdb.read_signals(path, kind="digital", layout=layout, signal_alignment="raw") + assert not np.ma.getmaskarray(_channel(raw, layout)).any() + unskewed = wfdb.read_signals(path, kind="digital", layout=layout, stop=6) + assert not np.ma.getmaskarray(_channel(unskewed, layout)).any() + + +@pytest.mark.parametrize("kind", ["digital", "physical"]) +def test_windowed_tail_marks_only_missing_frames(tmp_path, kind): + """A window that partly overlaps the tail retains valid samples.""" + path = _record(tmp_path, 1) + read = wfdb.read_signals(path, kind=kind, layout="uniform", start=4, stop=7) + if kind == "digital": + np.testing.assert_array_equal(read.signals.values.mask[:, 0], [0, 0, 1]) + np.testing.assert_array_equal(read.signals.values[:2, 0], [7, 8]) + else: + np.testing.assert_allclose(read.signals.values[:2, 0], [7 / 200, 8 / 200]) + assert np.isnan(read.signals.values[-1, 0]) + + +def test_skewed_format8_can_write_with_missing_marker(tmp_path): + """A masked skew tail can be stored using a format with a marker.""" + path = _record(tmp_path, 1) + read = wfdb.read_signals(path, kind="digital", layout="uniform") + read.write(tmp_path / "copy", formats="16", signal_alignment="aligned") + reread = wfdb.read_signals(tmp_path / "copy", kind="digital", layout="uniform") + np.testing.assert_array_equal(reread.signals.values.mask, read.signals.values.mask) + np.testing.assert_array_equal( + reread.signals.values.compressed(), read.signals.values.compressed() + ) + + +@pytest.mark.parametrize("physical", [False, True]) +def test_legacy_read_rejects_unrepresentable_tail(tmp_path, physical): + """Legacy Record gives a clear error instead of a NumPy TypeError.""" + path = _record(tmp_path, 1) + with pytest.raises(ValueError, match="format 8 has no missing-sample marker"): + wfdb.rdrecord(path, physical=physical) + raw = wfdb.rdrecord(path, physical=False, ignore_skew=True) + np.testing.assert_array_equal(raw.d_signal[:, 0], np.arange(1, 9)) + + +def test_multisegment_read_keeps_each_skewed_tail(tmp_path): + """Flattening and segment reads preserve the per-segment masks.""" + _record(tmp_path, 1) + (tmp_path / "multi.hea").write_text("multi/2 1 125 16\nskew1 8\nskew1 8\n") + combined = wfdb.read_signals(tmp_path / "multi", kind="digital", layout="uniform") + np.testing.assert_array_equal( + combined.signals.values.mask[:, 0], + [False] * 6 + [True] * 2 + [False] * 6 + [True] * 2, + ) + segments = wfdb.read_segments(tmp_path / "multi", kind="digital", layout="expanded") + assert len(segments.segments) == 2 + for segment in segments.segments: + np.testing.assert_array_equal( + segment.data.signals.values[0].mask, + [False] * 6 + [True] * 2, + ) + + +def test_expanded_skew_marks_every_sample_in_missing_frames(tmp_path): + """The shared decoder accounts for samples per frame when filling a tail.""" + (tmp_path / "other.dat").write_bytes(np.arange(16, dtype=" Date: Fri, 4 Dec 2026 12:49:19 -0500 Subject: [PATCH 2/2] Return physical NaNs for legacy format 8 skew tails --- changelog.d/format8-skew-tail.rst | 13 ++++++++---- src/wfdb/io/record.py | 27 +++++++++++++++++------- tests/test_format8_skew_tail.py | 35 +++++++++++++++++++++++++++---- 3 files changed, 60 insertions(+), 15 deletions(-) diff --git a/changelog.d/format8-skew-tail.rst b/changelog.d/format8-skew-tail.rst index 91ba92bd..9132eb5c 100644 --- a/changelog.d/format8-skew-tail.rst +++ b/changelog.d/format8-skew-tail.rst @@ -1,7 +1,12 @@ **Read skewed format-8 signals to the record end** Aligned ``read_signals`` values now identify the unavailable tail of a skewed format-8 signal with a digital mask or physical NaNs. This also - works in expanded and multi-segment reads. Legacy ``rdrecord`` raises a - clear ``ValueError`` for such a tail because format 8 has no digital - missing-sample marker; ``ignore_skew=True`` can read the raw values. - Expanded skewed reads now mark every sample in each missing frame. + works in expanded and multi-segment reads. Legacy ``rdrecord`` returns + physical NaNs, or raises a clear ``ValueError`` for digital values because + format 8 has no digital missing-sample marker; ``ignore_skew=True`` can + read the raw values. + + Expanded reads of skewed signals with more than one sample per frame + previously returned some samples beyond the end of the signal as zero + instead of missing. Every sample of each missing frame is now marked, in + ``rdrecord`` as well as the modern readers, for all signal formats. diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index c781a287..fcb6ffec 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -4118,16 +4118,21 @@ def _rdrecord( # A single segment record elif isinstance(record, Record): - if not ignore_skew and any( - record.fmt[channel] == "8" - and sampto + (record.skew[channel] or 0) > record.sig_len + markerless_tails = [ + min( + sampto - sampfrom, + max(0, sampto + (record.skew[channel] or 0) - record.sig_len), + ) + if not ignore_skew and record.fmt[channel] == "8" + else 0 for channel in channels - ): + ] + if not physical and any(markerless_tails): raise ValueError( "Cannot represent the skewed tail of a format 8 signal in a " - "legacy Record: format 8 has no missing-sample marker. " - "Use read_signals for masked digital values or physical NaNs, " - "or set ignore_skew=True." + "digital legacy Record: format 8 has no missing-sample marker. " + "Use read_signals for masked digital values, read physical " + "values, or set ignore_skew=True." ) values = _signal._rd_segment( file_name=record.file_name, @@ -4162,6 +4167,14 @@ def _rdrecord( return_res=return_res, ) ) + if physical: + for channel, frames in enumerate(markerless_tails): + if frames: + if smooth_frames: + record.p_signal[-frames:, channel] = np.nan + else: + factor = record.samps_per_frame[channel] or 1 + record.e_p_signal[channel][-frames * factor :] = np.nan # A multi segment record else: diff --git a/tests/test_format8_skew_tail.py b/tests/test_format8_skew_tail.py index 9f0d4830..f802672c 100644 --- a/tests/test_format8_skew_tail.py +++ b/tests/test_format8_skew_tail.py @@ -81,16 +81,33 @@ def test_skewed_format8_can_write_with_missing_marker(tmp_path): ) -@pytest.mark.parametrize("physical", [False, True]) -def test_legacy_read_rejects_unrepresentable_tail(tmp_path, physical): - """Legacy Record gives a clear error instead of a NumPy TypeError.""" +def test_legacy_digital_read_rejects_unrepresentable_tail(tmp_path): + """A digital Record gives a clear error instead of a NumPy TypeError.""" path = _record(tmp_path, 1) with pytest.raises(ValueError, match="format 8 has no missing-sample marker"): - wfdb.rdrecord(path, physical=physical) + wfdb.rdrecord(path, physical=False) raw = wfdb.rdrecord(path, physical=False, ignore_skew=True) np.testing.assert_array_equal(raw.d_signal[:, 0], np.arange(1, 9)) +@pytest.mark.parametrize("samples_per_frame", [1, 2]) +@pytest.mark.parametrize("smooth_frames", [False, True]) +def test_legacy_physical_read_uses_nan(tmp_path, samples_per_frame, smooth_frames): + """A physical Record can represent the missing skew tail as NaN.""" + path = _record(tmp_path, samples_per_frame) + read = wfdb.rdrecord(path, smooth_frames=smooth_frames) + values = read.p_signal[:, 0] if smooth_frames else read.e_p_signal[0] + factor = 1 if smooth_frames else samples_per_frame + np.testing.assert_array_equal( + np.isnan(values), [False] * (6 * factor) + [True] * (2 * factor) + ) + window = wfdb.rdrecord(path, sampfrom=4, sampto=7, smooth_frames=smooth_frames) + values = window.p_signal[:, 0] if smooth_frames else window.e_p_signal[0] + np.testing.assert_array_equal( + np.isnan(values), [False] * (2 * factor) + [True] * factor + ) + + def test_multisegment_read_keeps_each_skewed_tail(tmp_path): """Flattening and segment reads preserve the per-segment masks.""" _record(tmp_path, 1) @@ -107,6 +124,16 @@ def test_multisegment_read_keeps_each_skewed_tail(tmp_path): segment.data.signals.values[0].mask, [False] * 6 + [True] * 2, ) + legacy = wfdb.rdrecord(tmp_path / "multi", physical=True) + np.testing.assert_array_equal( + np.isnan(legacy.p_signal[:, 0]), + [False] * 6 + [True] * 2 + [False] * 6 + [True] * 2, + ) + uncombined = wfdb.rdrecord(tmp_path / "multi", physical=True, m2s=False) + for segment in uncombined.segments: + np.testing.assert_array_equal( + np.isnan(segment.p_signal[:, 0]), [False] * 6 + [True] * 2 + ) def test_expanded_skew_marks_every_sample_in_missing_frames(tmp_path):