diff --git a/README.md b/README.md index 11203918..2a56cde2 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ record = wfdb.read_record("path/to/record", layout="uniform") | Read a selected, combined record | `read_record` | | Inspect a header without loading samples | `read_header` | | Keep a multi-segment record's boundaries | `read_segments` | +| Write a multi-segment record with its boundaries | `write_segments` | | Read an annotation file | `read_annotations` | | Plot signals and annotations | `record.plot(annotation=...)` | | Write a loaded record or an array | `write_record` or `write_signals` | @@ -95,6 +96,22 @@ selected = record.select(start=0, stop=1000) wfdb.write_record("selected", selected) ``` +To keep the boundaries of a multi-segment record, read and write its +segments instead. This also preserves gaps between segments: + +```python +segments = wfdb.read_segments( + "path/to/multi-segment-record", layout="uniform", start=0, stop=1000 +) +segments.write("selected-segments") +# Equivalent: wfdb.write_segments("selected-segments", segments) +``` + +If the source uses a format that cannot be written, pass a target format such +as `formats="16"`. You can also pass one format per selected channel in master +channel order. A fixed-layout selection needs at least one data segment to +define its channels; a window containing only gaps cannot be written. + Use `write_signals` to create a single-segment record from arrays. In that case, supply the sampling frequency, value kind, storage format, channel names, and units: diff --git a/changelog.d/write-segments.rst b/changelog.d/write-segments.rst new file mode 100644 index 00000000..a608f56d --- /dev/null +++ b/changelog.d/write-segments.rst @@ -0,0 +1,12 @@ +**Write selected multi-segment records** + New ``write_segments`` and ``SegmentedRecordData.write`` write fixed- and + variable-layout records from loaded segments without a legacy + ``MultiRecord``. They preserve boundaries and ``~`` gaps, generate distinct + destination segment names, and stage files before replacing local output. + A real segment with no selected channels becomes a ``~`` gap of the same + length, so its original name and header are not included in the new record. + Segment and layout headers take their start times, including dates, from + the selected master. ``formats`` chooses a writable storage format for + every channel, or one per selected channel in master order. A fixed-layout + selection containing only gaps is rejected, because no data segment would + define its channels. diff --git a/docs/io.rst b/docs/io.rst index d2fbd226..37085655 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -12,7 +12,7 @@ WFDB Records :members: rdrecord, read_record, write_record, write_signals, find_record, wfdb_search_path, rdheader, read_header, read_multi_segment_headers, read_channel_header, - read_segments, iter_dataframes, + read_segments, write_segments, iter_dataframes, rdsamp, wrsamp, sampfreq, signame, wfdbdesc, wfdbtime @@ -818,6 +818,27 @@ frame count, signal kind and layout, sampling frequency, and channel mapping. times together, while keeping source headers as provenance. Call ``segments.plot()`` to show all loaded entries on one master-record timeline, with segment boundaries marked and gaps shaded. +Use ``write_segments(path, segments)`` or ``segments.write(path)`` to write the +selected view as a new multi-segment record. The output starts at frame zero +and uses generated segment names such as ``record_0001``. The writer preserves +boundaries and ``~`` gaps; a real segment with no selected channels becomes a +``~`` gap of the same length. The selected master metadata supplies the output +start time, while source headers remain provenance. This writer accepts local +record stems, supported writable cloud URIs, and local ``.wfdb`` archives. +It stages every file before replacing a local destination. Segment and layout +headers take their start times, including dates, from the selected master. +Pass ``formats="16"`` for every channel, or one format per selected channel in +master order, when a source format cannot be written or loaded segments do not +establish one format; each segment receives its own channels' formats. A +fixed-layout selection containing only ``~`` gaps is rejected because no data +segment would define its channels. + +For example, write a selected window while keeping its segment boundaries:: + + segments = wfdb.read_segments( + "path/to/multi-segment-record", layout="uniform", start=0, stop=1000 + ) + segments.write("selected-segments") .. autoclass:: wfdb.io.SegmentedRecordData :no-index: diff --git a/src/wfdb/__init__.py b/src/wfdb/__init__.py index e8d88ae2..7cb4207c 100644 --- a/src/wfdb/__init__.py +++ b/src/wfdb/__init__.py @@ -1,3 +1,4 @@ +from wfdb.io._segment_write import write_segments from wfdb.io.annotation import ( Annotation, merge_annotations, diff --git a/src/wfdb/io/__init__.py b/src/wfdb/io/__init__.py index fcd30407..f4966547 100644 --- a/src/wfdb/io/__init__.py +++ b/src/wfdb/io/__init__.py @@ -1,3 +1,4 @@ +from wfdb.io._segment_write import write_segments from wfdb.io._signal import est_res, wr_dat_file from wfdb.io.annotation import ( Annotation, diff --git a/src/wfdb/io/_segment_write.py b/src/wfdb/io/_segment_write.py new file mode 100644 index 00000000..61a3a23b --- /dev/null +++ b/src/wfdb/io/_segment_write.py @@ -0,0 +1,334 @@ +"""Write a selected multi-segment view without a legacy MultiRecord.""" + +from __future__ import annotations + +import datetime +import os +import re +import tempfile +import warnings + +from wfdb._warnings import _caller_stacklevel +from wfdb.io import _header +from wfdb.io._cloud import check_cloud_write, is_cloud_path, staged_cloud_write +from wfdb.io._coreio import _fsspec_open, _join_path, _split_path +from wfdb.io._read_model import _adjust_time +from wfdb.io._record_data_edits import _replace_record_metadata +from wfdb.io.archive import WFDBArchive, is_archive_path +from wfdb.io.record import _move_files_into_place +from wfdb.io.segment_values import SegmentedRecordData + + +def _validate_selected_segments(data: SegmentedRecordData) -> None: + """Check the current entries and master fields before any output exists.""" + metadata = data.metadata + if metadata.kind not in ("physical", "digital") or metadata.signal_layout not in ( + "uniform", + "expanded", + ): + raise ValueError( + "Cannot write a segmented read without known signal kind and layout" + ) + if ( + metadata.n_signals < 1 + or len(data.source_selection.channels) != metadata.n_signals + ): + raise ValueError("Selected master must have at least one channel") + if ( + any( + not isinstance(name, str) + or not name + or name.strip() != name + or not name.isprintable() + for name in metadata.channel_names + ) + or len(set(metadata.channel_names)) != metadata.n_signals + ): + raise ValueError( + "Selected master channel names must be printable, nonempty, and unique" + ) + if len(metadata.samples_per_frame) != metadata.n_signals or any( + isinstance(spf, bool) or not isinstance(spf, int) or spf < 1 + for spf in metadata.samples_per_frame + ): + raise ValueError("Selected master samples per frame must match channels") + if any( + not isinstance(comment, str) or not comment.isprintable() + for comment in metadata.comments + ): + raise ValueError("Selected master comments must be printable text") + if data.layout not in ("fixed", "variable"): + raise ValueError("Segmented record layout must be fixed or variable") + if metadata.n_frames != data.source_selection.stop - data.source_selection.start: + raise ValueError("Selected master frame count does not match its source range") + if not data.segments: + raise ValueError("Selected master has no segments") + offset = data.source_selection.start + for index, segment in enumerate(data.segments): + if segment.master_start != offset or segment.master_stop <= offset: + raise ValueError("Segment ranges must be contiguous and nonempty") + offset = segment.master_stop + if segment.data is not None: + data.with_segment(index, segment.data) + if offset != data.source_selection.stop: + raise ValueError("Segment ranges must cover the selected master") + if data.layout == "fixed" and not any( + segment.data is not None and segment.data.metadata.n_signals + for segment in data.segments + ): + raise ValueError( + "Cannot write a fixed-layout record without a data segment to define " + "its channels; select a window that includes one" + ) + + +def _master_formats(data: SegmentedRecordData, formats): + """Validate a format choice given for all channels or in master order.""" + if formats is None or isinstance(formats, str): + return formats + if not isinstance(formats, (list, tuple)): + raise TypeError("formats must be a string or a sequence of strings") + if len(formats) != data.metadata.n_signals: + raise ValueError( + "formats must contain one value per selected channel, in master order" + ) + if any(not isinstance(fmt, str) for fmt in formats): + raise TypeError("formats must contain strings") + return tuple(formats) + + +def _segment_formats(data: SegmentedRecordData, formats, segment_data): + """Map master-order formats to one segment's own channels.""" + if formats is None or isinstance(formats, str): + return formats + names = data.metadata.channel_names + return [ + formats[names.index(signal.name)] for signal in segment_data.metadata.signals + ] + + +def _selected_master_time(data: SegmentedRecordData): + """Return a writable selected start, including a date-only source.""" + metadata = data.metadata + if metadata.base_date is not None and metadata.base_time is None: + return _adjust_time( + metadata.base_date, + datetime.time(0), + metadata.fs, + data.source_selection.start, + ) + return metadata.base_date, metadata.base_time + + +def _record_fields(name, data, *, segment_count, frame_count, date, time, comments): + """Build explicit record-line fields for a master or layout header.""" + metadata = data.metadata + return { + "record_name": name, + "n_seg": segment_count, + "n_sig": metadata.n_signals, + "fs": metadata.fs, + "counter_freq": metadata.counter_frequency if segment_count else None, + "base_counter": metadata.base_counter if segment_count else None, + "sig_len": frame_count, + "base_time": time, + "base_date": date, + "comments": comments, + } + + +def _write_layout_header(staging, name, data, date, time): + """Write a selected variable-layout header from explicit channel fields.""" + fields = _record_fields( + name, + data, + segment_count=None, + frame_count=0, + date=date, + time=time, + comments=(), + ) + signals = [] + for channel, source_index in enumerate(data.source_selection.channels): + source = data.channel_header.signals[source_index] + signals.append( + _header._ParsedSignalLine( + file_name="~", + fmt="0", + samps_per_frame=data.metadata.samples_per_frame[channel], + skew=None, + byte_offset=None, + adc_gain=source.adc_gain or 200, + baseline=source.baseline if source.baseline is not None else 0, + units=source.units or "mV", + adc_res=None, + adc_zero=None, + init_value=None, + checksum=None, + block_size=None, + sig_name=data.metadata.channel_names[channel], + ) + ) + fields_to_write = _header._select_record_header_fields(fields, multi_segment=False) + channel_fields = { + key: list(range(data.metadata.n_signals)) + for key in ("file_name", "fmt", "adc_gain", "baseline", "units", "sig_name") + } + channel_fields["samps_per_frame"] = [ + index for index, spf in enumerate(data.metadata.samples_per_frame) if spf != 1 + ] + lines = _header._serialize_single_header_lines( + fields, signals, fields_to_write, channel_fields + ) + _header._write_header_lines(name, lines, staging, None) + + +def _write_master_header(staging, name, data, segments, date, time): + """Write the output master header using selected, not source, metadata.""" + fields = _record_fields( + name, + data, + segment_count=len(segments), + frame_count=data.n_frames, + date=date, + time=time, + comments=data.metadata.comments, + ) + fields_to_write = _header._select_record_header_fields(fields, multi_segment=True) + lines = _header._serialize_multi_header_lines(fields, segments, fields_to_write) + # The older multi-header serializer omits this closing parenthesis. + lines[0] = _header._record_header_line(fields, fields_to_write, close_counter=True) + _header._write_header_lines(name, lines, staging, None) + + +def _write_staged_files(staging, name, data, signal_alignment, formats): + """Encode every segment, then its layout and master headers in staging.""" + date, time = _selected_master_time(data) + width = max(4, len(str(len(data.segments)))) + output_segments = [] + for index, segment in enumerate(data.segments, 1): + if segment.data is None or segment.data.metadata.n_signals == 0: + output_segments.append(("~", segment.n_frames)) + continue + segment_name = f"{name}_{index:0{width}d}" + output_segments.append((segment_name, segment.n_frames)) + current = segment.data + if date is not None or time is not None: + segment_date, segment_time = _adjust_time( + date, + time, + data.metadata.fs, + segment.master_start - data.source_selection.start, + ) + if ( + current.metadata.base_date, + current.metadata.base_time, + ) != (segment_date, segment_time): + current = _replace_record_metadata( + current, timing=(segment_date, segment_time) + ) + current.write( + os.path.join(staging, segment_name), + signal_alignment=signal_alignment, + formats=_segment_formats(data, formats, current), + ) + if data.layout == "variable": + layout_name = f"{name}_layout" + _write_layout_header(staging, layout_name, data, date, time) + output_segments.insert(0, (layout_name, 0)) + _write_master_header(staging, name, data, output_segments, date, time) + + +def _warn_overwrites(directory, names): + """Warn about destination files that the staged write will replace.""" + existing = [] + for name in names: + target = _join_path(directory, name) + if is_cloud_path(directory): + opened = _fsspec_open(target) + present = opened.fs.exists(opened.path) + else: + present = os.path.exists(target) + if present: + existing.append(name) + if existing: + warnings.warn( + "Writing segmented record replaces existing files: " + ", ".join(existing), + stacklevel=_caller_stacklevel(), + ) + + +def write_segments( + path, data: SegmentedRecordData, *, signal_alignment=None, formats=None +) -> None: + """Write a selected segmented view under a new multi-segment record name. + + Every real segment is encoded through ``RecordData.write``. A zero-channel + real segment becomes a ``~`` gap of the same length. The output starts at + frame zero, and a selected window's start time becomes the master start. + Source headers are retained only as provenance, never copied to output. + + Parameters + ---------- + path : str or os.PathLike + Local record stem, supported writable cloud URI, or local ``.wfdb`` + archive path. + data : SegmentedRecordData + Selected segmented result to write. + signal_alignment : {"aligned", "raw"}, optional + Required if a written segment has nonzero skew. + formats : str or sequence of str, optional + Target storage format for every channel, or one format per selected + channel in master order. Each segment receives the formats of the + channels it contains. Required when a source format cannot be + written or loaded segments do not establish one format. + + Raises + ------ + ValueError + If the selection cannot form a valid record, such as a fixed-layout + window containing only ``~`` gaps. + """ + if not isinstance(data, SegmentedRecordData): + raise TypeError("data must be a SegmentedRecordData") + if signal_alignment not in (None, "aligned", "raw"): + raise ValueError("signal_alignment must be 'aligned' or 'raw'") + _validate_selected_segments(data) + formats = _master_formats(data, formats) + destination = os.fspath(path) + archive = is_archive_path(destination) + if archive and is_cloud_path(destination): + raise ValueError("Writing .wfdb archives to cloud storage is unsupported") + directory, name = _split_path(destination) + if archive: + name = name[:-5] + if re.fullmatch(r"[A-Za-z0-9_-]+", name) is None: + raise ValueError( + "Destination name must contain only letters, digits, hyphens, " + "and underscores" + ) + check_cloud_write(directory, destination if archive else None) + if archive: + with tempfile.TemporaryDirectory(prefix="wfdb-segments-") as staging: + _write_staged_files(staging, name, data, signal_alignment, formats) + if os.path.exists(destination): + warnings.warn( + f"Writing segmented record replaces {destination!r}", + stacklevel=_caller_stacklevel(), + ) + with WFDBArchive(destination, mode="w") as output: + for file_name in sorted(os.listdir(staging)): + with open(os.path.join(staging, file_name), "rb") as source: + output.write(file_name, source.read()) + elif is_cloud_path(directory): + with staged_cloud_write(directory, f"{name}.hea") as staging: + _write_staged_files(staging, name, data, signal_alignment, formats) + _warn_overwrites(directory, os.listdir(staging)) + else: + directory = directory or os.curdir + with tempfile.TemporaryDirectory( + dir=directory, prefix=".wfdb-segments-" + ) as staging: + _write_staged_files(staging, name, data, signal_alignment, formats) + _warn_overwrites(directory, os.listdir(staging)) + _move_files_into_place(staging, directory) diff --git a/src/wfdb/io/segment_values.py b/src/wfdb/io/segment_values.py index 059e527e..d8ea004f 100644 --- a/src/wfdb/io/segment_values.py +++ b/src/wfdb/io/segment_values.py @@ -304,6 +304,30 @@ def shift_time(self, delta: datetime.timedelta) -> SegmentedRecordData: segments=entries, ) + def write(self, path, *, signal_alignment=None, formats=None) -> None: + """Write the selected segments as a multi-segment WFDB record. + + The destination is a local record stem, a supported cloud URI, or a + local ``.wfdb`` archive. Segment names are generated from the + destination name. Real segments with no selected channels are written + as ``~`` gaps of the same length. + + Parameters + ---------- + path : str or os.PathLike + Destination record stem, supported cloud URI, or local + ``.wfdb`` archive. + signal_alignment : {"aligned", "raw"}, optional + Required when any written segment has nonzero skew, with the + same meaning as for ``RecordData.write``. + formats : str or sequence of str, optional + Target storage format for every channel, or one format per + selected channel in master order, as for ``write_segments``. + """ + from wfdb.io._segment_write import write_segments + + write_segments(path, self, signal_alignment=signal_alignment, formats=formats) + def plot( self, *, diff --git a/tests/test_write_segments.py b/tests/test_write_segments.py new file mode 100644 index 00000000..12e42ce1 --- /dev/null +++ b/tests/test_write_segments.py @@ -0,0 +1,313 @@ +"""Writing selected segmented records through the modern API.""" + +import datetime +import shutil + +import fsspec +import numpy as np +import pytest + +import wfdb + +FIXED = "sample-data/multi-segment/fixed1/v102s" +VARIABLE = "sample-data/multi-segment/s25047/s25047-2704-05-04-10-44" + + +def _assert_signal_values(actual, expected, kind, layout): + """Compare values and missing positions across both loaded layouts.""" + current = actual if layout == "expanded" else (actual,) + original = expected if layout == "expanded" else (expected,) + for values, baseline in zip(current, original): + if kind == "digital": + np.testing.assert_array_equal( + np.ma.getmaskarray(values), np.ma.getmaskarray(baseline) + ) + np.testing.assert_array_equal(values.compressed(), baseline.compressed()) + else: + np.testing.assert_allclose(values, baseline, rtol=0, atol=1e-10) + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_fixed_window_round_trip_and_combined_values(tmp_path, kind, layout): + """Both readers see the same selected fixed-layout values and order.""" + options = { + "kind": kind, + "layout": layout, + "start": 74996, + "stop": 75004, + "channels": [3, 0], + } + source = wfdb.read_segments(FIXED, **options) + target = tmp_path / "copy" + + wfdb.write_segments(target, source) + + copied = wfdb.read_segments(target, kind=kind, layout=layout) + assert copied.layout == "fixed" + assert [segment.n_frames for segment in copied.segments] == [4, 4] + assert [segment.name for segment in copied.segments] == [ + "copy_0001", + "copy_0002", + ] + for old, new in zip(source.segments, copied.segments): + _assert_signal_values( + new.data.signals.values, old.data.signals.values, kind, layout + ) + combined = wfdb.read_record(FIXED, **options) + written = wfdb.read_record(target, kind=kind, layout=layout) + _assert_signal_values(written.signals.values, combined.signals.values, kind, layout) + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_variable_gap_and_missing_channel_round_trip(tmp_path, kind, layout): + """The layout header selects channels; missing ones remain missing.""" + options = { + "kind": kind, + "layout": layout, + "start": 25735, + "stop": 25750, + "channel_names": ["ABP", "II"], + } + source = wfdb.read_segments(VARIABLE, **options) + target = tmp_path / "copy" + + source.write(target) + + copied = wfdb.read_segments(target, kind=kind, layout=layout) + assert copied.layout == "variable" + assert copied.metadata.channel_names == ("ABP", "II") + assert [(segment.name, segment.n_frames) for segment in copied.segments] == [ + ("~", 5), + ("copy_0002", 10), + ] + assert [signal.name for signal in copied.segments[1].data.metadata.signals] == [ + "II" + ] + _assert_signal_values( + copied.segments[1].data.signals.values, + source.segments[1].data.signals.values, + kind, + layout, + ) + original_combined = wfdb.read_record(VARIABLE, **options) + new_combined = wfdb.read_record(target, kind=kind, layout=layout) + _assert_signal_values( + new_combined.signals.values, original_combined.signals.values, kind, layout + ) + + +def test_zero_channel_real_segments_become_gaps(tmp_path): + """Segments with no selected values keep their duration as null entries.""" + source = wfdb.read_segments( + VARIABLE, layout="uniform", stop=60000, channel_names=["ABP"] + ) + target = tmp_path / "copy" + + wfdb.write_segments(target, source) + + copied = wfdb.read_segments(target, layout="uniform") + assert len(copied.segments) == len(source.segments) + assert all(segment.name == "~" for segment in copied.segments) + assert [segment.n_frames for segment in copied.segments] == [ + segment.n_frames for segment in source.segments + ] + assert not list(tmp_path.glob("copy_*.dat")) + + +def test_edited_segment_and_shifted_time_write_current_view(tmp_path): + """Written headers and samples come from edits, never source provenance.""" + source = wfdb.read_segments( + VARIABLE, + layout="uniform", + start=25735, + stop=25750, + channel_names=["ABP", "II"], + ) + original = source.segments[1].data + edited = source.with_segment( + 1, original.with_values(original.signals.values + 0.1) + ).shift_time(datetime.timedelta(days=2)) + target = tmp_path / "copy" + + wfdb.write_segments(target, edited) + + copied = wfdb.read_segments(target, layout="uniform") + assert copied.metadata.base_datetime == edited.metadata.base_datetime + np.testing.assert_allclose( + copied.segments[1].data.signals.values, + edited.segments[1].data.signals.values, + rtol=0, + atol=0.01, + ) + for header in tmp_path.glob("*.hea"): + original_date = source.source_header.base_date.strftime("%d/%m/%Y") + assert original_date.encode() not in header.read_bytes() + assert source.source_header.base_date.year == 2704 + + +@pytest.mark.parametrize("archive", [False, True]) +def test_archive_and_cloud_targets(tmp_path, archive): + """Staged outputs remain readable from an archive or memory cloud.""" + source = wfdb.read_segments( + FIXED, kind="digital", layout="uniform", start=74996, stop=75004 + ) + if archive: + target = tmp_path / "copy.wfdb" + else: + target = "memory://write-segments/copy" + + wfdb.write_segments(target, source) + + copied = wfdb.read_segments(target, kind="digital", layout="uniform") + for old, new in zip(source.segments, copied.segments): + _assert_signal_values( + new.data.signals.values, old.data.signals.values, "digital", "uniform" + ) + if not archive: + fsspec.filesystem("memory").rm("/write-segments", recursive=True) + + +def test_later_segment_error_leaves_destination_empty(tmp_path): + """A failed second segment discards the already staged first one.""" + source = wfdb.read_segments( + FIXED, kind="digital", layout="uniform", start=74996, stop=75004 + ) + source.segments[1].data.signals.values[0, 0] = 10**9 + + with pytest.raises(ValueError): + wfdb.write_segments(tmp_path / "copy", source) + + assert list(tmp_path.iterdir()) == [] + + +def test_failed_rewrite_preserves_existing_files(tmp_path): + """Staging leaves an older complete record intact on a later error.""" + source = wfdb.read_segments( + FIXED, kind="digital", layout="uniform", start=74996, stop=75004 + ) + target = tmp_path / "copy" + wfdb.write_segments(target, source) + before = {path.name: path.read_bytes() for path in tmp_path.iterdir()} + source.segments[1].data.signals.values[0, 0] = 10**9 + + with pytest.raises(ValueError): + wfdb.write_segments(target, source) + + assert {path.name: path.read_bytes() for path in tmp_path.iterdir()} == before + + +def test_replacing_existing_segment_files_warns(tmp_path): + """A successful rewrite reports every destination file it replaces.""" + source = wfdb.read_segments( + FIXED, kind="digital", layout="uniform", start=74996, stop=75004 + ) + target = tmp_path / "copy" + wfdb.write_segments(target, source) + + with pytest.warns(UserWarning, match="replaces existing files"): + wfdb.write_segments(target, source) + + +def test_skewed_segment_requires_alignment(tmp_path): + """Segment writes retain the explicit alignment contract.""" + shutil.copy("sample-data/test01_00s_skew.hea", tmp_path) + shutil.copy("sample-data/test01_00s.dat", tmp_path) + (tmp_path / "multi.hea").write_text("multi/1 4 500 4000\ntest01_00s_skew 4000\n") + source = wfdb.read_segments( + tmp_path / "multi", + layout="uniform", + stop=10, + ) + + with pytest.raises(ValueError, match="signal_alignment"): + wfdb.write_segments(tmp_path / "copy", source) + assert not list(tmp_path.glob("copy*")) + wfdb.write_segments(tmp_path / "copy", source, signal_alignment="aligned") + copied = wfdb.read_record(tmp_path / "copy", layout="uniform") + original = wfdb.read_record(tmp_path / "multi", layout="uniform", stop=10) + _assert_signal_values( + copied.signals.values, original.signals.values, "physical", "uniform" + ) + + +def _fixed_record_with_gap(directory, signal_file, fmt, line): + """Create a fixed-layout record with one data segment followed by a gap.""" + shutil.copy(f"sample-data/{signal_file}", directory / signal_file) + (directory / "part.hea").write_text(f"part 1 200 499\n{signal_file} {line}\n") + (directory / "gapped.hea").write_text("gapped/2 1 200 998\npart 499\n~ 499\n") + return directory / "gapped" + + +def test_fixed_gap_only_window_is_rejected_before_writing(tmp_path): + """A fixed-layout output needs a data segment to define its channels.""" + source = _fixed_record_with_gap( + tmp_path, "binformats.d1", "16", "16 200/mV 16 0 -32766 -750 0 sig" + ) + gaps = wfdb.read_segments(source, layout="uniform", start=600, stop=700) + assert [segment.data for segment in gaps.segments] == [None] + output = tmp_path / "out" + output.mkdir() + + with pytest.raises(ValueError, match="without a data segment"): + wfdb.write_segments(output / "copy", gaps) + assert list(output.iterdir()) == [] + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_unwritable_source_format_uses_formats_option(tmp_path, kind, layout): + """Format 8 segments can be written by choosing a writable format.""" + source = _fixed_record_with_gap( + tmp_path, "binformats.d0", "8", "8 200/mV 12 0 -2047 -31143 0 sig" + ) + parts = wfdb.read_segments(source, kind=kind, layout=layout, stop=700) + output = tmp_path / "out" + output.mkdir() + + with pytest.raises(ValueError, match="only supports writing"): + wfdb.write_segments(output / "copy", parts) + assert list(output.iterdir()) == [] + + parts.write(output / "copy", formats="16") + copied = wfdb.read_segments(output / "copy", kind=kind, layout=layout) + assert [segment.name for segment in copied.segments] == ["copy_0001", "~"] + assert copied.segments[0].data.metadata.channels[0].storage.format == "16" + _assert_signal_values( + copied.segments[0].data.signals.values, + parts.segments[0].data.signals.values, + kind, + layout, + ) + + +def test_per_channel_formats_follow_master_order(tmp_path): + """Each variable-layout segment receives its own channels' formats.""" + parts = wfdb.read_segments( + VARIABLE, layout="uniform", start=25000, stop=55000, channels=[2, 0] + ) + names = parts.metadata.channel_names + chosen = dict(zip(names, ["16", "212"])) + + wfdb.write_segments(tmp_path / "copy", parts, formats=[chosen[n] for n in names]) + + copied = wfdb.read_segments(tmp_path / "copy", layout="uniform") + checked = 0 + for segment in copied.segments: + if segment.data is None: + continue + for signal, channel in zip( + segment.data.metadata.signals, segment.data.metadata.channels + ): + assert channel.storage.format == chosen[signal.name] + checked += 1 + assert checked > 1 + + +def test_formats_length_is_checked_before_writing(tmp_path): + """A per-channel format list must match the selected master channels.""" + parts = wfdb.read_segments(FIXED, layout="uniform", start=74996, stop=75004) + with pytest.raises(ValueError, match="one value per selected channel"): + wfdb.write_segments(tmp_path / "copy", parts, formats=["16"]) + assert list(tmp_path.iterdir()) == []