From e03cf0ab120664281e5edb7679950cde2e0bd5f9 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sat, 5 Dec 2026 22:44:14 -0500 Subject: [PATCH] Rescale variable-layout digital reads to layout calibration --- .github/workflows/test.yml | 2 + .../variable-layout-digital-calibration.rst | 6 + src/wfdb/io/_multi_read_model.py | 65 +++++++++ src/wfdb/io/record.py | 10 +- src/wfdb/io/signal_values.py | 33 +++++ tests/spec_conformance.json | 9 +- tests/test_digital_missing_mask.py | 12 +- tests/test_multi_read_model.py | 124 ++++++++++++++++-- tests/test_read_model_snapshots.py | 35 +++-- tests/test_read_segments.py | 8 +- tests/test_wfdb_differential.py | 34 +++++ 11 files changed, 303 insertions(+), 35 deletions(-) create mode 100644 changelog.d/variable-layout-digital-calibration.rst create mode 100644 tests/test_wfdb_differential.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 559a89bd..70d20d8e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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 diff --git a/changelog.d/variable-layout-digital-calibration.rst b/changelog.d/variable-layout-digital-calibration.rst new file mode 100644 index 00000000..8bac16ab --- /dev/null +++ b/changelog.d/variable-layout-digital-calibration.rst @@ -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``. diff --git a/src/wfdb/io/_multi_read_model.py b/src/wfdb/io/_multi_read_model.py index cfc86bb1..944fe708 100644 --- a/src/wfdb/io/_multi_read_model.py +++ b/src/wfdb/io/_multi_read_model.py @@ -1,5 +1,6 @@ """Assemble selected multi-segment samples without a mutable MultiRecord.""" +import warnings from dataclasses import replace import numpy as np @@ -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: @@ -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 @@ -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, @@ -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 diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index e6596af9..00587f42 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -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): diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index d79343b9..4cb4db29 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -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) @@ -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 = [] diff --git a/tests/spec_conformance.json b/tests/spec_conformance.json index 1fec7423..8e8472f0 100644 --- a/tests/spec_conformance.json +++ b/tests/spec_conformance.json @@ -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": {} } diff --git a/tests/test_digital_missing_mask.py b/tests/test_digital_missing_mask.py index 9c8c943e..7edfb17f 100644 --- a/tests/test_digital_missing_mask.py +++ b/tests/test_digital_missing_mask.py @@ -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): diff --git a/tests/test_multi_read_model.py b/tests/test_multi_read_model.py index e3c63712..2513af5e 100644 --- a/tests/test_multi_read_model.py +++ b/tests/test_multi_read_model.py @@ -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 + ) diff --git a/tests/test_read_model_snapshots.py b/tests/test_read_model_snapshots.py index e6fcbfba..46aaeb35 100644 --- a/tests/test_read_model_snapshots.py +++ b/tests/test_read_model_snapshots.py @@ -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): @@ -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) @@ -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. diff --git a/tests/test_read_segments.py b/tests/test_read_segments.py index be683194..9d86e93d 100644 --- a/tests/test_read_segments.py +++ b/tests/test_read_segments.py @@ -267,14 +267,18 @@ def test_mismatched_calibration_does_not_block_uncombined_digital_read(layout): "start": 2225802, "stop": 2225810, } - with pytest.raises(ValueError, match="different adc_gain"): - wfdb.read_record(path, **options) + combined = wfdb.read_record(path, **options) read = wfdb.read_segments(path, **options) assert len(read.segments) == 2 assert all(part.data is not None for part in read.segments) assert read.segments[0].data.source_header.record_name != ( read.segments[1].data.source_header.record_name ) + assert combined.metadata.signals[2].adc_gain == 122 + assert [part.data.metadata.signals[1].adc_gain for part in read.segments] == [ + 26, + 66, + ] def test_single_segment_source_and_invalid_names_are_clear(): diff --git a/tests/test_wfdb_differential.py b/tests/test_wfdb_differential.py new file mode 100644 index 00000000..b71fddf9 --- /dev/null +++ b/tests/test_wfdb_differential.py @@ -0,0 +1,34 @@ +"""Compare selected reads with the WFDB Software Package.""" + +import io +import shutil +import subprocess + +import numpy as np +import pytest + +import wfdb + + +def test_variable_layout_digital_matches_rdsamp(): + """A boundary window uses WFDB C's digital calibration and rounding.""" + if shutil.which("rdsamp") is None: + pytest.skip("rdsamp is not installed") + path = "sample-data/multi-segment/s00001/s00001-2896-10-10-00-31" + first, last = 2225802, 2225810 + result = subprocess.run( + ["rdsamp", "-r", path, "-f", f"s{first}", "-t", f"s{last}"], + capture_output=True, + text=True, + check=True, + ) + reference = np.loadtxt(io.StringIO(result.stdout), dtype=np.int64) + np.testing.assert_array_equal(reference[:, 0], np.arange(first, last)) + + read = wfdb.read_record( + path, kind="digital", layout="uniform", start=first, stop=last + ) + values = read.signals.values + mask = np.ma.getmaskarray(values) + np.testing.assert_array_equal(mask, reference[:, 1:] == -32768) + np.testing.assert_array_equal(np.ma.getdata(values)[~mask], reference[:, 1:][~mask])