Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions changelog.d/record-data-metadata-edits.rst
Original file line number Diff line number Diff line change
@@ -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.
17 changes: 16 additions & 1 deletion docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
------------------------------
Expand Down
126 changes: 126 additions & 0 deletions src/wfdb/io/_record_data_edits.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import copy
import operator
import re
from dataclasses import replace

import numpy as np
Expand Down Expand Up @@ -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
Expand Down
57 changes: 55 additions & 2 deletions src/wfdb/io/signal_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading