diff --git a/changelog.d/record-data-metadata-edits.rst b/changelog.d/record-data-metadata-edits.rst new file mode 100644 index 00000000..a7f688c9 --- /dev/null +++ b/changelog.d/record-data-metadata-edits.rst @@ -0,0 +1,10 @@ +**Edit RecordData channel labels and comments** + ``RecordData.with_channels(names=..., units=...)`` and + ``RecordData.with_comments(...)`` return independent results with validated + 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 b429fca7..f5c89171 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,26 @@ 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 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. + .. 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..de366963 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,131 @@ 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 _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: + 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") + _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) + + +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") + 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) + + +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..72652e86 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,58 @@ 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 in printable ASCII. Internal + spaces are allowed. + units : sequence of str, optional + Complete unit labels in printable ASCII, 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 in printable ASCII, without line + breaks, tabs, or leading or trailing spaces or ``#`` characters. + + 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..11485d95 --- /dev/null +++ b/tests/test_record_data_metadata_edits.py @@ -0,0 +1,217 @@ +"""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="