diff --git a/changelog.d/record-data-calibration.rst b/changelog.d/record-data-calibration.rst new file mode 100644 index 00000000..28aabfde --- /dev/null +++ b/changelog.d/record-data-calibration.rst @@ -0,0 +1,7 @@ +**Edit digital calibration with an explicit meaning** + ``RecordData.with_calibration(adc_gain=..., baseline=..., mode=...)`` now + validates a complete per-channel calibration. ``mode="reinterpret"`` keeps + the digital samples; ``mode="rescale"`` adjusts them using the existing ADC + rounding rule to preserve physical values as closely as possible. Rescaling + rejects unknown current calibration and values outside the target format's + valid range. Physical values continue to choose calibration when written. diff --git a/docs/io.rst b/docs/io.rst index 8ec6ec75..e92abdf3 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -575,7 +575,8 @@ files that either reader accepts. .. autoclass:: wfdb.io.RecordData :no-index: :members: to_physical, to_digital, to_legacy_record, select, - with_values, with_channels, with_comments, shift_time, write + with_values, with_channels, with_calibration, with_comments, + shift_time, write .. autoclass:: wfdb.io.UniformSignals :no-index: @@ -627,6 +628,20 @@ return independent arrays. They update the selected view and leave Changing a unit label does not rescale the samples or change gain and baseline; use it to correct a mislabeled header, not to convert units. +For digital values, ``RecordData.with_calibration(adc_gain=..., baseline=..., +mode=...)`` changes the per-channel calibration. Both sequences must have one +value per loaded channel. Gains must be positive and finite, and baselines +must be signed 32-bit integers. ``mode="reinterpret"`` keeps the integers and +changes the physical values they represent. ``mode="rescale"`` changes the +integers to preserve the physical values as closely as the new calibration +allows. Rescaling requires a known current gain and baseline for each channel. +It uses the existing ADC rule: round to the nearest integer, with exact ties +going to the even integer. Values that hit a known format's missing marker or +exceed its valid range fail at the edit. Rescaling also preserves the loaded +integer dtype and rejects values that would require widening it. Both modes +copy the arrays and masks, and leave the source header unchanged. For physical +values, choose calibration when writing rather than editing the loaded values. + ``RecordData.shift_time(timedelta(...))`` changes the selected start date and time without changing samples. A time-only value wraps within the day, so whole-day shifts have no visible effect without a date. A date-only value @@ -646,6 +661,11 @@ do not share the result's source provenance if it is sensitive. labeled = edited.with_channels(names=["ECG lead V5", "ECG lead II"]) labeled = labeled.with_comments(["Reviewed for release"]) + digital = wfdb.read_signals("sample-data/100", kind="digital", layout="uniform") + corrected = digital.with_calibration( + adc_gain=[200.0, 200.0], baseline=[1024, 1024], mode="reinterpret" + ) + Writing a selected signal view ------------------------------ diff --git a/src/wfdb/io/_record_data_edits.py b/src/wfdb/io/_record_data_edits.py index b7e12ac4..3a697a7e 100644 --- a/src/wfdb/io/_record_data_edits.py +++ b/src/wfdb/io/_record_data_edits.py @@ -364,6 +364,115 @@ def replace_record_comments(read, comments): return _replace_record_metadata(read, comments=comments) +def _calibration_fields(values, field, count): + """Require one calibration value for each loaded channel.""" + if not isinstance(values, (list, tuple)) or len(values) != count: + raise ValueError(f"{field} must contain one value per loaded channel") + return tuple(values) + + +def replace_record_calibration(read, adc_gain, baseline, mode): + """Change digital calibration while preserving one chosen signal meaning.""" + if read.signals.kind != "digital": + raise ValueError( + "with_calibration applies only to digital values; choose calibration " + "with write options for physical values" + ) + if mode not in ("rescale", "reinterpret"): + raise ValueError("mode must be 'rescale' or 'reinterpret'") + count = read.metadata.n_signals + adc_gain = _calibration_fields(adc_gain, "adc_gain", count) + baseline = _calibration_fields(baseline, "baseline", count) + gains = [] + offsets = [] + for index, (gain, offset) in enumerate(zip(adc_gain, baseline, strict=True)): + if isinstance(gain, (bool, np.bool_)) or not isinstance( + gain, (int, float, np.integer, np.floating) + ): + raise ValueError(f"adc_gain[{index}] must be a positive finite number") + try: + gain = float(gain) + except OverflowError as error: + raise ValueError( + f"adc_gain[{index}] must be a positive finite number" + ) from error + if not np.isfinite(gain) or gain <= 0: + raise ValueError(f"adc_gain[{index}] must be a positive finite number") + if isinstance(offset, (bool, np.bool_)): + raise ValueError(f"baseline[{index}] must be a signed 32-bit integer") + try: + offset = operator.index(offset) + except TypeError as error: + raise ValueError( + f"baseline[{index}] must be a signed 32-bit integer" + ) from error + if not -(2**31) <= offset <= 2**31 - 1: + raise ValueError(f"baseline[{index}] must be a signed 32-bit integer") + gains.append(gain) + offsets.append(int(offset)) + calibration = (tuple(gains), tuple(offsets)) + if mode == "reinterpret": + return _replace_record_metadata(read, calibration=calibration) + + old = read.metadata.signals + missing = [ + index + for index, signal in enumerate(old) + if signal.adc_gain is None + or signal.baseline is None + or not np.isfinite(signal.adc_gain) + or signal.adc_gain <= 0 + ] + if missing: + raise ValueError( + "Cannot rescale channels without current adc_gain and baseline: " + + ", ".join(map(str, missing)) + ) + expanded = isinstance(read.signals, ExpandedSignals) + channels = read.signals.values if expanded else tuple(read.signals.values.T) + output = [] + for index, channel in enumerate(channels): + mask = np.ma.getmaskarray(channel) + source = np.ma.getdata(channel) + converted = np.zeros(source.shape, dtype=np.int64) + valid = ~mask + if np.any(valid): + physical = (source[valid].astype(np.float64) - old[index].baseline) / old[ + index + ].adc_gain + rounded = np.rint(physical * gains[index] + offsets[index]) + limits = np.iinfo(np.int64) + if ( + not np.all(np.isfinite(rounded)) + or np.any(rounded < limits.min) + or np.any(rounded >= -float(limits.min)) + ): + raise ValueError(f"rescaled channel {index} exceeds integer range") + converted[valid] = rounded.astype(np.int64) + output.append(np.ma.array(converted, mask=mask, copy=False)) + _validate_digital_ranges(read, output) + casted = [] + for index, (source, converted) in enumerate(zip(channels, output, strict=True)): + bounds = np.iinfo(source.dtype) + valid = np.ma.getdata(converted)[~np.ma.getmaskarray(converted)] + if valid.size and (np.min(valid) < bounds.min or np.max(valid) > bounds.max): + raise ValueError( + f"rescaled channel {index} exceeds loaded {source.dtype} " + "resolution; reread with a higher resolution" + ) + casted.append( + np.ma.array( + np.ma.getdata(converted).astype(source.dtype), + mask=np.ma.getmaskarray(converted), + copy=False, + ) + ) + arrays = tuple(casted) if expanded else np.ma.column_stack(casted) + return _replace_record_metadata( + read, calibration=calibration, replacement_values=arrays + ) + + def shift_record_time(read, delta): """Shift the selected start date or time without changing its source.""" if not isinstance(delta, datetime.timedelta): @@ -406,15 +515,22 @@ def shift_record_time(read, delta): def _replace_record_metadata( - read, *, names=None, units=None, comments=None, timing=None + read, + *, + names=None, + units=None, + comments=None, + timing=None, + calibration=None, + replacement_values=None, ): """Copy arrays and change only the selected view's header metadata.""" model = read._model expanded = isinstance(read.signals, ExpandedSignals) + current = read.signals.values if replacement_values is None else replacement_values if read.signals.kind == "digital": - values, mask = _copy_digital(read.signals.values, expanded) + values, mask = _copy_digital(current, expanded) else: - current = read.signals.values values = ( tuple(value.copy() for value in current) if expanded else current.copy() ) @@ -434,6 +550,12 @@ def _replace_record_metadata( record.comments = list(comments) if timing is not None: record.base_date, record.base_time = timing + if calibration is not None: + record.adc_gain = list(calibration[0]) + record.baseline = list(calibration[1]) + if replacement_values is not None: + record.init_value = [None] * read.metadata.n_signals + record.checksum = [None] * read.metadata.n_signals field = ("e_" if expanded else "") + ( "p_signal" if read.signals.kind == "physical" else "d_signal" ) @@ -451,9 +573,17 @@ def _replace_record_metadata( signal, sig_name=signal.sig_name if names is None else names[index], units=signal.units if units is None else units[index], + adc_gain=signal.adc_gain + if calibration is None + else calibration[0][index], + baseline=signal.baseline + if calibration is None + else calibration[1][index], ) for index, signal in enumerate(model.selected_header.signals) ) + if replacement_values is not None: + selected = _clean_signals(selected) selected_comments = ( model.selected_header.comments if comments is None else comments ) @@ -482,7 +612,11 @@ def _replace_record_metadata( metadata=metadata, ) ) - object.__setattr__(result, "_edited_values", getattr(read, "_edited_values", False)) + object.__setattr__( + result, + "_edited_values", + replacement_values is not None or getattr(read, "_edited_values", False), + ) return result diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index a4ca3d95..c677a154 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -362,6 +362,44 @@ def with_channels( return replace_record_channel_metadata(self, names, units) + def with_calibration( + self, + *, + adc_gain: list[float] | tuple[float, ...], + baseline: list[int] | tuple[int, ...], + mode: Literal["rescale", "reinterpret"], + ) -> "RecordData": + """Return digital data with a validated per-channel calibration. + + ``mode="rescale"`` changes the integers to preserve their physical + values under the new gain and baseline. It requires a known current + calibration for every channel. Conversion uses WFDB's existing ADC + rounding rule (nearest integer, with ties to even). Values that do not + fit their known storage formats or the loaded integer dtype are + rejected immediately; the dtype is never silently widened. + ``mode="reinterpret"`` keeps the integers and changes the physical + values they represent. Both modes copy the arrays and masks, retain + source provenance, and leave this object unchanged. Use write options + to choose calibration when writing physical data. + + Parameters + ---------- + adc_gain : sequence of float + One positive finite gain per loaded channel. + baseline : sequence of int + One signed 32-bit baseline per loaded channel. + mode : {"rescale", "reinterpret"} + Whether to preserve physical values or digital integers. + + Returns + ------- + RecordData + An independent result with the requested calibration. + """ + from wfdb.io._record_data_edits import replace_record_calibration + + return replace_record_calibration(self, adc_gain, baseline, mode) + def with_comments(self, comments: list[str] | tuple[str, ...]) -> "RecordData": """Return a copy with replacement record comments. diff --git a/tests/test_record_data_calibration.py b/tests/test_record_data_calibration.py new file mode 100644 index 00000000..db163503 --- /dev/null +++ b/tests/test_record_data_calibration.py @@ -0,0 +1,211 @@ +"""Validated calibration edits on digital RecordData.""" + +import pickle +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pytest + +import wfdb +from wfdb.io._read_model import _metadata_for_view +from wfdb.io.signal_values import _from_read_model + + +def _digital_read(tmp_path): + """Create two channels with distinct formats and a missing sample.""" + source = tmp_path / "source" + values = np.ma.array( + [[0, 1], [1, 2], [2, 3], [3, 4]], + mask=[[False, False], [True, False], [False, False], [False, False]], + dtype=np.int16, + ) + wfdb.write_signals( + source, + values, + fs=125, + kind="digital", + formats=["16", "212"], + channel_names=["I", "II"], + units=["mV", "mV"], + adc_gain=[2, 4], + baseline=[0, 1], + ) + return wfdb.read_signals(source, kind="digital", layout="uniform") + + +def test_reinterpret_keeps_digital_values_and_changes_physical_scale(tmp_path): + """Reinterpret changes metadata and conversion, but never source samples.""" + original = _digital_read(tmp_path) + edited = original.with_calibration( + adc_gain=[4, 8], baseline=[2, 3], mode="reinterpret" + ) + np.testing.assert_array_equal(edited.signals.values, original.signals.values) + np.testing.assert_array_equal( + np.ma.getmaskarray(edited.signals.values), + np.ma.getmaskarray(original.signals.values), + ) + assert edited.metadata.signals[0].adc_gain == 4 + assert edited.metadata.signals[1].baseline == 3 + assert original.metadata.signals[0].adc_gain == 2 + assert edited.source_header == original.source_header + assert edited.source_selection == original.source_selection + assert not np.shares_memory(edited.signals.values, original.signals.values) + assert edited.to_physical().signals.values[0, 0] == -0.5 + target = tmp_path / "reinterpret" + edited.write(target) + restored = wfdb.read_signals(target, kind="digital", layout="uniform") + assert restored.metadata.signals == edited.metadata.signals + np.testing.assert_array_equal(restored.signals.values, edited.signals.values) + + +def test_rescale_preserves_physical_values_up_to_adc_rounding(tmp_path): + """A rescale uses nearest-even ADC rounding and preserves gaps.""" + original = _digital_read(tmp_path) + edited = original.with_calibration(adc_gain=[1, 8], baseline=[1, 3], mode="rescale") + expected = np.array([[1, 3], [0, 5], [2, 7], [2, 9]]) + mask = np.ma.getmaskarray(edited.signals.values) + np.testing.assert_array_equal(edited.signals.values.data[~mask], expected[~mask]) + np.testing.assert_array_equal(mask, np.ma.getmaskarray(original.signals.values)) + assert edited.metadata.signals[0].adc_gain == 1 + assert edited.metadata.channels[0].storage.init_value is None + assert edited.metadata.channels[0].storage.checksum is None + assert original.metadata.signals[0].adc_gain == 2 + assert not np.shares_memory(edited.signals.values, original.signals.values) + target = tmp_path / "rescale" + wfdb.write_record(target, edited) + restored = wfdb.read_signals(target, kind="digital", layout="uniform") + np.testing.assert_array_equal(restored.signals.values, edited.signals.values) + np.testing.assert_array_equal(np.ma.getmaskarray(restored.signals.values), mask) + np.testing.assert_array_equal( + restored.to_physical().signals.values, + edited.to_physical().signals.values, + ) + + +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_rescale_preserves_loaded_integer_resolution(tmp_path, layout): + """A requested int16 read remains int16 after a valid calibration edit.""" + _digital_read(tmp_path) + read = wfdb.read_signals( + tmp_path / "source", kind="digital", layout=layout, resolution=16 + ) + gains = [signal.adc_gain for signal in read.metadata.signals] + baselines = [signal.baseline + 1 for signal in read.metadata.signals] + edited = read.with_calibration(adc_gain=gains, baseline=baselines, mode="rescale") + arrays = edited.signals.values if layout == "expanded" else (edited.signals.values,) + assert all(array.dtype == np.dtype("int16") for array in arrays) + + +def test_rescale_rejects_samples_outside_loaded_resolution(tmp_path): + """A value fitting format 24 cannot silently widen an int16 read.""" + path = tmp_path / "wide_format" + wfdb.write_signals( + path, + np.array([[0], [1000]], dtype=np.int16), + fs=125, + kind="digital", + formats="24", + channel_names=["I"], + units=["mV"], + adc_gain=[1], + baseline=[0], + missing="none", + ) + read = wfdb.read_signals(path, kind="digital", layout="uniform", resolution=32) + read = read.with_values(np.array([[0], [1000]], dtype=np.int16), missing="none") + with pytest.raises(ValueError, match="loaded int16 resolution"): + read.with_calibration(adc_gain=[100], baseline=[0], mode="rescale") + + +def test_expanded_rescale_keeps_lengths_and_source_provenance(): + """Each expanded channel retains its own sample count.""" + original = wfdb.read_signals( + "sample-data/test01_00s_frame", kind="digital", layout="expanded", stop=5 + ) + gain = [item.adc_gain for item in original.metadata.signals] + baseline = [item.baseline + 1 for item in original.metadata.signals] + edited = original.with_calibration(adc_gain=gain, baseline=baseline, mode="rescale") + assert edited.source_header == original.source_header + assert edited.source_selection == original.source_selection + assert edited.signals.samples_per_frame == original.signals.samples_per_frame + for old, new in zip(original.signals.values, edited.signals.values): + np.testing.assert_array_equal(new, old + 1) + + +def test_rescale_requires_known_current_calibration(tmp_path): + """Reinterpret can repair a missing gain, but rescale cannot infer one.""" + original = _digital_read(tmp_path) + model = original._model + signals = list(model.selected_header.signals) + signals[0] = replace(signals[0], adc_gain=None) + header = replace(model.selected_header, signals=tuple(signals)) + metadata = _metadata_for_view( + header.record_fields, signals, header.comments, "digital", "uniform" + ) + missing = _from_read_model( + replace(model, selected_header=header, metadata=metadata) + ) + with pytest.raises(ValueError, match="current adc_gain and baseline: 0"): + missing.with_calibration(adc_gain=[2, 4], baseline=[0, 1], mode="rescale") + repaired = missing.with_calibration( + adc_gain=[2, 4], baseline=[0, 1], mode="reinterpret" + ) + assert repaired.metadata.signals[0].adc_gain == 2 + + +@pytest.mark.parametrize( + "kwargs,message", + [ + ({"adc_gain": [2]}, "adc_gain must contain one value"), + ({"baseline": [0]}, "baseline must contain one value"), + ({"adc_gain": [0, 4]}, r"adc_gain\[0\]"), + ({"adc_gain": [-2, 4]}, r"adc_gain\[0\]"), + ({"adc_gain": [np.inf, 4]}, r"adc_gain\[0\]"), + ({"adc_gain": [True, 4]}, r"adc_gain\[0\]"), + ({"baseline": [0.0, 1]}, r"baseline\[0\]"), + ({"baseline": [True, 1]}, r"baseline\[0\]"), + ({"baseline": [2**31, 1]}, r"baseline\[0\]"), + ({"mode": "guess"}, "mode must be"), + ], +) +def test_calibration_rejects_invalid_inputs(tmp_path, kwargs, message): + """Invalid edits fail immediately and leave the source unchanged.""" + original = _digital_read(tmp_path) + options = {"adc_gain": [2, 4], "baseline": [0, 1], "mode": "reinterpret"} + options.update(kwargs) + with pytest.raises(ValueError, match=message): + original.with_calibration(**options) + assert original.metadata.signals[0].adc_gain == 2 + + +def test_calibration_rejects_physical_data(tmp_path): + """Physical calibration belongs to the write options.""" + physical = _digital_read(tmp_path).to_physical() + with pytest.raises(ValueError, match="write options for physical"): + physical.with_calibration(adc_gain=[2, 4], baseline=[0, 1], mode="reinterpret") + + +def test_rescale_checks_marker_and_range_before_writing(tmp_path): + """A new calibration cannot create unmasked markers or out-of-range data.""" + original = _digital_read(tmp_path) + with pytest.raises(ValueError, match="missing marker"): + original.with_calibration(adc_gain=[2, 4], baseline=[-32768, 1], mode="rescale") + with pytest.raises(ValueError, match="valid range"): + original.with_calibration(adc_gain=[100000, 4], baseline=[0, 1], mode="rescale") + + +def test_saved_517_read_can_change_calibration(): + """Old pickles can take a validated metadata edit without a new source.""" + path = Path(__file__).parent / "fixtures/signal_read_v5_17/digital_expanded.pkl" + saved = pickle.loads(path.read_bytes()) + gains = [signal.adc_gain for signal in saved.metadata.signals] + offsets = [signal.baseline for signal in saved.metadata.signals] + edited = saved.with_calibration( + adc_gain=gains, baseline=offsets, mode="reinterpret" + ) + assert edited.metadata.signals == saved.metadata.signals + assert edited.source_header is None + rescaled = saved.with_calibration(adc_gain=gains, baseline=offsets, mode="rescale") + for before, after in zip(saved.signals.values, rescaled.signals.values): + np.testing.assert_array_equal(before, after)