Skip to content

Commit 72fec54

Browse files
authored
Do not apply skew twice to rewritten records (#677)
`rdrecord` aligns skewed signals, but the record keeps its `skew` field. `Record.wrsamp` then wrote the aligned samples with a header that still gave the skew, so reading the new record shifted those signals a second time, with no error: ```python record = wfdb.rdrecord("sample-data/100skew", physical=False) record.wrsamp(write_dir="out") written = wfdb.rdrecord("out/100skew", physical=False) np.array_equal(record.d_signal, written.d_signal) # False on main, True here ``` This is the first step towards a reliable read and write round trip (#484, #500). Of the 75 single-segment records in `sample-data`, the 4 with skew were written incorrectly. All 4 now read back with the same samples. The record now remembers the skew applied when it was read, and `Record.wrsamp` leaves it out of the header. - `record.skew` does not change, so code that reads it after `rdrecord` is not affected. - A value assigned to `record.skew` after reading is written to the header. - Records read with `ignore_skew=True` are still written with their skew, and their signal files are byte-identical to the originals. - `wrheader` on its own still writes the skew, since that header may describe the original signal files. - The marker is ignored by `Record.__eq__`. - Skewed segments of a multi-segment record are handled through the same path. `wfdb_to_wav` with `write_header=True` had the same problem, and now writes no skew. Testing: - New `TestWriteAppliedSkew`, covering full and partial reads, channel selection, physical and digital reads, `ignore_skew`, an assigned skew, `wrheader`, equality and multi-segment records, and `test_write_header_skew` for `wfdb_to_wav`. The tests for the bug fail on `main`. - `uv run pytest -m "not network" -W error` (582 passed), the network tests in `tests/test_record.py` (14 passed), `ruff format --check`, `ruff check` and the docs build with `-W` pass. Changelog entry added in `changelog.d/`. Refs #484, #500 <sub>@tompollard 🟥 red 🐳 whale · quince</sub>
2 parents 3547521 + 3612391 commit 72fec54

5 files changed

Lines changed: 130 additions & 2 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
**Do not apply skew twice to rewritten records**
2+
``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.

‎src/wfdb/io/convert/wav.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,8 @@ def wfdb_to_wav(
137137
record.block_size = record.n_sig * [0]
138138
record.fmt = record.n_sig * ["16"]
139139
record.samps_per_frame = record.n_sig * [1]
140+
# The samples written are already aligned
141+
record.skew = None
140142
record.init_value = sig_data[0][: record.n_sig].tolist()
141143
record.byte_offset = record.n_sig * [44]
142144
# Write the header file

‎src/wfdb/io/record.py‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -832,6 +832,8 @@ def __init__(
832832
self.init_value = init_value
833833
self.checksum = checksum
834834
self.block_size = block_size
835+
# The skew already applied to the signals when they were read, if any
836+
self._applied_skew = None
835837

836838
# Equal comparison operator for objects of this type
837839
def __eq__(self, other, verbose=False):
@@ -850,8 +852,9 @@ def __eq__(self, other, verbose=False):
850852
Determines if the objects are equal (True) or not equal (False).
851853
852854
"""
853-
att1 = self.__dict__
854-
att2 = other.__dict__
855+
# How the signals were read does not affect whether records are equal
856+
att1 = {k: v for k, v in self.__dict__.items() if k != "_applied_skew"}
857+
att2 = {k: v for k, v in other.__dict__.items() if k != "_applied_skew"}
855858

856859
if set(att1.keys()) != set(att2.keys()):
857860
if verbose:
@@ -888,6 +891,12 @@ def __eq__(self, other, verbose=False):
888891
def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None):
889892
"""Write a WFDB header file and any associated dat files from this object.
890893
894+
If the signals were read with their skew applied, they are already
895+
aligned, so the header is written without skew. Read the record with
896+
`ignore_skew=True` to write the signals and their skew as stored. The
897+
`skew` attribute is not changed, and a value assigned to it after
898+
reading is written to the header.
899+
891900
Parameters
892901
----------
893902
expanded : bool, optional
@@ -915,6 +924,13 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None):
915924
self.e_d_signal = self.adc(expanded=True)
916925
converted = "e_d_signal"
917926

927+
# Signals that are already aligned must not be skewed again when read
928+
# (a record pickled by an older version does not have _applied_skew)
929+
skew = self.skew
930+
applied_skew = getattr(self, "_applied_skew", None)
931+
if applied_skew is not None and skew is not None and list(skew) == applied_skew:
932+
self.skew = None
933+
918934
try:
919935
# A record whose signals have no files, such as the layout header
920936
# of a variable layout multi-segment record, has no samples:
@@ -958,6 +974,7 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None):
958974
expanded=expanded, write_dir=write_dir, wfdb_archive=archive
959975
)
960976
finally:
977+
self.skew = skew
961978
if converted:
962979
setattr(self, converted, None)
963980

@@ -2509,6 +2526,9 @@ def _rdrecord(
25092526
# Perform dac to get physical signal
25102527
record.dac(expanded=True, return_res=return_res, inplace=True)
25112528

2529+
if not ignore_skew and record.skew is not None and any(record.skew):
2530+
record._applied_skew = list(record.skew)
2531+
25122532
# A multi segment record
25132533
else:
25142534
# Strategy:

‎tests/io/test_convert.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,17 @@ def test_sampfrom_sampto(self, tmp_path, monkeypatch):
458458
np.testing.assert_array_equal(self.read_wav("100.wav", 2), expected)
459459
assert rdheader("100").init_value == expected[0].tolist()
460460

461+
def test_write_header_skew(self, tmp_path, monkeypatch):
462+
"""The header does not repeat a skew already applied to the samples."""
463+
record_path = os.path.abspath("sample-data/100skew")
464+
monkeypatch.chdir(tmp_path)
465+
wfdb_to_wav(record_path, sampto=1000, write_header=True)
466+
467+
expected = rdrecord(record_path, sampto=1000)
468+
record = rdrecord("100skew")
469+
assert not any(record.skew)
470+
np.testing.assert_array_equal(record.p_signal, expected.p_signal)
471+
461472
def test_channels(self, tmp_path):
462473
"""Only the selected channels are written."""
463474
wav_file = str(tmp_path / "out.wav")

‎tests/test_record.py‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import datetime
22
import os
33
import re
4+
import shutil
45

56
import numpy as np
67
import pandas as pd
@@ -1946,3 +1947,95 @@ def test_invalid_base_time_is_ignored_with_a_warning(tmp_path, time_and_date, wa
19461947
assert record.sig_len == 10
19471948
if time_and_date.endswith("25/12/2020"):
19481949
assert record.base_date == datetime.date(2020, 12, 25)
1950+
1951+
1952+
class TestWriteAppliedSkew:
1953+
"""Writing a record whose signals were read with their skew applied."""
1954+
1955+
@staticmethod
1956+
def read(path, **kwargs):
1957+
return wfdb.rdrecord(path, physical=False, smooth_frames=False, **kwargs)
1958+
1959+
@staticmethod
1960+
def assert_signals_equal(record1, record2):
1961+
assert len(record1.e_d_signal) == len(record2.e_d_signal)
1962+
for sig1, sig2 in zip(record1.e_d_signal, record2.e_d_signal):
1963+
np.testing.assert_array_equal(sig1, sig2)
1964+
1965+
@pytest.mark.parametrize(
1966+
"record_name", ["100skew", "test01_00s_skew", "test01_00s_skewframe"]
1967+
)
1968+
@pytest.mark.parametrize(
1969+
"kwargs", [{}, {"sampfrom": 10, "sampto": 200}, {"channels": [1]}]
1970+
)
1971+
def test_not_applied_twice(self, tmp_path, record_name, kwargs):
1972+
"""The samples read back match those written, and skew is kept in memory."""
1973+
source = f"sample-data/{record_name}"
1974+
record = self.read(source, **kwargs)
1975+
skew = list(record.skew)
1976+
record.wrsamp(expanded=True, write_dir=str(tmp_path))
1977+
1978+
assert record.skew == skew
1979+
written = str(tmp_path / record_name)
1980+
assert not any(wfdb.rdheader(written).skew)
1981+
self.assert_signals_equal(record, self.read(written))
1982+
1983+
def test_uniform_physical(self, tmp_path):
1984+
"""A default read (physical, smoothed) is also written without skew."""
1985+
record = wfdb.rdrecord("sample-data/100skew", sampto=1000)
1986+
record.wrsamp(write_dir=str(tmp_path))
1987+
written = wfdb.rdrecord(str(tmp_path / "100skew"), physical=False)
1988+
expected = wfdb.rdrecord("sample-data/100skew", sampto=1000, physical=False)
1989+
np.testing.assert_array_equal(written.d_signal, expected.d_signal)
1990+
1991+
def test_ignore_skew_keeps_skew(self, tmp_path):
1992+
"""Signals read without applying the skew are written with it."""
1993+
source = "sample-data/100skew"
1994+
self.read(source, ignore_skew=True).wrsamp(
1995+
expanded=True, write_dir=str(tmp_path)
1996+
)
1997+
written = str(tmp_path / "100skew")
1998+
assert wfdb.rdheader(written).skew == wfdb.rdheader(source).skew
1999+
self.assert_signals_equal(self.read(source), self.read(written))
2000+
2001+
def test_assigned_skew_is_written(self, tmp_path):
2002+
"""A skew assigned after reading is written to the header."""
2003+
record = self.read("sample-data/100skew", sampto=100)
2004+
record.skew = [1, None]
2005+
record.wrsamp(expanded=True, write_dir=str(tmp_path))
2006+
assert wfdb.rdheader(str(tmp_path / "100skew")).skew == [1, None]
2007+
2008+
def test_wrheader_keeps_skew(self, tmp_path):
2009+
"""Writing only the header still describes the original signal file."""
2010+
record = self.read("sample-data/100skew")
2011+
record.wrheader(write_dir=str(tmp_path))
2012+
assert wfdb.rdheader(str(tmp_path / "100skew")).skew == record.skew
2013+
2014+
def test_equal_to_record_read_without_marker(self):
2015+
"""How the signals were read does not affect equality."""
2016+
record1 = self.read("sample-data/100skew", sampto=100)
2017+
record2 = self.read("sample-data/100skew", sampto=100)
2018+
record2._applied_skew = None
2019+
assert record1 == record2
2020+
2021+
def test_multi_segment(self, tmp_path):
2022+
"""Skewed segments of a multi-segment record are not skewed again."""
2023+
source_dir = tmp_path / "source"
2024+
source_dir.mkdir()
2025+
for file_name in ["test01_00s_skew.hea", "test01_00s.dat"]:
2026+
shutil.copy(f"sample-data/{file_name}", source_dir)
2027+
segment = wfdb.rdheader("sample-data/test01_00s_skew")
2028+
(source_dir / "multi.hea").write_text(
2029+
f"multi/1 {segment.n_sig} {segment.fs:g} {segment.sig_len}\n"
2030+
f"test01_00s_skew {segment.sig_len}\n"
2031+
)
2032+
record = wfdb.rdrecord(str(source_dir / "multi"), physical=False, m2s=False)
2033+
2034+
out_dir = tmp_path / "out"
2035+
out_dir.mkdir()
2036+
record.wrsamp(write_dir=str(out_dir))
2037+
2038+
written = wfdb.rdrecord(str(out_dir / "multi"), physical=False, m2s=False)
2039+
np.testing.assert_array_equal(
2040+
written.segments[0].d_signal, record.segments[0].d_signal
2041+
)

0 commit comments

Comments
 (0)