Skip to content
Open
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
6 changes: 6 additions & 0 deletions changelog.d/read-format0-signals.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
**Read missing format 0 signals**
``read_record`` and ``read_segments`` now return fully masked digital
values or ``NaN`` physical values for format 0 signals. Legacy physical
reads also return ``NaN``; legacy digital reads raise a clear ``ValueError``
pointing to ``read_record(..., kind="digital")``. Other signals in the
record remain readable.
31 changes: 27 additions & 4 deletions src/wfdb/io/_read_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,24 @@ def _dac_values(values, formats, gains, baselines, expanded, resolution):
if expanded:
converted = []
for array, fmt, gain, baseline in zip(values, formats, gains, baselines):
if fmt == "0":
converted.append(np.full(array.shape, np.nan, dtype=dtype))
continue
missing = array == _signal._digi_nan(fmt)
physical = array.astype(dtype, copy=False)
np.subtract(physical, baseline, physical)
np.divide(physical, gain, physical)
physical[missing] = np.nan
converted.append(physical)
return converted
missing = values == _signal._digi_nan(formats)
if "0" in formats:
missing = np.zeros(values.shape, dtype=bool)
for index, fmt in enumerate(formats):
missing[:, index] = (
True if fmt == "0" else values[:, index] == _signal._digi_nan(fmt)
)
else:
missing = values == _signal._digi_nan(formats)
converted = values.astype(dtype, copy=False)
np.subtract(converted, baselines, converted)
np.divide(converted, gains, converted)
Expand All @@ -225,14 +235,27 @@ def _digital_mask(values, channels, expanded):
if expanded:
masks = None
for index, (array, signal) in enumerate(zip(values, channels)):
missing = array == _signal._digi_nan(signal.fmt)
missing = (
np.ones(array.shape, dtype=bool)
if signal.fmt == "0"
else array == _signal._digi_nan(signal.fmt)
)
if np.any(missing):
if masks is None:
masks = [np.ma.nomask] * len(values)
masks[index] = missing
return None if masks is None else tuple(masks)
markers = [_signal._digi_nan(signal.fmt) for signal in channels]
masks = values == (markers[0] if len(set(markers)) == 1 else markers)
if any(signal.fmt == "0" for signal in channels):
masks = np.zeros(values.shape, dtype=bool)
for index, signal in enumerate(channels):
masks[:, index] = (
True
if signal.fmt == "0"
else values[:, index] == _signal._digi_nan(signal.fmt)
)
else:
markers = [_signal._digi_nan(signal.fmt) for signal in channels]
masks = values == (markers[0] if len(set(markers)) == 1 else markers)
return masks if np.any(masks) else None


Expand Down
7 changes: 7 additions & 0 deletions src/wfdb/io/_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
# Digital value used to represent a missing/invalid sample, in each of the
# WFDB dat formats.
INVALID_SAMPLE_VALUE = {
"0": None,
"80": -(2**7),
"508": -(2**7),
"310": -(2**9),
Expand Down Expand Up @@ -1162,6 +1163,12 @@ def _rd_segment(
signals = [None] * len(channels)

for fn in w_file_name:
if w_fmt[fn] == "0":
for channel in w_channel[fn]:
output = channels.index(channel)
count = (sampto - sampfrom) * samps_per_frame[channel]
signals[output] = np.zeros(count, dtype=f"int{return_res}")
continue
# Get the list of all signals contained in the dat file
datsignals = _rd_dat_signals(
file_name=fn,
Expand Down
9 changes: 9 additions & 0 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -4046,6 +4046,15 @@ def _rdrecord(

# A single segment record
elif isinstance(record, Record):
if not physical:
for channel in channels:
if record.fmt[channel] == "0":
raise ValueError(
f"Signal {record.sig_name[channel]!r} (channel {channel}) "
"has format 0 and cannot be represented in a digital "
'legacy Record; use read_record(..., kind="digital") '
"for masked values."
)
markerless_tails = (
_signal._format8_missing_skew_tails(
record.file_name,
Expand Down
6 changes: 1 addition & 5 deletions tests/spec_conformance.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
{
"spec_repository": "https://github.com/wfdb/wfdb-spec",
"spec_commit": "8170251a5f8d2379a0f0a687ab89e224a032e5ab",
"spec_commit": "ad32e3231a55cf9c8b8fb4da68f64d198bf4884d",
"known_gaps": {
"format0": {
"status": "unsupported",
"issue": 935
},
"header-partial-signal-fields": {
"status": "differs",
"issue": 937
Expand Down
75 changes: 75 additions & 0 deletions tests/test_format0_reads.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Format 0 declares a signal without a data file or valid samples."""

import numpy as np
import pytest

import wfdb


def _make_record(tmp_path, *, mixed=False):
"""Write a format 0 header, optionally with an ordinary signal beside it."""
n_sig = 2 if mixed else 1
lines = [f"null {n_sig} 250 4", "~ 0 200/mV 12 0 0 0 0 absent"]
if mixed:
(tmp_path / "present.dat").write_bytes(
np.array([1, 2, 3, 4], dtype="<i2").tobytes()
)
lines.append("present.dat 16 200/mV 12 0 1 10 0 present")
(tmp_path / "null.hea").write_text("\n".join(lines) + "\n")
assert not (tmp_path / "~").exists()
return tmp_path / "null"


@pytest.mark.parametrize("layout", ["uniform", "expanded"])
@pytest.mark.parametrize("kind", ["digital", "physical"])
@pytest.mark.parametrize("mixed", [False, True])
def test_modern_format0_reads(tmp_path, layout, kind, mixed):
"""The null channel is missing while a real channel stays readable."""
path = _make_record(tmp_path, mixed=mixed)
record = wfdb.read_record(path, kind=kind, layout=layout, start=1, stop=3)
values = record.signals.values
null = values[:, 0] if layout == "uniform" else values[0]
if kind == "digital":
np.testing.assert_array_equal(np.ma.getmaskarray(null), [True, True])
else:
assert np.isnan(null).all()
if mixed:
present = values[:, 1] if layout == "uniform" else values[1]
expected = [2, 3] if kind == "digital" else [2 / 200, 3 / 200]
np.testing.assert_array_equal(present, expected)
assert not (tmp_path / "~").exists()


@pytest.mark.parametrize("smooth_frames", [False, True])
@pytest.mark.parametrize("mixed", [False, True])
def test_legacy_format0_read(tmp_path, smooth_frames, mixed):
"""Physical legacy reads yield NaN; digital reads name the null signal."""
path = _make_record(tmp_path, mixed=mixed)
physical = wfdb.rdrecord(path, physical=True, smooth_frames=smooth_frames)
null = physical.p_signal[:, 0] if smooth_frames else physical.e_p_signal[0]
assert np.isnan(null).all()
if mixed:
present = physical.p_signal[:, 1] if smooth_frames else physical.e_p_signal[1]
np.testing.assert_array_equal(present, np.array([1, 2, 3, 4]) / 200)
with pytest.raises(ValueError, match='absent.*read_record.*kind="digital"'):
wfdb.rdrecord(path, physical=False, smooth_frames=smooth_frames)


@pytest.mark.parametrize("kind", ["digital", "physical"])
@pytest.mark.parametrize("layout", ["uniform", "expanded"])
def test_format0_in_segmented_reads(tmp_path, kind, layout):
"""Combined and separate segment reads keep the null channel missing."""
_make_record(tmp_path, mixed=True)
(tmp_path / "multi.hea").write_text("multi/1 2 250 4\nnull 4\n")
combined = wfdb.read_record(tmp_path / "multi", kind=kind, layout=layout)
parts = wfdb.read_segments(tmp_path / "multi", kind=kind, layout=layout)
for record in (combined, parts.segments[0].data):
values = record.signals.values
null = values[:, 0] if layout == "uniform" else values[0]
present = values[:, 1] if layout == "uniform" else values[1]
if kind == "digital":
assert np.ma.getmaskarray(null).all()
np.testing.assert_array_equal(present, [1, 2, 3, 4])
else:
assert np.isnan(null).all()
np.testing.assert_array_equal(present, np.array([1, 2, 3, 4]) / 200)
Loading