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
2 changes: 2 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,5 @@ jobs:
run: command -v bxb
- name: Compare all four seeds with bxb
run: uv run --python 3.11 pytest -q tests/test_beat_comparison.py::test_matches_wfdb_bxb
- name: Compare variable-layout digital reads with rdsamp
run: uv run --python 3.11 pytest -q tests/test_wfdb_differential.py
6 changes: 6 additions & 0 deletions changelog.d/variable-layout-digital-calibration.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
**Changed:** Modern combined digital reads of variable-layout multi-segment
records now return values rescaled to the layout header's gain and baseline,
using WFDB's round-half-up rule. Missing samples remain masked. Reads warn
when rescaling loses precision and raise if a result cannot fit the requested
digital resolution. Legacy ``rdrecord(..., physical=False, m2s=True)`` still rejects
conflicting calibrations, now with a descriptive ``ValueError``.
65 changes: 65 additions & 0 deletions src/wfdb/io/_multi_read_model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Assemble selected multi-segment samples without a mutable MultiRecord."""

import warnings
from dataclasses import replace

import numpy as np
Expand Down Expand Up @@ -228,6 +229,21 @@ def mark_missing(channel, first, last, missing):
mark_missing(channel, first, last, True)
continue
source = model.values[local] if expanded else model.values[:, local]
if variable and kind == "digital":
source_signal = model.selected_header.signals[local]
source = _rescale_segment_values(
source,
None
if model.mask is None
else model.mask[local]
if expanded
else model.mask[:, local],
source_signal,
reference[channel],
resolution,
wanted,
name,
)
if expanded:
values[channel][first:last] = source
if kind == "digital" and model.mask is not None:
Expand Down Expand Up @@ -343,6 +359,8 @@ def _reference_signals(
names.index(wanted_names[channel])
]
for name in values:
if kind == "digital" and name in ("adc_gain", "baseline", "units"):
continue
item = getattr(entry, name)
if values[name] is None:
values[name] = item
Expand All @@ -366,6 +384,12 @@ def _reference_signals(
for name in mismatched:
values[name] = None
global_mismatches.update(mismatched)
if kind == "digital":
values.update(
adc_gain=signal.adc_gain,
baseline=signal.baseline,
units=signal.units,
)
result.append(
replace(
signal,
Expand All @@ -386,3 +410,44 @@ def _reference_signals(
for signal in result
]
return tuple(result), tuple(sorted(global_mismatches))


def _rescale_segment_values(
source, missing, segment, layout, resolution, channel_name, segment_name
):
"""Map valid segment integers to the layout calibration as WFDB C does."""
scale = layout.adc_gain / segment.adc_gain
if scale == 1 and layout.baseline == segment.baseline:
return source
if scale < 1:
warnings.warn(
f"Loss of precision in channel {channel_name!r} in segment "
f"{segment_name!r}: calibration scale {scale:g} is below 1",
RuntimeWarning,
stacklevel=2,
)
valid = np.ones(source.shape, dtype=bool)
if missing is not None:
valid &= ~np.broadcast_to(missing, source.shape)
converted = np.empty(source.shape, dtype=f"int{resolution}")
converted[~valid] = 0
if not np.any(valid):
return converted
adjusted = np.floor(
source[valid].astype(np.float64) * scale
+ layout.baseline
- scale * segment.baseline
+ 0.5
)
dtype = np.iinfo(converted.dtype)
if (
not np.all(np.isfinite(adjusted))
or np.any(adjusted < dtype.min)
or np.any(adjusted > dtype.max)
):
raise ValueError(
f"Rescaled channel {channel_name!r} in segment {segment_name!r} "
f"does not fit the requested digital resolution {resolution}"
)
converted[valid] = adjusted.astype(converted.dtype)
return converted
10 changes: 8 additions & 2 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -2590,8 +2590,14 @@ def multi_to_single(self, physical, return_res=64, expanded=False):
elif physical:
mismatched_fields.append(field)
else:
raise Exception(
"This variable layout multi-segment record cannot be converted to single segment, in digital format."
raise ValueError(
f"Cannot combine {self.record_name} as digital "
f"values: channel {sig_name!r} has different "
f"{field} across segments "
f"({reference_fields[field][ch]!r} and "
f"{item_ch!r}); use "
'read_record(..., kind="digital") for a '
"calibration-rescaled read."
)
# Remove mismatched signal fields for physical signals
for field in set(mismatched_fields):
Expand Down
33 changes: 33 additions & 0 deletions src/wfdb/io/signal_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,12 @@ def to_physical(self, resolution: int = 64) -> "RecordData":
if self.signals.kind == "physical":
values = _copy_signal_arrays(self.signals, f"float{resolution}")
return _converted_read(self, values, "physical")
if self._model is not None and self._model.source_layout == "variable":
# A layout header declares logical calibration but no storage
# format. Convert masked, rescaled values without asking Record
# for a format that this selected view cannot have.
values = _variable_digital_to_physical(self, resolution)
return _converted_read(self, values, "physical")
record = self._record
_require_calibration(record)
expanded = isinstance(self.signals, ExpandedSignals)
Expand Down Expand Up @@ -853,6 +859,33 @@ def copy_array(values):
return copy_array(signals.values)


def _variable_digital_to_physical(read: RecordData, resolution: int):
"""Convert a combined variable-layout read using its layout calibration."""
channels = read._model.selected_header.signals
if any(signal.adc_gain is None or signal.baseline is None for signal in channels):
raise ValueError("Cannot convert variable-layout values without calibration")
dtype = f"float{resolution}"
if isinstance(read.signals, ExpandedSignals):
return tuple(
np.where(
np.ma.getmaskarray(values),
np.nan,
(np.ma.getdata(values) - signal.baseline) / signal.adc_gain,
).astype(dtype)
for values, signal in zip(read.signals.values, channels)
)
values = read.signals.values
result = np.empty(values.shape, dtype=dtype)
for channel, signal in enumerate(channels):
column = values[:, channel]
result[:, channel] = np.where(
np.ma.getmaskarray(column),
np.nan,
(np.ma.getdata(column) - signal.baseline) / signal.adc_gain,
)
return result


def _require_calibration(record) -> None:
"""Explain which channels cannot be converted with one calibration."""
missing = []
Expand Down
9 changes: 2 additions & 7 deletions tests/spec_conformance.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
{
"spec_repository": "https://github.com/wfdb/wfdb-spec",
"spec_commit": "cff1af24274d3051a0a43d8d415b216b76e6c690",
"known_gaps": {
"multi-segment-variable-rounding": {
"status": "differs",
"issue": 933
}
}
"spec_commit": "134fac813151bb86dfd7947df60a3253c70120c3",
"known_gaps": {}
}
12 changes: 9 additions & 3 deletions tests/test_digital_missing_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,14 +301,20 @@ def test_variable_layout_uses_agreed_format_with_or_without_gaps(
def test_variable_layout_requires_format_for_absent_channels(tmp_path):
"""A short selection cannot infer formats for never-present channels."""
source = "sample-data/multi-segment/s00001/s00001-2896-10-10-00-31"
read = wfdb.read_record(source, stop=10000, kind="digital", layout="uniform")
with pytest.raises(ValueError, match=r"formats for channel\(s\) 2, 3"):
read = wfdb.read_record(
source,
start=2225802,
stop=2225806,
kind="digital",
layout="uniform",
)
with pytest.raises(ValueError, match=r"formats for channel\(s\) 0, 3"):
read.write(tmp_path / "copy")
assert not list(tmp_path.iterdir())
read.write(tmp_path / "copy", formats="80")
header = wfdb.read_header(tmp_path / "copy")
assert [signal.format for signal in header.signals] == ["80"] * 4
assert (tmp_path / "copy.dat").stat().st_size == 10000 * 4
assert (tmp_path / "copy.dat").stat().st_size == 4 * 4


def test_signal_read_write_groups_explicit_channel_formats(tmp_path):
Expand Down
124 changes: 113 additions & 11 deletions tests/test_multi_read_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,18 +219,120 @@ def test_empty_selection_has_clear_error(capsys, kind, layout):


@pytest.mark.parametrize("layout", ["uniform", "expanded"])
def test_mismatched_digital_calibration_names_channel_and_field(layout):
"""A variable-layout digital read identifies its conflicting calibration."""
def test_variable_digital_calibration_matches_layout(layout):
"""Each segment's digital values use the layout calibration."""
path = "sample-data/multi-segment/s00001/s00001-2896-10-10-00-31"
with pytest.raises(
ValueError,
match=r"channel 'MCL1' has different adc_gain across segments "
r"\(26\.0 and 66\.0\)",
read = wfdb.read_record(
path, kind="digital", layout=layout, start=2225802, stop=2225810
)
values = read.signals.values
channel = values[:, 2] if layout == "uniform" else values[2]
np.testing.assert_array_equal(channel, [38, 28, 19, 14, 4, 0, 0, -4])
assert read.metadata.signals[2].adc_gain == 122
assert read.metadata.signals[2].baseline == 0
converted = read.to_physical().signals.values
physical = wfdb.read_record(
path, kind="physical", layout=layout, start=2225802, stop=2225810
).signals.values
converted_channel = converted[:, 2] if layout == "uniform" else converted[2]
physical_channel = physical[:, 2] if layout == "uniform" else physical[2]
np.testing.assert_allclose(converted_channel, physical_channel, atol=1 / 122)


def _variable_calibration_record(tmp_path, *, gain=3, baseline=1):
"""Make two short segments with different gains and one missing value."""
for name, values, segment_gain, segment_baseline in (
("part1", [-1, 1, 2], 2, 0),
("part2", [0, 2, -32768], 6, 1),
):
wfdb.read_record(
path,
wfdb.write_signals(
tmp_path / name,
np.ma.array(
np.array(values, dtype=np.int16).reshape(-1, 1),
mask=np.array([value == -32768 for value in values]).reshape(-1, 1),
),
fs=125,
kind="digital",
layout=layout,
start=2225802,
stop=2225810,
formats="16",
channel_names=("I",),
units=("mV",),
adc_gain=(segment_gain,),
baseline=(segment_baseline,),
)
(tmp_path / "layout.hea").write_text(
f"layout 1 125 0\n~ 0 {gain}({baseline})/mV 16 0 0 0 0 I\n"
)
(tmp_path / "multi.hea").write_text("multi/3 1 125 6\nlayout 0\npart1 3\npart2 3\n")
return tmp_path / "multi"


@pytest.mark.parametrize("layout", ["uniform", "expanded"])
def test_variable_digital_half_up_warning_and_mask(tmp_path, layout):
"""Half steps round up, and rescaling leaves missing samples masked."""
path = _variable_calibration_record(tmp_path)
with pytest.warns(RuntimeWarning, match="Loss of precision.*below 1"):
read = wfdb.read_record(path, kind="digital", layout=layout)
values = read.signals.values
channel = values[:, 0] if layout == "uniform" else values[0]
np.testing.assert_array_equal(channel.compressed(), [0, 3, 4, 1, 2])
np.testing.assert_array_equal(
np.ma.getmaskarray(channel), [False, False, False, False, False, True]
)


def test_variable_digital_gap_and_segment_mask(tmp_path):
"""A missing segment and a missing sample retain separate mask positions."""
path = _variable_calibration_record(tmp_path)
(tmp_path / "multi.hea").write_text(
"multi/4 1 125 8\nlayout 0\npart1 3\n~ 2\npart2 3\n"
)
with pytest.warns(RuntimeWarning, match="Loss of precision"):
read = wfdb.read_record(path, kind="digital", layout="uniform")
np.testing.assert_array_equal(
np.ma.getmaskarray(read.signals.values[:, 0]),
[False, False, False, True, True, False, False, True],
)
np.testing.assert_array_equal(
read.signals.values[:, 0].compressed(), [0, 3, 4, 1, 2]
)


def test_variable_digital_allows_storage_marker_in_combined_view(tmp_path):
"""A combined view has a mask, so a source-format marker can be valid."""
path = _variable_calibration_record(tmp_path, gain=2, baseline=-32767)
with pytest.warns(RuntimeWarning, match="Loss of precision"):
read = wfdb.read_record(path, kind="digital", layout="uniform", resolution=16)
values = read.signals.values[:, 0]
assert values[0] == -32768
assert not np.ma.getmaskarray(values)[0]
assert np.ma.getmaskarray(values)[-1]


def test_variable_digital_rejects_resolution_overflow(tmp_path):
"""Rescaling fails when valid samples cannot fit the requested dtype."""
path = _variable_calibration_record(tmp_path, gain=2, baseline=32768)
with pytest.raises(ValueError, match="requested digital resolution 16"):
wfdb.read_record(path, kind="digital", layout="uniform", resolution=16)


def test_variable_digital_can_exceed_segment_storage_format():
"""A combined view can hold values outside a segment's 8-bit format."""
path = "sample-data/multi-segment/s00001/s00001-2896-10-10-00-31"
read = wfdb.read_record(
path, kind="digital", layout="uniform", start=10005, stop=10017
)
assert np.any(np.abs(read.signals.values[:, 0].compressed()) > 127)


def test_legacy_variable_digital_error_points_to_modern_reader():
"""Legacy flattening still refuses mixed gains with a useful error."""
path = "sample-data/multi-segment/s00001/s00001-2896-10-10-00-31"
with pytest.warns(DeprecationWarning):
with pytest.raises(
ValueError,
match=r"channel 'MCL1'.*adc_gain.*26\.0 and 66\.0.*"
r"read_record\(\.\.\., kind=\"digital\"\)",
):
wfdb.rdrecord(
path, physical=False, m2s=True, sampfrom=2225802, sampto=2225810
)
35 changes: 25 additions & 10 deletions tests/test_read_model_snapshots.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,6 @@
"error": "No selected channels are present in the requested sample range",
"stdout": "",
}
MISMATCHED_DIGITAL_ERROR = {
"error_type": "ValueError",
"error": (
"Cannot combine s00001-2896-10-10-00-31 as digital values: "
"channel 'MCL1' has different adc_gain across segments (26.0 and 66.0)"
),
"stdout": "",
}


def _plain(value):
Expand Down Expand Up @@ -323,9 +315,20 @@ def test_read_matches_v5_17_snapshot(case, kind, layout):
assert snapshot(case, kind, layout) == EMPTY_SELECTION_ERROR
return
if case == "multi_variable_boundary_two" and kind == "digital":
# v5.17.0 used bare Exception with no channel or field details.
# #933 now rescales these segments to the layout calibration.
assert expected["error_type"] == "Exception"
assert snapshot(case, kind, layout) == MISMATCHED_DIGITAL_ERROR
actual = snapshot(case, kind, layout)
assert "error_type" not in actual
return
if case in ("multi_variable_names", "multi_variable_boundary_one") and kind == (
"digital"
):
# Values and source coordinates are unchanged. Channel calibration
# now comes from the layout header, which also changes conversion and
# legacy-projection diagnostics.
actual = snapshot(case, kind, layout)
for field in ("arrays", "provenance", "stdout"):
assert actual[field] == expected[field]
return
_compare_with_old_defaults(snapshot(case, kind, layout), expected, case)

Expand All @@ -334,6 +337,18 @@ def test_read_matches_v5_17_snapshot(case, kind, layout):
def test_read_record_matches_v5_18_read_signals(case, kind, layout):
"""The 6.0 reader retains 5.18.0 values, masks, and metadata."""
expected = json.loads(V5_18_FIXTURE.read_text())[f"{case}:{kind}:{layout}"]
if case == "multi_variable_boundary_two" and kind == "digital":
# The released reader rejected this calibration mismatch.
assert expected["error_type"] == "ValueError"
assert "error_type" not in snapshot(case, kind, layout)
return
if case in ("multi_variable_names", "multi_variable_boundary_one") and kind == (
"digital"
):
actual = snapshot(case, kind, layout)
for field in ("arrays", "provenance", "stdout"):
assert actual[field] == expected[field]
return
if case == "single_format_24":
# #923 preserves the second # in this header's comment. The release
# snapshot predates that intended change to metadata and provenance.
Expand Down
Loading
Loading