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
12 changes: 12 additions & 0 deletions changelog.d/format8-skew-tail.rst
Original file line number Diff line number Diff line change
@@ -0,0 +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`` 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.
38 changes: 38 additions & 0 deletions src/wfdb/io/_read_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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}"
Expand All @@ -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
)
Expand Down
9 changes: 7 additions & 2 deletions src/wfdb/io/_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
24 changes: 24 additions & 0 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -4118,6 +4118,22 @@ def _rdrecord(

# A single segment record
elif isinstance(record, Record):
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 "
"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,
dir_name=dir_name,
Expand Down Expand Up @@ -4151,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:
Expand Down
172 changes: 172 additions & 0 deletions tests/test_format8_skew_tail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""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()
)


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=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)
(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,
)
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):
"""The shared decoder accounts for samples per frame when filling a tail."""
(tmp_path / "other.dat").write_bytes(np.arange(16, dtype="<i2").tobytes())
(tmp_path / "other.hea").write_text(
"other 1 125 8\nother.dat 16x2:2 200/mV 16 0 0 0 0 I\n"
)
read = wfdb.read_signals(tmp_path / "other", kind="digital", layout="expanded")
np.testing.assert_array_equal(
read.signals.values[0].mask,
[False] * 12 + [True] * 4,
)


def test_selected_channels_keep_their_own_tail_masks(tmp_path):
"""A format-8 tail does not mark another format or move when reordered."""
_record(tmp_path, 1)
(tmp_path / "plain.dat").write_bytes(np.arange(8, dtype="<i2").tobytes())
(tmp_path / "mixed.hea").write_text(
"mixed 2 125 8\n"
"skew1.dat 8:2 200/mV 12 0 0 0 0 I\n"
"plain.dat 16 200/mV 16 0 0 0 0 II\n"
)
read = wfdb.read_signals(
tmp_path / "mixed",
kind="digital",
layout="uniform",
channels=[1, 0],
)
assert not read.signals.values.mask[:, 0].any()
np.testing.assert_array_equal(
read.signals.values.mask[:, 1], [False] * 6 + [True] * 2
)
legacy = wfdb.rdrecord(tmp_path / "mixed", physical=False, channels=[1])
np.testing.assert_array_equal(legacy.d_signal[:, 0], np.arange(8))
Loading