From 3612391775c02c64a8da51e99087e4b30b816483 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 20:52:58 -0500 Subject: [PATCH] Do not apply skew twice to rewritten records rdrecord aligns skewed signals, but the record keeps its skew field, so Record.wrsamp wrote aligned samples with a header that still gave the skew. Reading the new record shifted those signals a second time. Remember the skew applied when reading, and leave it out of the header when writing the samples. The skew attribute is not changed, a value assigned to it after reading is written, and wrheader on its own still describes the original signal files. wfdb_to_wav had the same problem with write_header=True. --- changelog.d/wrsamp-applied-skew.rst | 2 + src/wfdb/io/convert/wav.py | 2 + src/wfdb/io/record.py | 24 +++++++- tests/io/test_convert.py | 11 ++++ tests/test_record.py | 93 +++++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 changelog.d/wrsamp-applied-skew.rst diff --git a/changelog.d/wrsamp-applied-skew.rst b/changelog.d/wrsamp-applied-skew.rst new file mode 100644 index 00000000..a0f3f302 --- /dev/null +++ b/changelog.d/wrsamp-applied-skew.rst @@ -0,0 +1,2 @@ +**Do not apply skew twice to rewritten records** + ``Record.wrsamp`` no longer writes the skew of a record whose signals were read with the skew applied. The samples were written already aligned but the header kept the skew, so reading the new record shifted those signals a second time. ``wfdb_to_wav`` with ``write_header=True`` had the same problem. The ``skew`` attribute is unchanged, and records read with ``ignore_skew=True`` are still written with their skew. diff --git a/src/wfdb/io/convert/wav.py b/src/wfdb/io/convert/wav.py index 6455dddb..42e90e35 100644 --- a/src/wfdb/io/convert/wav.py +++ b/src/wfdb/io/convert/wav.py @@ -137,6 +137,8 @@ def wfdb_to_wav( record.block_size = record.n_sig * [0] record.fmt = record.n_sig * ["16"] record.samps_per_frame = record.n_sig * [1] + # The samples written are already aligned + record.skew = None record.init_value = sig_data[0][: record.n_sig].tolist() record.byte_offset = record.n_sig * [44] # Write the header file diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 851e1ed1..535ad94a 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -832,6 +832,8 @@ def __init__( self.init_value = init_value self.checksum = checksum self.block_size = block_size + # The skew already applied to the signals when they were read, if any + self._applied_skew = None # Equal comparison operator for objects of this type def __eq__(self, other, verbose=False): @@ -850,8 +852,9 @@ def __eq__(self, other, verbose=False): Determines if the objects are equal (True) or not equal (False). """ - att1 = self.__dict__ - att2 = other.__dict__ + # How the signals were read does not affect whether records are equal + att1 = {k: v for k, v in self.__dict__.items() if k != "_applied_skew"} + att2 = {k: v for k, v in other.__dict__.items() if k != "_applied_skew"} if set(att1.keys()) != set(att2.keys()): if verbose: @@ -888,6 +891,12 @@ def __eq__(self, other, verbose=False): def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): """Write a WFDB header file and any associated dat files from this object. + If the signals were read with their skew applied, they are already + aligned, so the header is written without skew. Read the record with + `ignore_skew=True` to write the signals and their skew as stored. The + `skew` attribute is not changed, and a value assigned to it after + reading is written to the header. + Parameters ---------- expanded : bool, optional @@ -915,6 +924,13 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): self.e_d_signal = self.adc(expanded=True) converted = "e_d_signal" + # Signals that are already aligned must not be skewed again when read + # (a record pickled by an older version does not have _applied_skew) + skew = self.skew + applied_skew = getattr(self, "_applied_skew", None) + if applied_skew is not None and skew is not None and list(skew) == applied_skew: + self.skew = None + try: # A record whose signals have no files, such as the layout header # of a variable layout multi-segment record, has no samples: @@ -958,6 +974,7 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): expanded=expanded, write_dir=write_dir, wfdb_archive=archive ) finally: + self.skew = skew if converted: setattr(self, converted, None) @@ -2509,6 +2526,9 @@ def _rdrecord( # Perform dac to get physical signal record.dac(expanded=True, return_res=return_res, inplace=True) + if not ignore_skew and record.skew is not None and any(record.skew): + record._applied_skew = list(record.skew) + # A multi segment record else: # Strategy: diff --git a/tests/io/test_convert.py b/tests/io/test_convert.py index 9d0ecbd9..607968c9 100644 --- a/tests/io/test_convert.py +++ b/tests/io/test_convert.py @@ -458,6 +458,17 @@ def test_sampfrom_sampto(self, tmp_path, monkeypatch): np.testing.assert_array_equal(self.read_wav("100.wav", 2), expected) assert rdheader("100").init_value == expected[0].tolist() + def test_write_header_skew(self, tmp_path, monkeypatch): + """The header does not repeat a skew already applied to the samples.""" + record_path = os.path.abspath("sample-data/100skew") + monkeypatch.chdir(tmp_path) + wfdb_to_wav(record_path, sampto=1000, write_header=True) + + expected = rdrecord(record_path, sampto=1000) + record = rdrecord("100skew") + assert not any(record.skew) + np.testing.assert_array_equal(record.p_signal, expected.p_signal) + def test_channels(self, tmp_path): """Only the selected channels are written.""" wav_file = str(tmp_path / "out.wav") diff --git a/tests/test_record.py b/tests/test_record.py index 06d93674..a0580ec9 100644 --- a/tests/test_record.py +++ b/tests/test_record.py @@ -1,6 +1,7 @@ import datetime import os import re +import shutil import numpy as np import pandas as pd @@ -1946,3 +1947,95 @@ def test_invalid_base_time_is_ignored_with_a_warning(tmp_path, time_and_date, wa assert record.sig_len == 10 if time_and_date.endswith("25/12/2020"): assert record.base_date == datetime.date(2020, 12, 25) + + +class TestWriteAppliedSkew: + """Writing a record whose signals were read with their skew applied.""" + + @staticmethod + def read(path, **kwargs): + return wfdb.rdrecord(path, physical=False, smooth_frames=False, **kwargs) + + @staticmethod + def assert_signals_equal(record1, record2): + assert len(record1.e_d_signal) == len(record2.e_d_signal) + for sig1, sig2 in zip(record1.e_d_signal, record2.e_d_signal): + np.testing.assert_array_equal(sig1, sig2) + + @pytest.mark.parametrize( + "record_name", ["100skew", "test01_00s_skew", "test01_00s_skewframe"] + ) + @pytest.mark.parametrize( + "kwargs", [{}, {"sampfrom": 10, "sampto": 200}, {"channels": [1]}] + ) + def test_not_applied_twice(self, tmp_path, record_name, kwargs): + """The samples read back match those written, and skew is kept in memory.""" + source = f"sample-data/{record_name}" + record = self.read(source, **kwargs) + skew = list(record.skew) + record.wrsamp(expanded=True, write_dir=str(tmp_path)) + + assert record.skew == skew + written = str(tmp_path / record_name) + assert not any(wfdb.rdheader(written).skew) + self.assert_signals_equal(record, self.read(written)) + + def test_uniform_physical(self, tmp_path): + """A default read (physical, smoothed) is also written without skew.""" + record = wfdb.rdrecord("sample-data/100skew", sampto=1000) + record.wrsamp(write_dir=str(tmp_path)) + written = wfdb.rdrecord(str(tmp_path / "100skew"), physical=False) + expected = wfdb.rdrecord("sample-data/100skew", sampto=1000, physical=False) + np.testing.assert_array_equal(written.d_signal, expected.d_signal) + + def test_ignore_skew_keeps_skew(self, tmp_path): + """Signals read without applying the skew are written with it.""" + source = "sample-data/100skew" + self.read(source, ignore_skew=True).wrsamp( + expanded=True, write_dir=str(tmp_path) + ) + written = str(tmp_path / "100skew") + assert wfdb.rdheader(written).skew == wfdb.rdheader(source).skew + self.assert_signals_equal(self.read(source), self.read(written)) + + def test_assigned_skew_is_written(self, tmp_path): + """A skew assigned after reading is written to the header.""" + record = self.read("sample-data/100skew", sampto=100) + record.skew = [1, None] + record.wrsamp(expanded=True, write_dir=str(tmp_path)) + assert wfdb.rdheader(str(tmp_path / "100skew")).skew == [1, None] + + def test_wrheader_keeps_skew(self, tmp_path): + """Writing only the header still describes the original signal file.""" + record = self.read("sample-data/100skew") + record.wrheader(write_dir=str(tmp_path)) + assert wfdb.rdheader(str(tmp_path / "100skew")).skew == record.skew + + def test_equal_to_record_read_without_marker(self): + """How the signals were read does not affect equality.""" + record1 = self.read("sample-data/100skew", sampto=100) + record2 = self.read("sample-data/100skew", sampto=100) + record2._applied_skew = None + assert record1 == record2 + + def test_multi_segment(self, tmp_path): + """Skewed segments of a multi-segment record are not skewed again.""" + source_dir = tmp_path / "source" + source_dir.mkdir() + for file_name in ["test01_00s_skew.hea", "test01_00s.dat"]: + shutil.copy(f"sample-data/{file_name}", source_dir) + segment = wfdb.rdheader("sample-data/test01_00s_skew") + (source_dir / "multi.hea").write_text( + f"multi/1 {segment.n_sig} {segment.fs:g} {segment.sig_len}\n" + f"test01_00s_skew {segment.sig_len}\n" + ) + record = wfdb.rdrecord(str(source_dir / "multi"), physical=False, m2s=False) + + out_dir = tmp_path / "out" + out_dir.mkdir() + record.wrsamp(write_dir=str(out_dir)) + + written = wfdb.rdrecord(str(out_dir / "multi"), physical=False, m2s=False) + np.testing.assert_array_equal( + written.segments[0].d_signal, record.segments[0].d_signal + )