From 1fa307c13664f3cfe5eb5cc681915dbf28b5156f Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 13:27:02 -0500 Subject: [PATCH] Accept RecordData in write_record --- changelog.d/write-record-data.rst | 6 + docs/io.rst | 48 ++++---- src/wfdb/io/record.py | 46 ++++++-- tests/test_write_record_data.py | 190 ++++++++++++++++++++++++++++++ 4 files changed, 257 insertions(+), 33 deletions(-) create mode 100644 changelog.d/write-record-data.rst create mode 100644 tests/test_write_record_data.py diff --git a/changelog.d/write-record-data.rst b/changelog.d/write-record-data.rst new file mode 100644 index 00000000..19061a40 --- /dev/null +++ b/changelog.d/write-record-data.rst @@ -0,0 +1,6 @@ +**Write RecordData with write_record** + ``write_record(path, data)`` now accepts ``RecordData`` and produces the + same files as ``data.write(path)``. Both forms accept ``signal_alignment`` + and ``formats`` for this type. ``kind`` and ``layout`` continue to select + loaded forms only for mutable ``Record`` objects. Existing ``Record`` + writing behavior is unchanged. diff --git a/docs/io.rst b/docs/io.rst index 6c822fe7..8ec6ec75 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -144,11 +144,12 @@ names retain their existing behavior. assert record.sig_name[0] == "ECG" ``write_record(path, record)`` writes the current values of a single-segment -``Record`` to a destination stem or local ``.wfdb`` archive. It writes a -selected or flattened read as one record. When the object holds more than one -signal form, use ``kind`` and ``layout`` to choose which one to write. The -original object is unchanged. ``record.write(path, kind=..., layout=...)`` -uses the same writer with the record as its receiver. +``Record`` or ``RecordData`` to a destination stem or local ``.wfdb`` archive. +For a ``Record``, it writes a selected or flattened read as one record. +When a ``Record`` holds more than one signal form, use ``kind`` and ``layout`` +to choose which one to write. The original object is unchanged. +``record.write(path, kind=..., layout=...)`` uses the same writer with the +record as its receiver. Before writing, it checks that ``n_sig`` (when set), the selected signal array, and retained per-channel header fields agree on the channel count. A mismatch raises ``ValueError`` listing every mismatched field and suggests using @@ -158,6 +159,12 @@ When several arrays are loaded, ``kind`` and ``layout`` select the one whose channel count is checked. If ``n_sig`` is unset, the writer fills it on its copy from that array. +For ``RecordData``, ``write_record(path, data)`` calls ``data.write(path)``. +Both accept ``signal_alignment`` and ``formats`` and produce the same files. +``kind`` and ``layout`` apply only to ``Record`` because ``RecordData`` +already holds one signal form. ``formats`` applies only to ``RecordData``; +a mutable ``Record`` uses its ``fmt`` field. + ``write_signals(path, values, ...)`` writes a new single-segment record from arrays, without first constructing a ``Record``. It requires ``kind`` and ``formats`` explicitly. A 2D array is uniform; a sequence of 1D arrays is @@ -643,13 +650,14 @@ Writing a selected signal view ------------------------------ ``RecordData.write(path)`` writes the selected frames, channels, and current -signal values to a new record stem or local ``.wfdb`` archive. It accepts the -same writable cloud destinations as ``Record.wrsamp`` for separate WFDB files; -cloud ``.wfdb`` archives and ``physionet://`` writes are unsupported. The -local parent directory must already exist. The destination basename becomes -the new record name, and the signal files are renamed while keeping their -channel grouping. Source byte offsets are dropped because the new files do -not need the original padding. The source ``RecordData`` is unchanged. +signal values to a new record stem or local ``.wfdb`` archive. It has the same +options and output as ``write_record(path, data)`` for that ``RecordData``. +It accepts the same writable cloud destinations as ``Record.wrsamp`` for +separate WFDB files; cloud ``.wfdb`` archives and ``physionet://`` writes are +unsupported. The local parent directory must already exist. The destination +basename becomes the new record name. Signal files are renamed while keeping +their channel grouping. Source byte offsets are dropped because the new files +do not need the original padding. The source ``RecordData`` is unchanged. The round-trip promise is about the logical data. A digital read written in the same format retains its sample values. Physical values are subject to @@ -1058,14 +1066,14 @@ URI to a reader for remote records. Legacy ``wrsamp`` and ``wrann`` put files in ``write_dir`` using the record name supplied to the writer. ``write_record(path, record)`` takes a complete -record stem or local archive path and writes a single-segment ``Record`` as it -currently exists in memory. ``write_signals(path, values, ...)`` writes a new -single-segment record from arrays. ``write_annotations(path, annotation)`` takes a -complete annotation filename and writes the supplied ``Annotation`` without -changing it. ``Record.write`` and ``Annotation.write`` provide method forms -of these functions. A ``RecordData`` can instead call ``write(path)`` with a -complete destination stem, cloud URI, or local archive path. ``physionet://`` writes -and cloud archives are unsupported. +record stem or local archive path and writes a single-segment ``Record`` or +``RecordData`` as it currently exists in memory. ``write_signals`` writes a +new single-segment record from arrays. ``write_annotations(path, annotation)`` +takes a complete annotation filename and writes the supplied ``Annotation`` +without changing it. ``Record.write`` and ``Annotation.write`` provide method +forms of these functions. A ``RecordData`` can also call ``write(path)`` with +a complete destination stem, cloud URI, or local archive path. +``physionet://`` writes and cloud archives are unsupported. See :ref:`wfdb-archives`, :ref:`cloud-storage-access`, and :ref:`reading-from-physionet` for details and examples. diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index fcb6ffec..154c43df 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -38,6 +38,7 @@ _from_parsed_header, ) from wfdb.io.metadata import RecordMetadata, _from_record +from wfdb.io.signal_values import RecordData # -------------- WFDB Signal Calibration and Classification ---------- # @@ -6011,13 +6012,14 @@ def _require_signal_alignment(record: Record, alignment: str | None) -> None: def write_record( path: str | os.PathLike[str], - record: Record, + record: Record | RecordData, *, kind: str | None = None, layout: str | None = None, signal_alignment: str | None = None, + formats: str | tuple[str, ...] | list[str] | None = None, ) -> None: - """Write the current values of a single-segment ``Record`` to ``path``. + """Write the current values of a ``Record`` or ``RecordData`` to ``path``. The destination is a local record stem, a supported cloud URI, or a local ``.wfdb`` archive path. A selected or flattened record is written as its @@ -6030,16 +6032,22 @@ def write_record( path : str or os.PathLike Output record stem without ``.hea`` or ``.dat``, or a local ``.wfdb`` archive path. - record : Record - The loaded, single-segment record to write. + record : Record or RecordData + The loaded record view to write. A ``RecordData`` uses the same + behavior as its ``write`` method. kind : {"physical", "digital"}, optional - Signal kind to write when needed to select one loaded form. + Signal kind to write when needed to select one loaded form of a + ``Record``. Not accepted for ``RecordData``. layout : {"uniform", "expanded"}, optional - Signal layout to write when needed to select one loaded form. + Signal layout to write when needed to select one loaded form of a + ``Record``. Not accepted for ``RecordData``. signal_alignment : {"aligned", "raw"}, optional Alignment of the selected values. Required when any channel has nonzero skew. This does not shift samples or change ``record``. Either value has no effect when the record has no skew. + formats : str or sequence of str, optional + Target storage format for all channels or one format per channel of + ``RecordData``. Not accepted for ``Record``; use its ``fmt`` field. Returns ------- @@ -6047,12 +6055,14 @@ def write_record( Notes ----- - Digital values are written directly. Physical values are converted to - digital samples and may differ after reading because of quantization. - Missing calibration and header defaults are calculated for physical values. - Digital values require ``fmt``, ``adc_gain``, and ``baseline``. Source - byte offsets are not copied to the new file. This function does not promise - byte-for-byte reproduction of source files. If ``n_sig`` is set, it must + ``RecordData`` and its ``write`` method produce identical files. For a + ``Record``, digital values are written directly. Physical values are + converted to digital samples and may differ after reading because of + quantization. Missing calibration and header defaults are calculated for + physical values. + Digital values require a storage format, ``adc_gain``, and ``baseline``. + Source byte offsets are not copied to the new file. This function does not + promise byte-for-byte reproduction of source files. If ``n_sig`` is set, it must match the selected signal array's channel count. Retained per-channel header fields must have that same number of entries. A ``ValueError`` lists all mismatches before any files are written. ``byte_offset`` is @@ -6077,10 +6087,20 @@ def write_record( needed to preserve alignment. Read the full source or clear skew first. """ + if isinstance(record, RecordData): + if kind is not None or layout is not None: + raise ValueError( + "kind and layout apply only to Record; RecordData already " + "has one signal kind and layout" + ) + record.write(path, signal_alignment=signal_alignment, formats=formats) + return if isinstance(record, MultiRecord): raise TypeError("write_record does not yet support MultiRecord") if not isinstance(record, Record): - raise TypeError("record must be a Record") + raise TypeError("record must be a Record or RecordData") + if formats is not None: + raise TypeError("formats applies only to RecordData; edit Record.fmt instead") if kind not in (None, "physical", "digital"): raise ValueError("kind must be 'physical' or 'digital'") if layout not in (None, "uniform", "expanded"): diff --git a/tests/test_write_record_data.py b/tests/test_write_record_data.py new file mode 100644 index 00000000..685d42f2 --- /dev/null +++ b/tests/test_write_record_data.py @@ -0,0 +1,190 @@ +"""The function and method forms of writing RecordData agree.""" + +import datetime +import pickle +from pathlib import Path + +import numpy as np +import pytest + +import wfdb + + +def _same_written_bytes(tmp_path, data, **options): + """Write the same basename through both public routes and compare files.""" + method_dir = tmp_path / "method" + function_dir = tmp_path / "function" + method_dir.mkdir() + function_dir.mkdir() + assert data.write(method_dir / "copy", **options) is None + assert wfdb.write_record(function_dir / "copy", data, **options) is None + method_files = {path.name: path.read_bytes() for path in method_dir.iterdir()} + function_files = {path.name: path.read_bytes() for path in function_dir.iterdir()} + assert function_files == method_files + return function_dir / "copy" + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_function_matches_method_for_single_segment(tmp_path, kind, layout): + """The same selected values produce byte-identical files.""" + data = wfdb.read_signals( + "sample-data/100", kind=kind, layout=layout, start=10, stop=18 + ) + _same_written_bytes(tmp_path, data) + + +def _dated_data(tmp_path): + """Create a short digital record whose time can be edited.""" + path = tmp_path / "source" + wfdb.write_signals( + path, + np.arange(8, dtype=np.int16).reshape(4, 2), + fs=2, + kind="digital", + formats="16", + channel_names=["I", "II"], + units=["mV", "mV"], + adc_gain=[200, 200], + baseline=[0, 0], + missing="none", + base_date=datetime.date(2020, 5, 6), + base_time=datetime.time(12, 0), + ) + return wfdb.read_signals(path, kind="digital", layout="uniform") + + +@pytest.mark.parametrize("edit", ["select", "values", "channels", "comments", "time"]) +def test_function_matches_method_after_each_edit(tmp_path, edit): + """Every validated edit reaches the same write path.""" + data = _dated_data(tmp_path) + if edit == "select": + data = data.select(start=1, stop=3, channels=[1, 0]) + elif edit == "values": + values = data.signals.values.copy() + values[0, 0] += 1 + data = data.with_values(values) + elif edit == "channels": + data = data.with_channels(names=["Lead I", "Lead II"]) + elif edit == "comments": + data = data.with_comments(["Reviewed"]) + else: + data = data.shift_time(datetime.timedelta(days=3, microseconds=17)) + _same_written_bytes(tmp_path, data) + + +@pytest.mark.parametrize("conversion", ["physical", "digital"]) +def test_function_matches_method_after_conversion(tmp_path, conversion): + """The selected kind is taken from RecordData itself.""" + data = _dated_data(tmp_path) + data = data.to_physical() if conversion == "physical" else data.to_digital() + _same_written_bytes(tmp_path, data) + + +@pytest.mark.parametrize("alignment", ["aligned", "raw"]) +def test_function_matches_method_for_skew(tmp_path, alignment): + """Both entry points require the same explicit alignment choice.""" + data = wfdb.read_signals( + "sample-data/test01_00s_skew", + kind="digital", + layout="uniform", + signal_alignment=alignment, + stop=20 if alignment == "aligned" else None, + ) + with pytest.raises(ValueError, match="requires signal_alignment"): + wfdb.write_record(tmp_path / "without_alignment", data) + assert not (tmp_path / "without_alignment.hea").exists() + _same_written_bytes(tmp_path, data, signal_alignment=alignment) + + +def test_function_matches_method_for_flattened_segments(tmp_path): + """A combined multi-segment view is written as one record.""" + data = wfdb.read_signals( + "sample-data/multi-segment/fixed1/v102s", + kind="digital", + layout="uniform", + start=74996, + stop=75004, + ) + _same_written_bytes(tmp_path, data) + + +@pytest.mark.parametrize( + "fixture", ["physical_uniform", "digital_expanded", "digital_multi_segment"] +) +def test_function_matches_method_for_old_pickles(tmp_path, fixture): + """The wrapper also handles reads saved by wfdb 5.17.0.""" + path = Path(__file__).parent / "fixtures" / "signal_read_v5_17" / f"{fixture}.pkl" + data = pickle.loads(path.read_bytes()) + _same_written_bytes(tmp_path, data) + + +def test_formats_and_missing_mask_use_same_validation(tmp_path): + """A format override preserves digital gaps in both entry points.""" + source = tmp_path / "source" + values = np.ma.array( + np.array([[1], [2], [3]], dtype=np.int16), + mask=[[False], [True], [False]], + ) + wfdb.write_signals( + source, + values, + fs=125, + kind="digital", + formats="16", + channel_names=["I"], + units=["mV"], + adc_gain=[200], + baseline=[0], + ) + data = wfdb.read_signals(source, kind="digital", layout="uniform") + written = _same_written_bytes(tmp_path, data, formats="24") + restored = wfdb.read_signals(written, kind="digital", layout="uniform") + np.testing.assert_array_equal( + restored.signals.values.mask, data.signals.values.mask + ) + np.testing.assert_array_equal( + restored.signals.values.compressed(), data.signals.values.compressed() + ) + + +def test_future_read_record_write_record_round_trip(tmp_path): + """The 6.0 pair will preserve selected digital values and logical metadata.""" + original = wfdb.read_signals( + "sample-data/100", + kind="digital", + layout="uniform", + start=10, + stop=18, + ) + destination = tmp_path / "copy" + wfdb.write_record(destination, original) + restored = wfdb.read_signals(destination, kind="digital", layout="uniform") + np.testing.assert_array_equal(restored.signals.values, original.signals.values) + np.testing.assert_array_equal( + np.ma.getmaskarray(restored.signals.values), + np.ma.getmaskarray(original.signals.values), + ) + assert restored.metadata.n_frames == original.metadata.n_frames + assert restored.metadata.n_signals == original.metadata.n_signals + assert restored.metadata.fs == original.metadata.fs + assert restored.metadata.signals == original.metadata.signals + assert restored.metadata.comments == original.metadata.comments + assert restored.metadata.base_date == original.metadata.base_date + assert restored.metadata.base_time == original.metadata.base_time + for actual, expected in zip(restored.metadata.channels, original.metadata.channels): + assert (actual.storage.checksum - expected.storage.checksum) % 65536 == 0 + + +def test_record_data_rejects_record_only_options_before_writing(tmp_path): + """kind and layout choose a form only when writing a mutable Record.""" + data = wfdb.read_signals( + "sample-data/100", kind="digital", layout="uniform", stop=4 + ) + for option in ({"kind": "digital"}, {"layout": "uniform"}): + with pytest.raises(ValueError, match="apply only to Record"): + wfdb.write_record(tmp_path / "wrong", data, **option) + assert not (tmp_path / "wrong.hea").exists() + with pytest.raises(TypeError, match="applies only to RecordData"): + wfdb.write_record(tmp_path / "legacy", data.to_legacy_record(), formats="16") + assert not (tmp_path / "legacy.hea").exists()