From ebd0b2bf025e4b37f3508abd7858a0dda5ae486d Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 12:55:24 -0500 Subject: [PATCH 1/2] Add validated RecordData channel and comment edits --- changelog.d/record-data-metadata-edits.rst | 8 ++ docs/io.rst | 14 +- src/wfdb/io/_record_data_edits.py | 115 ++++++++++++++++ src/wfdb/io/signal_values.py | 55 +++++++- tests/test_record_data_metadata_edits.py | 153 +++++++++++++++++++++ 5 files changed, 342 insertions(+), 3 deletions(-) create mode 100644 changelog.d/record-data-metadata-edits.rst create mode 100644 tests/test_record_data_metadata_edits.py diff --git a/changelog.d/record-data-metadata-edits.rst b/changelog.d/record-data-metadata-edits.rst new file mode 100644 index 00000000..9e7dbd4b --- /dev/null +++ b/changelog.d/record-data-metadata-edits.rst @@ -0,0 +1,8 @@ +**Edit RecordData channel labels and comments** + ``RecordData.with_channels(names=..., units=...)`` and + ``RecordData.with_comments(...)`` return independent results with validated + header text. Names may contain internal spaces and are checked for + uniqueness only when supplied, so unit corrections work on records with + duplicate source names. The selected view changes while source provenance + stays unchanged. Changing units corrects the label without rescaling + samples or changing calibration. diff --git a/docs/io.rst b/docs/io.rst index b429fca7..b540964c 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -568,7 +568,7 @@ files that either reader accepts. .. autoclass:: wfdb.io.RecordData :no-index: :members: to_physical, to_digital, to_legacy_record, select, - with_values, write + with_values, with_channels, with_comments, write .. autoclass:: wfdb.io.UniformSignals :no-index: @@ -607,11 +607,23 @@ 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. +``RecordData.with_channels(names=..., units=...)`` corrects the loaded view's +channel labels. Supply a complete sequence for each field being changed. +Names must be unique when supplied; they may contain internal spaces. WFDB's +signal description is the channel name, so there is no separate description +field. ``RecordData.with_comments([...])`` replaces the record comments. +These methods validate the supplied text immediately and return independent +arrays. They update the selected view and leave ``source_header`` unchanged. +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. + .. 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) + labeled = edited.with_channels(names=["ECG lead V5", "ECG lead II"]) + labeled = labeled.with_comments(["Reviewed for release"]) Writing a selected signal view ------------------------------ diff --git a/src/wfdb/io/_record_data_edits.py b/src/wfdb/io/_record_data_edits.py index c5496380..3060744f 100644 --- a/src/wfdb/io/_record_data_edits.py +++ b/src/wfdb/io/_record_data_edits.py @@ -2,6 +2,7 @@ import copy import operator +import re from dataclasses import replace import numpy as np @@ -308,6 +309,120 @@ def replace_record_values(read, values, missing): return _edited_result(_from_read_model(edited)) +def _text_sequence(values, field, count=None): + """Validate an entire sequence of header text values.""" + if not isinstance(values, (list, tuple)): + raise TypeError(f"{field} must be a sequence of strings") + if count is not None and len(values) != count: + raise ValueError(f"{field} must contain one value per loaded channel") + if any(not isinstance(value, str) for value in values): + raise TypeError(f"{field} must contain strings") + return tuple(values) + + +def replace_record_channel_metadata(read, names, units): + """Correct selected channel labels without changing sample calibration.""" + if names is None and units is None: + raise ValueError("Pass names or units to with_channels") + count = read.metadata.n_signals + if names is not None: + names = _text_sequence(names, "names", count) + if any( + not name or name != name.strip() or re.search(r"[\x00-\x1f\x7f-\x9f]", name) + for name in names + ): + raise ValueError( + "channel names must be nonempty, with no surrounding " + "whitespace or control characters" + ) + if len(set(names)) != len(names): + raise ValueError("channel names must be unique") + if units is not None: + units = _text_sequence(units, "units", count) + if any(not unit or re.search(r"\s", unit) for unit in units): + raise ValueError("units must be nonempty and contain no whitespace") + return _replace_record_text(read, names=names, units=units) + + +def replace_record_comments(read, comments): + """Replace selected-view comments after validating header line safety.""" + comments = _text_sequence(comments, "comments") + if any(re.search(r"[\t\n\r\f\v]", comment) for comment in comments): + raise ValueError("comments may not contain tabs or line breaks") + return _replace_record_text(read, comments=comments) + + +def _replace_record_text(read, *, names=None, units=None, comments=None): + """Copy arrays and change only the selected view's header text.""" + model = read._model + expanded = isinstance(read.signals, ExpandedSignals) + if read.signals.kind == "digital": + values, mask = _copy_digital(read.signals.values, expanded) + else: + current = read.signals.values + values = ( + tuple(value.copy() for value in current) if expanded else current.copy() + ) + mask = None + if model is None: + from wfdb.io.signal_values import _from_record + + record = copy.copy(read._record) + for field, value in vars(record).items(): + if isinstance(value, list): + setattr(record, field, value.copy()) + if names is not None: + record.sig_name = list(names) + if units is not None: + record.units = list(units) + if comments is not None: + record.comments = list(comments) + field = ("e_" if expanded else "") + ( + "p_signal" if read.signals.kind == "physical" else "d_signal" + ) + setattr(record, field, list(values) if expanded else values) + result = _from_record( + record, + read.signals.kind, + expanded, + mask=mask, + write_formats=read._write_formats, + ) + else: + selected = tuple( + replace( + signal, + sig_name=signal.sig_name if names is None else names[index], + units=signal.units if units is None else units[index], + ) + for index, signal in enumerate(model.selected_header.signals) + ) + selected_comments = ( + model.selected_header.comments if comments is None else comments + ) + header = replace( + model.selected_header, signals=selected, comments=selected_comments + ) + metadata = _metadata_for_view( + header.record_fields, + selected, + selected_comments, + model.kind, + "expanded" if expanded else "uniform", + ) + result = _from_read_model( + replace( + model, + selected_header=header, + values=values, + mask=mask, + metadata=metadata, + ) + ) + object.__setattr__(result, "_edited_values", getattr(read, "_edited_values", False)) + return result + + 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 diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index c0b3fcf9..a0ba2f89 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -85,8 +85,9 @@ class RecordData: segments. Conversions return another ``RecordData`` and leave this one unchanged. Use ``write`` to save the selected values. 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. + ``select``, ``with_values``, ``with_channels``, and ``with_comments`` for + validated edits; ``dataclasses.replace`` cannot construct a complete + result with source provenance. """ signals: UniformSignals | ExpandedSignals @@ -329,6 +330,56 @@ def with_values(self, values, *, missing: str | None = None) -> "RecordData": return replace_record_values(self, values, missing) + def with_channels( + self, + *, + names: list[str] | tuple[str, ...] | None = None, + units: list[str] | tuple[str, ...] | None = None, + ) -> "RecordData": + """Return a copy with corrected channel names or unit labels. + + Each supplied sequence must contain one value per loaded channel. + WFDB's signal description is exposed as the channel name; there is + no separate description field. Unit changes correct the label only: + they do not rescale samples or change gain and baseline. The original + source header remains available as provenance. + + Parameters + ---------- + names : sequence of str, optional + Complete, unique channel names. Internal spaces are allowed. + units : sequence of str, optional + Complete unit labels with no whitespace. + + Returns + ------- + RecordData + An independent result with the corrected channel metadata. + """ + from wfdb.io._record_data_edits import replace_record_channel_metadata + + return replace_record_channel_metadata(self, names, units) + + def with_comments(self, comments: list[str] | tuple[str, ...]) -> "RecordData": + """Return a copy with replacement record comments. + + The comments belong to the selected view. The source header remains + available as provenance, and the signal arrays are copied. + + Parameters + ---------- + comments : sequence of str + Complete replacement comments, without line breaks or tabs. + + Returns + ------- + RecordData + An independent result with the replacement comments. + """ + from wfdb.io._record_data_edits import replace_record_comments + + return replace_record_comments(self, comments) + def write( self, path: str | os.PathLike, diff --git a/tests/test_record_data_metadata_edits.py b/tests/test_record_data_metadata_edits.py new file mode 100644 index 00000000..d03589a7 --- /dev/null +++ b/tests/test_record_data_metadata_edits.py @@ -0,0 +1,153 @@ +"""Validated channel and comment edits on selected RecordData views.""" + +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_channel_and_comment_edits_round_trip(tmp_path, kind, layout): + """Edited text is written while values and source provenance are retained.""" + original = wfdb.read_signals("sample-data/100", kind=kind, layout=layout, stop=8) + edited = original.with_channels( + names=["ECG lead II", "ECG lead V5"], units=["uV", "uV"] + ).with_comments(["Reviewed for release", "Units corrected"]) + assert [signal.name for signal in edited.metadata.signals] == [ + "ECG lead II", + "ECG lead V5", + ] + assert [signal.units for signal in edited.metadata.signals] == ["uV", "uV"] + assert edited.metadata.comments == ("Reviewed for release", "Units corrected") + assert edited.source_header == original.source_header + assert edited.source_selection == original.source_selection + assert original.metadata.comments != edited.metadata.comments + assert original.metadata.signals[0].name != edited.metadata.signals[0].name + + original_arrays = ( + original.signals.values if layout == "expanded" else (original.signals.values,) + ) + edited_arrays = ( + edited.signals.values if layout == "expanded" else (edited.signals.values,) + ) + for source, result in zip(original_arrays, edited_arrays): + np.testing.assert_array_equal(result, source) + assert not np.shares_memory(result, source) + if kind == "digital": + np.testing.assert_array_equal( + np.ma.getmaskarray(result), np.ma.getmaskarray(source) + ) + + converted = edited.to_digital() if kind == "physical" else edited.to_physical() + reference = original.to_digital() if kind == "physical" else original.to_physical() + converted_arrays = ( + converted.signals.values + if layout == "expanded" + else (converted.signals.values,) + ) + reference_arrays = ( + reference.signals.values + if layout == "expanded" + else (reference.signals.values,) + ) + for actual, expected in zip(converted_arrays, reference_arrays): + np.testing.assert_array_equal(actual, expected) + assert converted.metadata.signals[0].name == "ECG lead II" + assert converted.metadata.signals[0].units == "uV" + + edited.write(tmp_path / "edited") + restored = wfdb.read_signals(tmp_path / "edited", kind=kind, layout=layout) + assert [signal.name for signal in restored.metadata.signals] == [ + "ECG lead II", + "ECG lead V5", + ] + assert [signal.units for signal in restored.metadata.signals] == ["uV", "uV"] + assert restored.metadata.comments == edited.metadata.comments + + +def test_units_can_be_fixed_when_source_names_are_duplicate(tmp_path): + """Only a supplied names sequence needs to pass uniqueness validation.""" + values = np.arange(16, dtype=" Date: Fri, 4 Dec 2026 13:04:56 -0500 Subject: [PATCH 2/2] Reject metadata edits the current header reader changes --- changelog.d/record-data-metadata-edits.rst | 8 ++- docs/io.rst | 7 ++- src/wfdb/io/_record_data_edits.py | 11 ++++ src/wfdb/io/signal_values.py | 8 ++- tests/test_record_data_metadata_edits.py | 64 ++++++++++++++++++++++ 5 files changed, 90 insertions(+), 8 deletions(-) diff --git a/changelog.d/record-data-metadata-edits.rst b/changelog.d/record-data-metadata-edits.rst index 9e7dbd4b..a7f688c9 100644 --- a/changelog.d/record-data-metadata-edits.rst +++ b/changelog.d/record-data-metadata-edits.rst @@ -1,8 +1,10 @@ **Edit RecordData channel labels and comments** ``RecordData.with_channels(names=..., units=...)`` and ``RecordData.with_comments(...)`` return independent results with validated - header text. Names may contain internal spaces and are checked for - uniqueness only when supplied, so unit corrections work on records with - duplicate source names. The selected view changes while source provenance + printable ASCII header text. Comments cannot begin or end with spaces or + ``#`` because the current reader strips them. Names may contain internal + spaces; uniqueness is checked only when names are supplied, so unit + corrections work on records with duplicate source names. The selected view + changes while source provenance stays unchanged. Changing units corrects the label without rescaling samples or changing calibration. diff --git a/docs/io.rst b/docs/io.rst index b540964c..f5c89171 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -612,8 +612,11 @@ channel labels. Supply a complete sequence for each field being changed. Names must be unique when supplied; they may contain internal spaces. WFDB's signal description is the channel name, so there is no separate description field. ``RecordData.with_comments([...])`` replaces the record comments. -These methods validate the supplied text immediately and return independent -arrays. They update the selected view and leave ``source_header`` unchanged. +These methods accept printable ASCII text that the current header reader can +return unchanged. Comments cannot begin or end with spaces or ``#`` because +the current parser strips them. They validate supplied text immediately and +return independent arrays. They update the selected view and leave +``source_header`` unchanged. 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. diff --git a/src/wfdb/io/_record_data_edits.py b/src/wfdb/io/_record_data_edits.py index 3060744f..de366963 100644 --- a/src/wfdb/io/_record_data_edits.py +++ b/src/wfdb/io/_record_data_edits.py @@ -320,6 +320,12 @@ def _text_sequence(values, field, count=None): return tuple(values) +def _require_printable_ascii(values): + """Reject header text that the current reader would silently change.""" + if any(not value.isascii() or not value.isprintable() for value in values): + raise ValueError("WFDB header text must be printable ASCII") + + def replace_record_channel_metadata(read, names, units): """Correct selected channel labels without changing sample calibration.""" if names is None and units is None: @@ -337,10 +343,12 @@ def replace_record_channel_metadata(read, names, units): ) if len(set(names)) != len(names): raise ValueError("channel names must be unique") + _require_printable_ascii(names) if units is not None: units = _text_sequence(units, "units", count) if any(not unit or re.search(r"\s", unit) for unit in units): raise ValueError("units must be nonempty and contain no whitespace") + _require_printable_ascii(units) return _replace_record_text(read, names=names, units=units) @@ -349,6 +357,9 @@ def replace_record_comments(read, comments): comments = _text_sequence(comments, "comments") if any(re.search(r"[\t\n\r\f\v]", comment) for comment in comments): raise ValueError("comments may not contain tabs or line breaks") + if any(comment != comment.strip(" #") for comment in comments): + raise ValueError("comments must not start or end with spaces or '#'") + _require_printable_ascii(comments) return _replace_record_text(read, comments=comments) diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index a0ba2f89..72652e86 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -347,9 +347,10 @@ def with_channels( Parameters ---------- names : sequence of str, optional - Complete, unique channel names. Internal spaces are allowed. + Complete, unique channel names in printable ASCII. Internal + spaces are allowed. units : sequence of str, optional - Complete unit labels with no whitespace. + Complete unit labels in printable ASCII, with no whitespace. Returns ------- @@ -369,7 +370,8 @@ def with_comments(self, comments: list[str] | tuple[str, ...]) -> "RecordData": Parameters ---------- comments : sequence of str - Complete replacement comments, without line breaks or tabs. + Complete replacement comments in printable ASCII, without line + breaks, tabs, or leading or trailing spaces or ``#`` characters. Returns ------- diff --git a/tests/test_record_data_metadata_edits.py b/tests/test_record_data_metadata_edits.py index d03589a7..11485d95 100644 --- a/tests/test_record_data_metadata_edits.py +++ b/tests/test_record_data_metadata_edits.py @@ -112,6 +112,70 @@ def test_invalid_metadata_edits_fail_when_called(): read.with_comments("one comment") +@pytest.mark.parametrize( + ("field", "text"), + [ + ("names", "ECG lead II"), + ("names", "a:b"), + ("names", "#x"), + ("names", "200/mV"), + ("names", "A" * 300), + ("units", "mV/s"), + ("units", "uV(x)"), + ("units", "%"), + ("units", "a:b"), + ("units", "m#V"), + ("units", "("), + ("units", "mV)"), + ], +) +def test_printable_header_text_round_trips(tmp_path, field, text): + """Accepted punctuation and internal spaces survive writing and reading.""" + read = wfdb.read_signals("sample-data/100", layout="uniform", stop=4) + other = "V5" if field == "names" else "mV" + edited = read.with_channels(**{field: [text, other]}) + edited.write(tmp_path / "edited") + restored = wfdb.read_signals(tmp_path / "edited", layout="uniform") + actual = ( + restored.metadata.signals[0].name + if field == "names" + else restored.metadata.signals[0].units + ) + assert actual == text + + +def test_comment_with_internal_hash_round_trips(tmp_path): + """An internal hash is preserved even though edge hashes are stripped.""" + read = wfdb.read_signals("sample-data/100", layout="uniform", stop=4) + read.with_comments(["Reviewed #1"]).write(tmp_path / "edited") + restored = wfdb.read_signals(tmp_path / "edited", layout="uniform") + assert restored.metadata.comments == ("Reviewed #1",) + + +@pytest.mark.parametrize( + ("method", "value", "message"), + [ + ("names", "é ü", "printable ASCII"), + ("names", "a\u00a0b", "printable ASCII"), + ("units", "°C", "printable ASCII"), + ("comments", "é unicode", "printable ASCII"), + ("comments", " leading space", "start or end"), + ("comments", "#hash", "start or end"), + ("comments", "trailing space ", "start or end"), + ("comments", "trailing#", "start or end"), + ], +) +def test_text_lost_by_reader_is_rejected(method, value, message): + """Validation does not accept text that the current parser changes.""" + read = wfdb.read_signals("sample-data/100", layout="uniform", stop=4) + with pytest.raises(ValueError, match=message): + if method == "comments": + read.with_comments([value]) + else: + other = "V5" if method == "names" else "mV" + read.with_channels(**{method: [value, other]}) + + def test_metadata_edits_keep_segment_provenance_and_prior_value_edits(tmp_path): """Metadata-only edits preserve segment mappings and edit state.""" read = wfdb.read_signals(