diff --git a/changelog.d/format8-window.rst b/changelog.d/format8-window.rst new file mode 100644 index 00000000..4b70e603 --- /dev/null +++ b/changelog.d/format8-window.rst @@ -0,0 +1,8 @@ +**Correct partial reads of format-8 signals** + Windowed reads beginning after frame zero now include preceding stored + differences when reconstructing format-8 samples. This fixes incorrect + values in ``read_signals``, ``read_record``, ``rdrecord``, and multi-segment + reads. These windowed values now differ from earlier wfdb-python releases + and the WFDB C ``rdsamp``, which restarts from the header's initial value + when seeking into format 8. A late window must process all preceding bytes; + this uses bounded memory but can take about as long as a full read. diff --git a/src/wfdb/io/_signal.py b/src/wfdb/io/_signal.py index 4ee440d2..5a956750 100644 --- a/src/wfdb/io/_signal.py +++ b/src/wfdb/io/_signal.py @@ -12,6 +12,7 @@ MIN_I32 = -2147483648 CHECKSUM_MODULUS = 65536 +_FORMAT8_PREFIX_CHUNK_BYTES = 8 * 1024 * 1024 # Formats in which all samples align with integer (power-of-two) boundaries ALIGNED_FMTS = ["8", "16", "32", "61", "80", "160"] @@ -1187,6 +1188,39 @@ def _rd_segment( return signals +def _format8_prefix_sums( + file_name, + dir_name, + pn_dir, + byte_offset, + samps_per_frame, + sampfrom, + wfdb_archive, +): + """Sum preceding format-8 differences with bounded memory use.""" + tsamps_per_frame = sum(samps_per_frame) + chunk_frames = max(1, _FORMAT8_PREFIX_CHUNK_BYTES // tsamps_per_frame) + sums = np.zeros(len(samps_per_frame), dtype="int64") + for first in range(0, sampfrom, chunk_frames): + count = min(chunk_frames, sampfrom - first) + differences = _rd_dat_file( + file_name, + dir_name, + pn_dir, + "8", + byte_offset + first * tsamps_per_frame, + count * tsamps_per_frame, + wfdb_archive=wfdb_archive, + ).reshape(count, tsamps_per_frame) + offset = 0 + for channel, width in enumerate(samps_per_frame): + sums[channel] += np.sum( + differences[:, offset : offset + width], dtype="int64" + ) + offset += width + return sums + + def _rd_dat_signals( file_name, dir_name, @@ -1264,6 +1298,23 @@ def _rd_dat_signals( tsamps_per_frame = sum(samps_per_frame) # The signal length to read (per channel) read_len = sampto - sampfrom + # Format 8 stores differences, so a window needs their sum before its + # first frame. The WFDB C rdsamp seeks directly and restarts from initval + # for a later window; that differs from slicing a full read. We retain the + # actual samples by reading the prefix in bounded chunks. + prefix_sums = ( + _format8_prefix_sums( + file_name, + dir_name, + pn_dir, + byte_offset, + samps_per_frame, + sampfrom, + wfdb_archive, + ) + if fmt == "8" and sampfrom > 0 and not no_file + else None + ) # Calculate parameters used to read and process the dat file ( @@ -1355,15 +1406,8 @@ def _rd_dat_signals( elif fmt == "160": sig_data = (sig_data.astype("int32") - 32768).astype("int16") - # For format 8, convert sample differences to absolute samples. Note - # that if sampfrom is not 0, the results will be wrong, since we can't - # know the starting value without reading the entire record from the - # beginning - an inherent limitation of the format, and the use of - # format 8 is discouraged for this reason! However, the following is - # consistent with the behavior of the WFDB library: the initial value - # specified by the header file is used as the starting sample value, - # regardless of where in the record we begin reading. Therefore, the - # following should give the same results as rdsamp. + # For format 8, convert sample differences to absolute samples using the + # initial value and the sum of preceding differences in each channel. if fmt == "8": dif_frames = sig_data.reshape(-1, tsamps_per_frame) abs_frames = np.empty(dif_frames.shape, dtype="int32") @@ -1374,7 +1418,9 @@ def _rd_dat_signals( ch_dif_signal = dif_frames[:, ch_start:ch_end] # Convert to a 1D array of absolute samples ch_abs_signal = ch_dif_signal.cumsum(dtype=abs_frames.dtype) - ch_abs_signal += init_value[ch] + ch_abs_signal += init_value[ch] + ( + 0 if prefix_sums is None else prefix_sums[ch] + ) # Transfer to the output array ch_abs_signal = ch_abs_signal.reshape(ch_dif_signal.shape) abs_frames[:, ch_start:ch_end] = ch_abs_signal diff --git a/tests/test_format8_window.py b/tests/test_format8_window.py new file mode 100644 index 00000000..5ae35276 --- /dev/null +++ b/tests/test_format8_window.py @@ -0,0 +1,133 @@ +"""Windowed format-8 decoding must retain the running initial value.""" + +import shutil + +import numpy as np +import pytest + +import wfdb +from wfdb.io import _signal + + +@pytest.mark.parametrize("start", [1, 2, 127, 477, 498]) +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_window_matches_full_format8_read(start, kind, layout): + """A window uses all earlier stored differences in its first value.""" + path = "sample-data/binformats" + full = wfdb.read_signals(path, kind=kind, layout=layout, channels=[0]) + window = wfdb.read_signals( + path, + kind=kind, + layout=layout, + channels=[0], + start=start, + stop=min(start + 3, 499), + ) + if layout == "expanded": + expected = full.signals.values[0][start : start + 3] + actual = window.signals.values[0] + else: + expected = full.signals.values[start : start + 3, :] + actual = window.signals.values + np.testing.assert_array_equal(actual, expected) + if kind == "digital": + np.testing.assert_array_equal( + np.ma.getmaskarray(actual), np.ma.getmaskarray(expected) + ) + + +@pytest.mark.parametrize("start", [2, 477, 498]) +@pytest.mark.parametrize("physical", [False, True]) +@pytest.mark.parametrize("smooth_frames", [False, True]) +def test_legacy_window_matches_full_format8_read(start, physical, smooth_frames): + """The shared decoder also fixes rdrecord's partial reads.""" + path = "sample-data/binformats" + full = wfdb.rdrecord( + path, channels=[0], physical=physical, smooth_frames=smooth_frames + ) + window = wfdb.rdrecord( + path, + channels=[0], + physical=physical, + smooth_frames=smooth_frames, + sampfrom=start, + sampto=min(start + 3, 499), + ) + field = ( + ("p_signal" if physical else "d_signal") + if smooth_frames + else ("e_p_signal" if physical else "e_d_signal") + ) + expected = getattr(full, field) + actual = getattr(window, field) + if not smooth_frames: + expected = expected[0] + actual = actual[0] + np.testing.assert_array_equal(actual, expected[start : start + 3]) + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_format8_segment_window_matches_full_multi_read(tmp_path, kind, layout): + """A segment's local nonzero start must carry its own difference prefix.""" + shutil.copyfile("sample-data/binformats.d0", tmp_path / "part.dat") + (tmp_path / "part.hea").write_text( + "part 1 200 499\npart.dat 8 200/mV 12 0 -2047 -31143 0 sig 0, fmt 8\n" + ) + (tmp_path / "multi.hea").write_text("multi/2 1 200 998\npart 499\npart 499\n") + full = wfdb.read_signals(tmp_path / "multi", kind=kind, layout=layout) + window = wfdb.read_signals( + tmp_path / "multi", + kind=kind, + layout=layout, + start=499 + 477, + stop=499 + 480, + ) + if layout == "expanded": + expected = full.signals.values[0][976:979] + actual = window.signals.values[0] + else: + expected = full.signals.values[976:979, :] + actual = window.signals.values + np.testing.assert_array_equal(actual, expected) + + +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +@pytest.mark.parametrize("byte_offset", [0, 3]) +@pytest.mark.parametrize("skew", [0, 1]) +def test_interleaved_format8_window_with_multiple_samples_per_frame( + tmp_path, layout, byte_offset, skew, monkeypatch +): + """The decoded prefix is removed in frames across interleaved channels.""" + deltas = np.array([[0, 1, -1], [2, 3, 1]] * 5, dtype="int8") + (tmp_path / "interleaved.dat").write_bytes(bytes(byte_offset) + deltas.tobytes()) + offset = f"+{byte_offset}" if byte_offset else "" + skew_field = f":{skew}" if skew else "" + (tmp_path / "interleaved.hea").write_text( + "interleaved 2 125 10\n" + f"interleaved.dat 8x2{skew_field}{offset} 200/mV 12 0 100 0 0 A\n" + f"interleaved.dat 8{offset} 200/mV 12 0 -50 0 0 B\n" + ) + monkeypatch.setattr(_signal, "_FORMAT8_PREFIX_CHUNK_BYTES", 7) + full = wfdb.read_signals( + tmp_path / "interleaved", kind="digital", layout=layout, stop=8 + ) + window = wfdb.read_signals( + tmp_path / "interleaved", + kind="digital", + layout=layout, + start=4, + stop=7, + ) + if layout == "uniform": + np.testing.assert_array_equal( + window.signals.values, full.signals.values[4:7, :] + ) + else: + np.testing.assert_array_equal( + window.signals.values[0], full.signals.values[0][8:14] + ) + np.testing.assert_array_equal( + window.signals.values[1], full.signals.values[1][4:7] + )