From ff739644f1bc1c2f5c75c1950cf4976d6ef630b3 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 11:02:11 -0500 Subject: [PATCH 1/3] Add validated RecordData selection and value replacement --- changelog.d/record-data-edits.rst | 7 + docs/io.rst | 29 +++- src/wfdb/io/_record_data_edits.py | 276 ++++++++++++++++++++++++++++++ src/wfdb/io/record.py | 5 + src/wfdb/io/signal_values.py | 111 +++++++++++- tests/test_record_data_edits.py | 264 ++++++++++++++++++++++++++++ 6 files changed, 685 insertions(+), 7 deletions(-) create mode 100644 changelog.d/record-data-edits.rst create mode 100644 src/wfdb/io/_record_data_edits.py create mode 100644 tests/test_record_data_edits.py diff --git a/changelog.d/record-data-edits.rst b/changelog.d/record-data-edits.rst new file mode 100644 index 00000000..e0e6e3c2 --- /dev/null +++ b/changelog.d/record-data-edits.rst @@ -0,0 +1,7 @@ +**Select and replace loaded RecordData values** + ``RecordData.select`` copies a frame and channel selection from the current + arrays, preserving source provenance. ``RecordData.with_values`` validates + replacement arrays of the same kind and layout, including an explicit + missing-sample policy for plain digital arrays. Both return independent + results. Writing a result of either edit method derives initial values and + checksums from the values being saved. diff --git a/docs/io.rst b/docs/io.rst index 1257979b..43aa5580 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -567,7 +567,8 @@ files that either reader accepts. .. autoclass:: wfdb.io.RecordData :no-index: - :members: to_physical, to_digital, to_legacy_record, write + :members: to_physical, to_digital, to_legacy_record, select, + with_values, write .. autoclass:: wfdb.io.UniformSignals :no-index: @@ -575,6 +576,32 @@ files that either reader accepts. .. autoclass:: wfdb.io.ExpandedSignals :no-index: +Editing a selected record +------------------------- + +``RecordData.select(start=..., stop=..., channels=...)`` selects from the +current loaded arrays, including any sample edits already made. Frame bounds +and channel indices refer to the current view; ``channel_names`` can be used +instead of indices when each name identifies one channel. The result copies +the selected arrays and masks, and its ``source_selection`` still refers to +the original source record. Flattened ``source_segments`` are clipped and +rebased to the new view. The source header remains the original header. + +``RecordData.with_values(values)`` replaces the current arrays while keeping +their kind, layout, frame count, channel count, and calibration. Physical +replacement arrays must contain floating values, using NaN for missing +samples. Digital replacement arrays must be NumPy masked integer arrays; +for a plain integer array with no missing samples, pass ``missing="none"``. +Both methods return independent arrays. They clear sample-dependent header +initial values and checksums; writing derives those fields from the values +being saved. + +.. code-block:: python + + read = wfdb.read_signals("sample-data/100", layout="uniform") + selected = read.select(start=100, stop=200, channels=[1, 0]) + edited = selected.with_values(selected.signals.values * 2) + Writing a selected signal view ------------------------------ diff --git a/src/wfdb/io/_record_data_edits.py b/src/wfdb/io/_record_data_edits.py new file mode 100644 index 00000000..01cc0bec --- /dev/null +++ b/src/wfdb/io/_record_data_edits.py @@ -0,0 +1,276 @@ +"""Validated edits of selected record data and its private read model.""" + +import copy +import operator +from dataclasses import replace + +import numpy as np + +from wfdb.io import _header +from wfdb.io._read_model import _adjust_time, _metadata_for_view +from wfdb.io.signal_values import ExpandedSignals, _from_read_model + + +def _clean_signals(signals): + """Clear sample-dependent declarations after changing a selected view.""" + return tuple(replace(signal, init_value=None, checksum=None) for signal in signals) + + +def _edited_result(result): + """Mark a new result whose sample-dependent header fields must be derived.""" + object.__setattr__(result, "_edited_values", True) + return result + + +def _selected_model(read, values, mask, selected, start, stop, channels): + """Build a coherent model after a frame or channel selection.""" + model = read._model + fields = model.selected_header.record_fields + base_date, base_time = _adjust_time( + fields.base_date, fields.base_time, fields.fs, start + ) + updated_fields = replace( + fields, + n_sig=len(channels), + sig_len=stop - start, + base_date=base_date, + base_time=base_time, + ) + selected_header = _header._ParsedSingleSegmentHeader( + updated_fields, selected, model.selected_header.comments + ) + layout = "expanded" if model.expanded else "uniform" + metadata = _metadata_for_view( + updated_fields, selected, model.selected_header.comments, model.kind, layout + ) + segments = tuple( + type(segment)( + segment.name, + max(segment.start, start) - start, + min(segment.stop, stop) - start, + ) + for segment in model.source_segments + if segment.start < stop and segment.stop > start + ) + skewed = any(signal.skew not in (None, 0) for signal in selected) + return replace( + model, + selected_header=selected_header, + source_segments=segments, + source_start=model.source_start + start, + source_stop=model.source_start + stop, + source_channels=tuple(model.source_channels[index] for index in channels), + values=values, + mask=mask, + metadata=metadata, + write_formats=tuple(model.write_formats[index] for index in channels) + if model.write_formats is not None + else None, + incomplete_skew_tail=model.raw_alignment + and skewed + and (model.incomplete_skew_tail or stop < read.metadata.n_frames), + ) + + +def select_record_data(read, start, stop, channels, channel_names): + """Select copied current samples and update source-relative provenance.""" + model = read._model + frames = read.metadata.n_frames + if isinstance(start, bool) or isinstance(stop, bool): + raise TypeError("start and stop must be integers") + try: + start = operator.index(start) + stop = frames if stop is None else operator.index(stop) + except TypeError as error: + raise TypeError("start and stop must be integers") from error + if start < 0 or stop > frames or stop <= start: + raise ValueError("Require 0 <= start < stop <= current frame count") + if channels is not None and channel_names is not None: + raise ValueError("Pass either channels or channel_names, not both") + if channel_names is not None: + if not isinstance(channel_names, (list, tuple)) or not channel_names: + raise ValueError("channel_names must be a nonempty sequence") + available = [signal.name for signal in read.metadata.signals] + if any(available.count(name) != 1 for name in channel_names): + raise ValueError("channel_names must uniquely identify loaded channels") + channels = [available.index(name) for name in channel_names] + elif channels is None: + channels = list(range(read.metadata.n_signals)) + if not isinstance(channels, (list, tuple)) or not channels: + raise ValueError("channels must be a nonempty sequence") + try: + indices = [operator.index(index) for index in channels] + except TypeError as error: + raise TypeError("channel indices must be integers") from error + if ( + any(isinstance(index, bool) for index in channels) + or len(set(indices)) != len(indices) + or any(index < 0 or index >= read.metadata.n_signals for index in indices) + ): + raise ValueError("channels must be distinct indices in the loaded view") + expanded = isinstance(read.signals, ExpandedSignals) + if expanded: + factors = read.signals.samples_per_frame + arrays = tuple( + read.signals.values[index][start * factors[index] : stop * factors[index]] + for index in indices + ) + else: + arrays = read.signals.values[start:stop, :][:, indices] + if read.signals.kind == "digital": + arrays, mask = _copy_digital(arrays, expanded) + else: + arrays = tuple(array.copy() for array in arrays) if expanded else arrays.copy() + mask = None + if model is None: + return _legacy_edited_read(read, arrays, mask, start, stop, indices) + selected = _clean_signals(model.selected_header.signals[index] for index in indices) + return _edited_result( + _from_read_model( + _selected_model(read, arrays, mask, selected, start, stop, indices) + ) + ) + + +def _copy_digital(values, expanded): + """Copy digital data and masks, keeping the no-mask fast path.""" + arrays = values if expanded else (values,) + copied = tuple(np.ma.array(array, copy=True) for array in arrays) + masks = tuple(array.mask for array in copied) + mask = None if all(value is np.ma.nomask for value in masks) else masks + if not expanded: + return np.ma.getdata(copied[0]), None if mask is None else masks[0] + return tuple(np.ma.getdata(array) for array in copied), mask + + +def replace_record_values(read, values, missing): + """Validate replacement arrays and keep the source selection unchanged.""" + model = read._model + expanded = isinstance(read.signals, ExpandedSignals) + if expanded: + if ( + not isinstance(values, (list, tuple)) + or len(values) != read.metadata.n_signals + ): + raise ValueError("expanded values need one array per loaded channel") + arrays = tuple(values) + else: + arrays = (values,) + expected_kind = "f" if read.signals.kind == "physical" else "iu" + for index, array in enumerate(arrays): + if not isinstance(array, np.ndarray): + raise ValueError("replacement values must be NumPy arrays") + if array.dtype.kind not in expected_kind: + raise ValueError( + f"{read.signals.kind} replacement values have the wrong dtype" + ) + if array.ndim != (1 if expanded else 2): + raise ValueError("replacement values must keep the loaded layout") + expected_shape = ( + (read.metadata.n_frames * read.signals.samples_per_frame[index],) + if expanded + else (read.metadata.n_frames, read.metadata.n_signals) + ) + if array.shape != expected_shape: + raise ValueError( + f"replacement channel {index} has shape {array.shape}; " + f"expected {expected_shape}" + ) + if read.signals.kind == "physical": + if missing is not None or any(isinstance(a, np.ma.MaskedArray) for a in arrays): + raise ValueError("physical values use NaN, not a separate missing mask") + if any(np.isinf(array).any() for array in arrays): + raise ValueError("physical values cannot contain infinity") + copied = tuple(array.copy() for array in arrays) + mask = None + else: + masked = [isinstance(array, np.ma.MaskedArray) for array in arrays] + if all(masked): + if missing is not None: + raise ValueError("masked digital arrays already carry missing samples") + elif not any(masked) and missing == "none": + pass + else: + raise ValueError( + 'plain digital arrays require missing="none"; ' + "use NumPy masked arrays for missing samples" + ) + copied, mask = _copy_digital(arrays if expanded else arrays[0], expanded) + result_values = copied if expanded or read.signals.kind == "digital" else copied[0] + if model is None: + return _legacy_edited_read( + read, + result_values, + mask, + 0, + read.metadata.n_frames, + list(range(read.metadata.n_signals)), + ) + selected = _clean_signals(model.selected_header.signals) + edited = _selected_model( + read, + result_values, + mask, + selected, + 0, + read.metadata.n_frames, + list(range(read.metadata.n_signals)), + ) + return _edited_result(_from_read_model(edited)) + + +def _legacy_edited_read(read, values, mask, start, stop, channels): + """Keep old saved reads editable without inventing lost provenance.""" + from wfdb.io.record import _ReadSource + from wfdb.io.signal_values import _from_record + + source = copy.copy(read._record) + old_count = read.metadata.n_signals + for field in _header.SIGNAL_SPECS.index: + items = getattr(source, field, None) + if isinstance(items, (list, tuple)) and len(items) == old_count: + setattr(source, field, [items[index] for index in channels]) + for field in ("_applied_skew", "_read_skew"): + items = getattr(source, field, None) + if isinstance(items, (list, tuple)) and len(items) == old_count: + setattr(source, field, [items[index] for index in channels]) + source.n_sig = len(channels) + source.sig_len = stop - start + source.base_date, source.base_time = _adjust_time( + source.base_date, source.base_time, source.fs, start + ) + source.source_segments = [ + type(segment)( + segment.name, + max(segment.start, start) - start, + min(segment.stop, stop) - start, + ) + for segment in read.source_segments + if segment.start < stop and segment.stop > start + ] or None + original = getattr(source, "_read_source", None) + if original is not None: + source._read_source = _ReadSource( + original.header, + original.start + start, + original.start + stop, + tuple(original.channels[index] for index in channels), + original.signal_header, + ) + field = ("e_" if isinstance(read.signals, ExpandedSignals) else "") + ( + "p_signal" if read.signals.kind == "physical" else "d_signal" + ) + for name in ("p_signal", "d_signal", "e_p_signal", "e_d_signal"): + setattr(source, name, None) + setattr(source, field, list(values) if isinstance(values, tuple) else values) + source.init_value = [None] * len(channels) + source.checksum = [None] * len(channels) + return _edited_result( + _from_record( + source, + read.signals.kind, + isinstance(read.signals, ExpandedSignals), + mask=mask, + write_formats=tuple(read._write_formats[index] for index in channels), + ) + ) diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 2aa0e7b7..48f4e676 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -5710,6 +5710,7 @@ def write( archive_path=None, *, derive_features: bool = True, + refresh_features: bool = False, ) -> None: """Validate, prepare, and encode this model without a Record adapter.""" self.record_name = name @@ -5769,6 +5770,10 @@ def write( self.e_d_signal = converted else: self.d_signal = converted + if refresh_features and not self.from_segments: + # Selected read values may have been edited since decoding. + # Derive sample-dependent header fields from the values written. + self._prepare_digital_features(expanded=expanded) if derive_features or self.from_segments: self._prepare_defaults() self._validate_values_before_write(physical_checked=physical_checked) diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index 903f58d4..40338e34 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -2,7 +2,7 @@ import copy import os -from dataclasses import dataclass +from dataclasses import dataclass, replace from typing import Literal import numpy as np @@ -84,8 +84,9 @@ class RecordData: flattened multi-segment read, ``source_segments`` identifies the source segments. Conversions return another ``RecordData`` and leave this one unchanged. Use ``write`` to save the selected values. - Construct results through ``read_signals``; ``dataclasses.replace`` - cannot construct one because it lacks the record needed for conversions. + Construct results through ``read_signals`` or ``read_segments``. Use + ``select`` and ``with_values`` for validated edits; ``dataclasses.replace`` + cannot construct a complete result with source provenance. """ signals: UniformSignals | ExpandedSignals @@ -138,7 +139,9 @@ def _record(self): def __init__(self, *args, **kwargs) -> None: """Reserve construction for the reader, which supplies calibration.""" - raise TypeError("RecordData objects are returned by read_signals") + raise TypeError( + "RecordData objects are returned by read_signals or read_segments" + ) def __setstate__(self, state: dict) -> None: """Load saved reads that predate the private reader model.""" @@ -161,6 +164,7 @@ def _create( object.__setattr__(result, "_record_adapter", record) object.__setattr__(result, "_model", model) object.__setattr__(result, "_write_formats", write_formats) + object.__setattr__(result, "_edited_values", False) return result def to_physical(self, resolution: int = 64) -> "RecordData": @@ -261,6 +265,68 @@ def to_legacy_record(self): ) return copy.deepcopy(source) + def select( + self, + *, + start: int = 0, + stop: int | None = None, + channels: list[int] | tuple[int, ...] | None = None, + channel_names: list[str] | tuple[str, ...] | None = None, + ) -> "RecordData": + """Return a copy of selected frames and channels from current values. + + ``start`` and exclusive ``stop`` are relative to this loaded view; + channel indices also refer to this view. Source provenance remains in + the original record's coordinates. The result does not share signal + arrays or masks with this object. + + Parameters + ---------- + start, stop : int, optional + First and exclusive last frame in the current loaded view. + channels : sequence of int, optional + Distinct channel indices in the current loaded view. + channel_names : sequence of str, optional + Names that uniquely identify loaded channels. Cannot be combined + with ``channels``. + + Returns + ------- + RecordData + An independent selected result. + """ + from wfdb.io._record_data_edits import select_record_data + + return select_record_data(self, start, stop, channels, channel_names) + + def with_values(self, values, *, missing: str | None = None) -> "RecordData": + """Return a copy with replacement values of the same kind and layout. + + Replacement arrays must match the current frame and channel shape. + Physical values must be floating arrays, with NaN for missing samples. + Digital values must be integer masked arrays, or plain integer arrays + with ``missing="none"``. The result copies the arrays and masks. + Calibration and source provenance are retained; header checksums and + initial values are cleared because they describe previous samples. + + Parameters + ---------- + values : ndarray or sequence of ndarray + Replacement array for uniform layout, or one array per channel + for expanded layout. + missing : {"none"}, optional + Required for plain digital arrays to declare that no samples are + missing. Omit for physical or masked digital arrays. + + Returns + ------- + RecordData + An independent result with the replacement samples. + """ + from wfdb.io._record_data_edits import replace_record_values + + return replace_record_values(self, values, missing) + def write( self, path: str | os.PathLike, @@ -329,7 +395,11 @@ def write( source, field, "expanded" if expanded else "uniform", signal_alignment ) model.write( - name, directory, destination if archive else None, derive_features=False + name, + directory, + destination if archive else None, + derive_features=False, + refresh_features=getattr(self, "_edited_values", False), ) @@ -622,6 +692,31 @@ def _converted_read( read: RecordData, values, kind: SignalKind, mask=None ) -> RecordData: """Build a converted view without changing the original record or arrays.""" + if read._model is not None: + from wfdb.io._read_model import _metadata_for_view + + model = read._model + expanded = isinstance(read.signals, ExpandedSignals) + if expanded: + arrays = tuple(values) + if kind == "digital": + arrays = tuple(np.ma.getdata(array) for array in arrays) + else: + arrays = np.ma.getdata(values) if kind == "digital" else values + metadata = _metadata_for_view( + model.selected_header.record_fields, + model.selected_header.signals, + model.selected_header.comments, + kind, + "expanded" if expanded else "uniform", + ) + converted = _from_read_model( + replace(model, values=arrays, kind=kind, mask=mask, metadata=metadata) + ) + object.__setattr__( + converted, "_edited_values", getattr(read, "_edited_values", False) + ) + return converted from wfdb.io.record import _LoadedSignalValues record = copy.copy(read._record) @@ -630,9 +725,13 @@ def _converted_read( setattr(record, name, value.copy()) expanded = isinstance(read.signals, ExpandedSignals) _LoadedSignalValues(values, kind == "physical", expanded).set_on_record(record) - return _from_record( + converted = _from_record( record, kind, expanded, mask=mask, write_formats=read._write_formats ) + object.__setattr__( + converted, "_edited_values", getattr(read, "_edited_values", False) + ) + return converted def _from_record( diff --git a/tests/test_record_data_edits.py b/tests/test_record_data_edits.py new file mode 100644 index 00000000..86ba2b5c --- /dev/null +++ b/tests/test_record_data_edits.py @@ -0,0 +1,264 @@ +"""Validated edits to loaded RecordData values and selections.""" + +import pickle +from pathlib import Path + +import numpy as np +import pytest + +import wfdb + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_select_uses_current_values_and_preserves_source(kind, layout): + """A second selection copies edits and keeps source coordinates.""" + path = "sample-data/mixedsignals" + read = wfdb.read_signals( + path, + layout=layout, + kind=kind, + start=10, + stop=20, + channels=[0, 3], + ) + if layout == "uniform": + read.signals.values[2, 1] = 7 + else: + read.signals.values[1][4] = 7 + selected = read.select(start=2, stop=6, channels=[1, 0]) + assert selected.source_header == read.source_header + assert selected.source_selection == wfdb.io.SourceSelection(12, 16, (3, 0)) + assert selected.metadata.n_frames == 4 + assert selected.metadata.n_signals == 2 + assert [signal.name for signal in selected.metadata.signals] == [ + read.metadata.signals[1].name, + read.metadata.signals[0].name, + ] + assert selected.metadata.channels[0].storage.checksum is None + direct = wfdb.read_signals( + path, + layout=layout, + kind=kind, + start=12, + stop=16, + channels=[3, 0], + ) + actual = ( + selected.signals.values if layout == "expanded" else (selected.signals.values,) + ) + expected = ( + direct.signals.values if layout == "expanded" else (direct.signals.values,) + ) + original_arrays = ( + read.signals.values if layout == "expanded" else (read.signals.values,) + ) + for left, right in zip(actual, expected): + assert not np.shares_memory(left, right) + assert all(not np.shares_memory(left, original) for original in original_arrays) + if layout == "uniform": + assert actual[0][0, 0] == 7 + else: + assert actual[0][0] == 7 + + +def test_select_rebases_flattened_segments(): + """Combined segment offsets follow the newly selected view.""" + read = wfdb.read_signals( + "sample-data/multi-segment/fixed1/v102s", + layout="uniform", + kind="digital", + start=74996, + stop=75004, + ) + selected = read.select(start=2, stop=6, channels=[1, 0]) + assert selected.source_selection.start == 74998 + assert selected.source_selection.stop == 75002 + assert [ + (part.name, part.start, part.stop) for part in selected.source_segments + ] == [ + ("v102s_1", 0, 2), + ("v102s_2", 2, 4), + ] + direct = wfdb.read_signals( + "sample-data/multi-segment/fixed1/v102s", + layout="uniform", + kind="digital", + start=74998, + stop=75002, + channels=[1, 0], + ) + np.testing.assert_array_equal(selected.signals.values, direct.signals.values) + + +def test_select_by_name_and_invalid_selection(): + """Names must identify one loaded channel; index and frame errors are clear.""" + read = wfdb.read_signals("sample-data/100", layout="uniform", stop=8) + name = read.metadata.signals[1].name + assert read.select(channel_names=[name]).metadata.n_signals == 1 + for kwargs, message in ( + ({"start": 3, "stop": 3}, "frame count"), + ({"start": -1}, "frame count"), + ({"stop": 9}, "frame count"), + ({"channels": [0, 0]}, "distinct"), + ({"channels": [2]}, "distinct"), + ({"channels": []}, "nonempty"), + ({"channel_names": ["missing"]}, "uniquely"), + ({"channels": [0], "channel_names": [name]}, "either"), + ): + with pytest.raises(ValueError, match=message): + read.select(**kwargs) + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_with_values_copies_and_keeps_metadata(kind, layout): + """Replaced arrays have the same shape and independent storage.""" + read = wfdb.read_signals( + "sample-data/mixedsignals", layout=layout, kind=kind, stop=5 + ) + arrays = read.signals.values if layout == "expanded" else (read.signals.values,) + replacement = tuple(array.copy() for array in arrays) + replacement[0][0] = 4 + input_values = replacement if layout == "expanded" else replacement[0] + result = read.with_values(input_values) + assert result.metadata.n_frames == read.metadata.n_frames + assert result.source_header == read.source_header + assert result.source_selection == read.source_selection + assert result.metadata.channels[0].storage.init_value is None + assert result.metadata.channels[0].storage.checksum is None + copied = result.signals.values if layout == "expanded" else (result.signals.values,) + for source, edited in zip(replacement, copied): + np.testing.assert_array_equal(source, edited) + assert not np.shares_memory(source, edited) + + +def test_with_values_requires_explicit_digital_missing_policy(): + """A stripped digital mask needs an explicit no-missing declaration.""" + read = wfdb.read_signals( + "sample-data/100", layout="uniform", kind="digital", stop=5 + ) + bare = np.asarray(read.signals.values) + with pytest.raises(ValueError, match='missing="none"'): + read.with_values(bare) + result = read.with_values(bare, missing="none") + assert isinstance(result.signals.values, np.ma.MaskedArray) + assert result.signals.values.mask is np.ma.nomask + with pytest.raises(ValueError, match="already carry"): + read.with_values(read.signals.values, missing="none") + + +def test_masked_digital_edit_preserves_gaps_and_copies_mask(tmp_path): + """Selecting and replacing masked samples keeps masks independent.""" + source = tmp_path / "source" + values = np.ma.array( + [[1, 2], [99, 99], [3, 4], [5, 6]], + mask=[[0, 0], [1, 1], [0, 0], [0, 0]], + dtype="int16", + ) + wfdb.write_signals( + source, + values, + fs=125, + kind="digital", + formats=["16", "212"], + channel_names=["I", "II"], + units=["mV", "mV"], + adc_gain=[200.0, 200.0], + baseline=[0, 0], + ) + read = wfdb.read_signals(source, kind="digital", layout="uniform") + selected = read.select(start=1, stop=4, channels=[1, 0]) + np.testing.assert_array_equal(selected.signals.values.mask[0], [True, True]) + edited = selected.with_values(selected.signals.values) + edited.signals.values[0, 0] = 7 + assert not edited.signals.values.mask[0, 0] + assert selected.signals.values.mask[0, 0] + edited.write(tmp_path / "edited") + restored = wfdb.read_signals(tmp_path / "edited", kind="digital", layout="uniform") + np.testing.assert_array_equal( + restored.signals.values.mask, edited.signals.values.mask + ) + + +def test_with_values_rejects_wrong_kind_layout_and_shape(): + """Replacement validation happens at the edit call.""" + read = wfdb.read_signals("sample-data/100", layout="uniform", stop=5) + for values, message in ( + (np.ones((5, 2), dtype="int16"), "wrong dtype"), + (np.ones(5, dtype="float64"), "layout"), + (np.ones((4, 2), dtype="float64"), "shape"), + (np.ma.array(np.ones((5, 2))), "separate missing mask"), + (np.full((5, 2), np.inf), "infinity"), + ): + with pytest.raises(ValueError, match=message): + read.with_values(values) + + +def test_edited_digital_write_recomputes_header_features(tmp_path): + """A changed value is written with its new initial value and checksum.""" + read = wfdb.read_signals( + "sample-data/100", layout="uniform", kind="digital", stop=8 + ) + values = read.signals.values.copy() + values[0, 0] += 10 + edited = read.with_values(values) + destination = tmp_path / "edited" + edited.write(destination) + reread = wfdb.read_signals(destination, layout="uniform", kind="digital") + np.testing.assert_array_equal(reread.signals.values, values) + header = wfdb.read_header(destination) + assert header.signals[0].init_value == int(values[0, 0]) + assert header.signals[0].checksum == int(np.sum(values[:, 0]) % 65536) + + +def test_edited_physical_write_keeps_calibration(tmp_path): + """A physical selection is writable with its original calibration.""" + read = wfdb.read_signals("sample-data/100", layout="uniform", stop=8) + selected = read.select(start=2, stop=6, channels=[1]) + destination = tmp_path / "selected" + selected.write(destination) + restored = wfdb.read_signals(destination, layout="uniform") + assert restored.metadata.n_frames == 4 + assert restored.metadata.n_signals == 1 + assert ( + restored.metadata.signals[0].adc_gain == selected.metadata.signals[0].adc_gain + ) + np.testing.assert_allclose( + restored.signals.values, selected.signals.values, atol=1e-12 + ) + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +def test_converted_result_can_be_selected_and_replaced(kind): + """Conversions retain the model needed for later validated edits.""" + read = wfdb.read_signals("sample-data/100", layout="uniform", kind=kind, stop=8) + converted = read.to_digital() if kind == "physical" else read.to_physical() + selected = converted.select(start=2, stop=5, channels=[1]) + assert selected.source_selection.start == 2 + assert selected.source_selection.channels == (1,) + assert selected.signals.kind == converted.signals.kind + edited = selected.with_values(selected.signals.values) + np.testing.assert_array_equal(edited.signals.values, selected.signals.values) + + +@pytest.mark.parametrize( + "name", + [ + "digital_uniform", + "digital_expanded", + "digital_multi_segment", + "physical_uniform", + "physical_expanded", + ], +) +def test_old_saved_read_can_use_new_edits(name): + """A v5.17.0 pickle remains editable without fabricating source fields.""" + fixture = Path(f"tests/fixtures/signal_read_v5_17/{name}.pkl") + read = pickle.loads(fixture.read_bytes()) + selected = read.select(start=1, stop=3, channels=[0]) + edited = selected.with_values(selected.signals.values) + assert edited.metadata.n_frames == 2 + assert edited.metadata.n_signals == 1 + assert edited.source_header is None + np.testing.assert_array_equal(edited.signals.values, selected.signals.values) From 469b5382ebf5841cef015edded6b25947831eb99 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 11:05:35 -0500 Subject: [PATCH 2/3] Match direct reads and validate digital edits --- changelog.d/record-data-edits.rst | 6 ++- docs/io.rst | 11 +++-- src/wfdb/io/_record_data_edits.py | 75 ++++++++++++++++++++++++++++++- src/wfdb/io/signal_values.py | 2 + tests/test_record_data_edits.py | 75 ++++++++++++++++++++++++++++++- 5 files changed, 162 insertions(+), 7 deletions(-) diff --git a/changelog.d/record-data-edits.rst b/changelog.d/record-data-edits.rst index e0e6e3c2..4a9e64ee 100644 --- a/changelog.d/record-data-edits.rst +++ b/changelog.d/record-data-edits.rst @@ -3,5 +3,7 @@ arrays, preserving source provenance. ``RecordData.with_values`` validates replacement arrays of the same kind and layout, including an explicit missing-sample policy for plain digital arrays. Both return independent - results. Writing a result of either edit method derives initial values and - checksums from the values being saved. + results. ``select`` recomputes sample-dependent header fields when the + selected data has enough calibration information. Writing a result of + either edit method derives initial values and checksums from the values + being saved. diff --git a/docs/io.rst b/docs/io.rst index 43aa5580..57a02d2b 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -592,9 +592,14 @@ their kind, layout, frame count, channel count, and calibration. Physical replacement arrays must contain floating values, using NaN for missing samples. Digital replacement arrays must be NumPy masked integer arrays; for a plain integer array with no missing samples, pass ``missing="none"``. -Both methods return independent arrays. They clear sample-dependent header -initial values and checksums; writing derives those fields from the values -being saved. +Known digital channel formats are checked for out-of-range and unmasked +missing-marker values when ``with_values`` is called. Channels assembled +from different source formats need a target ``formats=`` choice when written. +Both methods return independent arrays. ``select`` recomputes initial values +and checksums when the selected data has enough calibration information; +``with_values`` clears them. Writing either result derives these fields from +the values being saved. The source views identify where the data came from; +they do not assert that edited samples still match the source file. .. code-block:: python diff --git a/src/wfdb/io/_record_data_edits.py b/src/wfdb/io/_record_data_edits.py index 01cc0bec..8fa62915 100644 --- a/src/wfdb/io/_record_data_edits.py +++ b/src/wfdb/io/_record_data_edits.py @@ -16,6 +16,78 @@ def _clean_signals(signals): return tuple(replace(signal, init_value=None, checksum=None) for signal in signals) +def _selection_signals(read, arrays, indices, expanded): + """Derive sample declarations from the selected current values.""" + from wfdb.io import _signal + + selected = [] + for output_index, source_index in enumerate(indices): + signal = read._model.selected_header.signals[source_index] + values = arrays[output_index] if expanded else arrays[:, output_index] + digital = None + if read.signals.kind == "digital": + missing = np.ma.getmaskarray(values) + marker = _signal._digi_nan(signal.fmt) if signal.fmt else None + if not np.any(missing): + digital = np.ma.getdata(values) + elif marker is not None: + digital = np.ma.getdata(values).copy() + digital[missing] = marker + elif all( + value is not None + for value in (signal.fmt, signal.adc_gain, signal.baseline) + ): + try: + digital = _signal._adc_values( + [values], + [signal.fmt], + [signal.adc_gain], + [signal.baseline], + expanded=True, + )[0] + except (TypeError, ValueError): + pass + selected.append( + replace( + signal, + init_value=int(digital[0]) + if digital is not None and len(digital) + else None, + checksum=int(np.sum(digital) % 65536) if digital is not None else None, + ) + ) + return tuple(selected) + + +def _validate_digital_ranges(read, arrays): + """Reject replacement samples outside known source channel formats.""" + from wfdb.io import _signal + + formats = read._write_formats + for index, values in enumerate(arrays): + fmt = formats[index] if formats is not None else None + if fmt not in _signal.SAMPLE_VALUE_RANGE: + continue + marker = _signal._digi_nan(fmt) + lower, upper = _signal.SAMPLE_VALUE_RANGE[fmt] + valid_lower = lower + 1 if marker == lower else lower + data = np.ma.getdata(values) + missing = np.ma.getmaskarray(values) + valid = data[~missing] + if not valid.size: + continue + if marker is not None and np.any(valid == marker): + raise ValueError( + f"digital channel {index} has an unmasked value equal to " + f"format {fmt}'s missing marker {marker}" + ) + if np.min(valid) < valid_lower or np.max(valid) > upper: + raise ValueError( + f"digital channel {index} exceeds format {fmt}'s " + f"valid range {valid_lower} to {upper}" + ) + + def _edited_result(result): """Mark a new result whose sample-dependent header fields must be derived.""" object.__setattr__(result, "_edited_values", True) @@ -124,7 +196,7 @@ def select_record_data(read, start, stop, channels, channel_names): mask = None if model is None: return _legacy_edited_read(read, arrays, mask, start, stop, indices) - selected = _clean_signals(model.selected_header.signals[index] for index in indices) + selected = _selection_signals(read, arrays, indices, expanded) return _edited_result( _from_read_model( _selected_model(read, arrays, mask, selected, start, stop, indices) @@ -195,6 +267,7 @@ def replace_record_values(read, values, missing): 'plain digital arrays require missing="none"; ' "use NumPy masked arrays for missing samples" ) + _validate_digital_ranges(read, arrays) copied, mask = _copy_digital(arrays if expanded else arrays[0], expanded) result_values = copied if expanded or read.signals.kind == "digital" else copied[0] if model is None: diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index 40338e34..c0b3fcf9 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -306,6 +306,8 @@ def with_values(self, values, *, missing: str | None = None) -> "RecordData": Physical values must be floating arrays, with NaN for missing samples. Digital values must be integer masked arrays, or plain integer arrays with ``missing="none"``. The result copies the arrays and masks. + Digital values are checked against each channel's known format; + channels without one target format are checked when written. Calibration and source provenance are retained; header checksums and initial values are cleared because they describe previous samples. diff --git a/tests/test_record_data_edits.py b/tests/test_record_data_edits.py index 86ba2b5c..3e33d29d 100644 --- a/tests/test_record_data_edits.py +++ b/tests/test_record_data_edits.py @@ -35,7 +35,7 @@ def test_select_uses_current_values_and_preserves_source(kind, layout): read.metadata.signals[1].name, read.metadata.signals[0].name, ] - assert selected.metadata.channels[0].storage.checksum is None + assert selected.metadata.channels[0].storage.checksum is not None direct = wfdb.read_signals( path, layout=layout, @@ -88,9 +88,51 @@ def test_select_rebases_flattened_segments(): stop=75002, channels=[1, 0], ) + assert selected.metadata == direct.metadata np.testing.assert_array_equal(selected.signals.values, direct.signals.values) +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_select_matches_direct_read_metadata_and_values(tmp_path, kind, layout): + """Selecting a read reproduces a directly selected source window.""" + path = "sample-data/100" + selected = wfdb.read_signals( + path, kind=kind, layout=layout, start=10, stop=20 + ).select(start=2, stop=6, channels=[1, 0]) + direct = wfdb.read_signals( + path, kind=kind, layout=layout, start=12, stop=16, channels=[1, 0] + ) + assert selected.metadata == direct.metadata + assert selected.source_selection == direct.source_selection + assert selected.source_header == direct.source_header + actual = ( + selected.signals.values if layout == "expanded" else (selected.signals.values,) + ) + expected = ( + direct.signals.values if layout == "expanded" else (direct.signals.values,) + ) + for left, right in zip(actual, expected): + np.testing.assert_array_equal(left, right) + if kind == "digital": + np.testing.assert_array_equal( + np.ma.getmaskarray(left), np.ma.getmaskarray(right) + ) + converted = selected.to_digital() if kind == "physical" else selected.to_physical() + comparison = direct.to_digital() if kind == "physical" else direct.to_physical() + np.testing.assert_array_equal(converted.signals.values, comparison.signals.values) + selected_dir = tmp_path / "selected" + direct_dir = tmp_path / "direct" + selected_dir.mkdir() + direct_dir.mkdir() + selected.write(selected_dir / "copy") + direct.write(direct_dir / "copy") + for extension in ("hea", "dat"): + assert (selected_dir / f"copy.{extension}").read_bytes() == ( + direct_dir / f"copy.{extension}" + ).read_bytes() + + def test_select_by_name_and_invalid_selection(): """Names must identify one loaded channel; index and frame errors are clear.""" read = wfdb.read_signals("sample-data/100", layout="uniform", stop=8) @@ -110,6 +152,21 @@ def test_select_by_name_and_invalid_selection(): read.select(**kwargs) +def test_raw_skew_selection_preserves_incomplete_tail_rule(tmp_path): + """A trimmed raw view cannot silently write incomplete skewed data.""" + read = wfdb.read_signals( + "sample-data/test01_00s_skew", + layout="uniform", + kind="digital", + signal_alignment="raw", + ) + selected = read.select(start=1, stop=10) + destination = tmp_path / "short_raw" + with pytest.raises(ValueError, match="lack extra tail samples"): + selected.write(destination, signal_alignment="raw") + assert not destination.with_suffix(".hea").exists() + + @pytest.mark.parametrize("kind", ["physical", "digital"]) @pytest.mark.parametrize("layout", ["uniform", "expanded"]) def test_with_values_copies_and_keeps_metadata(kind, layout): @@ -148,6 +205,22 @@ def test_with_values_requires_explicit_digital_missing_policy(): read.with_values(read.signals.values, missing="none") +def test_with_values_rejects_known_format_range_and_marker(): + """Digital replacements are checked against the loaded channel format.""" + read = wfdb.read_signals( + "sample-data/100", layout="uniform", kind="digital", stop=5 + ) + values = read.signals.values.copy() + values[0, 0] = -2048 + with pytest.raises(ValueError, match="missing marker"): + read.with_values(values) + values[0, 0] = 5000 + with pytest.raises(ValueError, match="valid range"): + read.with_values(values) + values[0, 0] = np.ma.masked + assert read.with_values(values).signals.values.mask[0, 0] + + def test_masked_digital_edit_preserves_gaps_and_copies_mask(tmp_path): """Selecting and replacing masked samples keeps masks independent.""" source = tmp_path / "source" From f001edf13423d0816d126076ab4e559d351b66de Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 12:11:23 -0500 Subject: [PATCH 3/3] Align selected multi-segment metadata and provenance --- docs/io.rst | 12 +++++++++--- src/wfdb/io/_multi_read_model.py | 1 + src/wfdb/io/_read_model.py | 1 + src/wfdb/io/_record_data_edits.py | 16 ++++++++++++++++ tests/test_record_data_edits.py | 29 +++++++++++++++++++++++++++++ 5 files changed, 56 insertions(+), 3 deletions(-) diff --git a/docs/io.rst b/docs/io.rst index 57a02d2b..b429fca7 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -585,7 +585,9 @@ and channel indices refer to the current view; ``channel_names`` can be used instead of indices when each name identifies one channel. The result copies the selected arrays and masks, and its ``source_selection`` still refers to the original source record. Flattened ``source_segments`` are clipped and -rebased to the new view. The source header remains the original header. +rebased to the new view. The master ``source_header`` remains unchanged; for +fixed-layout data, ``source_signal_header`` follows the first retained data +segment, as it does on a direct read of that window. ``RecordData.with_values(values)`` replaces the current arrays while keeping their kind, layout, frame count, channel count, and calibration. Physical @@ -597,8 +599,12 @@ missing-marker values when ``with_values`` is called. Channels assembled from different source formats need a target ``formats=`` choice when written. Both methods return independent arrays. ``select`` recomputes initial values and checksums when the selected data has enough calibration information; -``with_values`` clears them. Writing either result derives these fields from -the values being saved. The source views identify where the data came from; +flattened physical multi-segment reads retain absent checksum declarations. +``with_values`` clears them. A source header can hold a signed checksum while +recalculation uses the equivalent unsigned value modulo 65536, so a full-record +selection can differ numerically from its source header. Writing either result +derives these fields from the values being saved. The source views identify +where the data came from; they do not assert that edited samples still match the source file. .. code-block:: python diff --git a/src/wfdb/io/_multi_read_model.py b/src/wfdb/io/_multi_read_model.py index db381602..cfc86bb1 100644 --- a/src/wfdb/io/_multi_read_model.py +++ b/src/wfdb/io/_multi_read_model.py @@ -308,6 +308,7 @@ def mark_missing(channel, first, last, missing): write_formats=write_formats, source_layout="variable" if variable else "fixed", unset_signal_fields=unset_signal_fields, + segment_headers=tuple(headers.items()), ) diff --git a/src/wfdb/io/_read_model.py b/src/wfdb/io/_read_model.py index 56c6f9ce..06655647 100644 --- a/src/wfdb/io/_read_model.py +++ b/src/wfdb/io/_read_model.py @@ -40,6 +40,7 @@ class _ReadModel: write_formats: tuple[str | None, ...] | None = None source_layout: str | None = None unset_signal_fields: tuple[str, ...] = () + segment_headers: tuple[tuple[str, _header._ParsedSingleSegmentHeader], ...] = () def to_record(self, current_values): """Project current values to a legacy Record only when requested.""" diff --git a/src/wfdb/io/_record_data_edits.py b/src/wfdb/io/_record_data_edits.py index 8fa62915..c5496380 100644 --- a/src/wfdb/io/_record_data_edits.py +++ b/src/wfdb/io/_record_data_edits.py @@ -20,6 +20,12 @@ def _selection_signals(read, arrays, indices, expanded): """Derive sample declarations from the selected current values.""" from wfdb.io import _signal + if read.source_segments and read.signals.kind == "physical": + # The flattened physical reader has no one digital declaration for + # the assembled samples; preserve that contract after selection. + return _clean_signals( + read._model.selected_header.signals[index] for index in indices + ) selected = [] for output_index, source_index in enumerate(indices): signal = read._model.selected_header.signals[source_index] @@ -124,10 +130,20 @@ def _selected_model(read, values, mask, selected, start, stop, channels): for segment in model.source_segments if segment.start < stop and segment.stop > start ) + signal_header = model.source_signal_header + if model.source_layout == "fixed": + first_name = next( + (segment.name for segment in segments if segment.name != "~"), None + ) + if first_name is not None: + signal_header = dict(getattr(model, "segment_headers", ())).get( + first_name, signal_header + ) skewed = any(signal.skew not in (None, 0) for signal in selected) return replace( model, selected_header=selected_header, + source_signal_header=signal_header, source_segments=segments, source_start=model.source_start + start, source_stop=model.source_start + stop, diff --git a/tests/test_record_data_edits.py b/tests/test_record_data_edits.py index 3e33d29d..03259d4a 100644 --- a/tests/test_record_data_edits.py +++ b/tests/test_record_data_edits.py @@ -92,6 +92,35 @@ def test_select_rebases_flattened_segments(): np.testing.assert_array_equal(selected.signals.values, direct.signals.values) +def test_flattened_physical_selection_keeps_absent_digital_declarations(): + """Flattened physical metadata matches the direct multi-segment read.""" + path = "sample-data/multi-segment/041s/041s" + selected = wfdb.read_signals( + path, layout="uniform", kind="physical", start=10, stop=20 + ).select(start=2, stop=6) + direct = wfdb.read_signals( + path, layout="uniform", kind="physical", start=12, stop=16 + ) + assert selected.metadata == direct.metadata + assert selected.metadata.channels[0].storage.checksum is None + assert selected.to_digital().metadata == direct.to_digital().metadata + + +def test_fixed_layout_selection_updates_source_signal_header(): + """A selection starting in a later segment names that segment's header.""" + path = "sample-data/multi-segment/fixed1/v102s" + read = wfdb.read_signals( + path, layout="uniform", kind="digital", start=74996, stop=75004 + ) + selected = read.select(start=5, stop=8) + direct = wfdb.read_signals( + path, layout="uniform", kind="digital", start=75001, stop=75004 + ) + assert selected.source_signal_header == direct.source_signal_header + assert selected.source_signal_header.record_name == "v102s_2" + assert selected.metadata == direct.metadata + + @pytest.mark.parametrize("kind", ["physical", "digital"]) @pytest.mark.parametrize("layout", ["uniform", "expanded"]) def test_select_matches_direct_read_metadata_and_values(tmp_path, kind, layout):