Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/wrsamp-applied-skew.rst
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions src/wfdb/io/convert/wav.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 22 additions & 2 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down
11 changes: 11 additions & 0 deletions tests/io/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
93 changes: 93 additions & 0 deletions tests/test_record.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import datetime
import os
import re
import shutil

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -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
)
Loading