From 5a7923b225eaf298bfffc793e395abffbd3d788d Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Tue, 24 Nov 2026 19:13:05 -0500 Subject: [PATCH 1/2] Preserve segment ranges on flattened records --- changelog.d/flattened-segment-ranges.rst | 4 ++ src/wfdb/io/record.py | 33 +++++++++++-- tests/test_multi_record.py | 62 ++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 3 deletions(-) create mode 100644 changelog.d/flattened-segment-ranges.rst diff --git a/changelog.d/flattened-segment-ranges.rst b/changelog.d/flattened-segment-ranges.rst new file mode 100644 index 00000000..32b22ffa --- /dev/null +++ b/changelog.d/flattened-segment-ranges.rst @@ -0,0 +1,4 @@ +**Preserve source segment ranges on flattened records** + ``rdrecord`` now retains source segment names and frame ranges, including + empty segments, in the ``source_segments`` attribute when flattening a + multi-segment record. diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index f77ff1d1..0408205f 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -764,6 +764,12 @@ class Record(BaseRecord, _header.HeaderMixin, _signal.SignalMixin): A list of strings giving the signal name of each signal channel. comments : list, optional A list of string comments to be written to the header file. + source_segments : list of tuple, optional + For a record flattened from a multi-segment record, tuples of + ``(segment_name, start, stop)`` giving the source segment and its + half-open range in the returned record's frames. Empty segments have + the name ``"~"``. The zero-length layout header is omitted. This + metadata is kept in memory and is not written to a WFDB header. Examples -------- @@ -803,6 +809,7 @@ def __init__( block_size=None, sig_name=None, comments=None, + source_segments=None, ): # Note the lack of the 'n_seg' field. Single segment records cannot # have this field. Even n_seg = 1 makes the header a multi-segment @@ -839,6 +846,7 @@ def __init__( self.init_value = init_value self.checksum = checksum self.block_size = block_size + self.source_segments = source_segments # The skew already applied to the signals when they were read, if any self._applied_skew = None @@ -859,9 +867,10 @@ def __eq__(self, other, verbose=False): Determines if the objects are equal (True) or not equal (False). """ - # How the signals were read does not affect whether records are equal - att1 = {k: v for k, v in self.__dict__.items() if k != "_applied_skew"} - att2 = {k: v for k, v in other.__dict__.items() if k != "_applied_skew"} + # Read provenance does not affect whether record contents are equal. + read_metadata = {"_applied_skew", "source_segments"} + att1 = {k: v for k, v in self.__dict__.items() if k not in read_metadata} + att2 = {k: v for k, v in other.__dict__.items() if k not in read_metadata} if set(att1.keys()) != set(att2.keys()): if verbose: @@ -1752,6 +1761,23 @@ def multi_to_single(self, physical, return_res=64, expanded=False): # The fields to transfer to the new object fields = self.__dict__.copy() + # Retain the original segment boundaries as read, before dropping the + # multi-segment header fields. _arrange_fields has already clipped + # seg_len to the requested sample window. + source_segments = [] + start = 0 + names = self.seg_name + if names is None: + names = [ + segment.record_name if segment is not None else "~" + for segment in self.segments + ] + for name, length in zip(names, self.seg_len): + stop = start + int(length) + if stop > start: + source_segments.append((name, start, stop)) + start = stop + # Remove multirecord fields for attr in ["segments", "seg_name", "seg_len", "n_seg"]: del fields[attr] @@ -1924,6 +1950,7 @@ def multi_to_single(self, physical, return_res=64, expanded=False): record = Record() for field in fields: setattr(record, field, fields[field]) + record.source_segments = source_segments setattr(record, sig_attr, combined_signal) # Use the signal to set record features diff --git a/tests/test_multi_record.py b/tests/test_multi_record.py index 6e144404..bba19769 100644 --- a/tests/test_multi_record.py +++ b/tests/test_multi_record.py @@ -10,6 +10,68 @@ class TestMultiRecordRanges: """Test logic that deduces relevant segments/ranges for given signals.""" + def test_flattened_variable_ranges_include_clipped_empty_segment(self): + """Preserve explicit gaps separately from missing channel samples.""" + path = "sample-data/multi-segment/s25047/s25047-2704-05-04-10-44" + record = wfdb.rdrecord(path, sampfrom=1000, sampto=26000) + + assert record.source_segments == [ + ("~", 0, 24740), + ("3234460_0001", 24740, 25000), + ] + assert np.isnan(record.p_signal[:24740]).all() + + def test_flattened_range_inside_empty_segment(self): + """A digital read retains the empty segment's clipped boundaries.""" + path = "sample-data/multi-segment/s25047/s25047-2704-05-04-10-44" + record = wfdb.rdrecord(path, sampfrom=1000, sampto=2000, physical=False) + + assert record.source_segments == [("~", 0, 1000)] + + def test_flattened_fixed_ranges_cover_requested_window(self): + """Fixed-layout segment ranges use the returned frame coordinates.""" + record = wfdb.rdrecord( + "sample-data/multi-segment/041s/041s", + sampfrom=500, + sampto=1500, + physical=False, + smooth_frames=False, + ) + + assert record.source_segments == [ + ("041s01", 0, 500), + ("041s02", 500, 1000), + ] + + def test_single_segment_has_no_source_ranges(self): + """Ordinary records have no multi-segment provenance.""" + record = wfdb.rdrecord("sample-data/100", sampto=100) + + assert record.source_segments is None + + def test_flattened_in_memory_record_uses_segment_names(self): + """Direct conversion works when a MultiRecord has no seg_name list.""" + segment = wfdb.Record( + record_name="segment", + n_sig=1, + fs=1, + sig_len=2, + p_signal=np.array([[1.0], [2.0]]), + fmt=["16"], + adc_gain=[1.0], + baseline=[0], + units=["mV"], + sig_name=["I"], + samps_per_frame=[1], + ) + multi = wfdb.MultiRecord( + segments=[segment], layout="fixed", n_sig=1, fs=1, sig_len=2 + ) + + record = multi.multi_to_single(physical=True) + + assert record.source_segments == [("segment", 0, 2)] + def test_contained_ranges_simple_cases(self): record = wfdb.MultiRecord( segments=[ From 4402c8d1e5515c3cae11fe9bc7c6a23047f3e961 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Tue, 24 Nov 2026 19:19:44 -0500 Subject: [PATCH 2/2] Return source segments as named tuples Record.source_segments now holds SourceSegment named tuples, so ranges can be used by field name (segment.start) as well as unpacked or compared as (name, start, stop) tuples. --- changelog.d/flattened-segment-ranges.rst | 3 +- docs/io.rst | 3 ++ src/wfdb/io/__init__.py | 1 + src/wfdb/io/record.py | 35 ++++++++++++++++++++---- tests/test_multi_record.py | 12 ++++++++ 5 files changed, 48 insertions(+), 6 deletions(-) diff --git a/changelog.d/flattened-segment-ranges.rst b/changelog.d/flattened-segment-ranges.rst index 32b22ffa..73a5d479 100644 --- a/changelog.d/flattened-segment-ranges.rst +++ b/changelog.d/flattened-segment-ranges.rst @@ -1,4 +1,5 @@ **Preserve source segment ranges on flattened records** ``rdrecord`` now retains source segment names and frame ranges, including empty segments, in the ``source_segments`` attribute when flattening a - multi-segment record. + multi-segment record. Each range is a ``wfdb.io.SourceSegment`` named tuple + of ``(name, start, stop)``. diff --git a/docs/io.rst b/docs/io.rst index 3aba4506..725c53af 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -34,6 +34,9 @@ headers are reused within one iterator, including for remote records: :members: get_frame_number, get_elapsed_time, get_absolute_time, multi_to_single, contained_ranges, contained_combined_ranges +.. autoclass:: wfdb.io.SourceSegment + :no-index: + WFDB Annotations ---------------- diff --git a/src/wfdb/io/__init__.py b/src/wfdb/io/__init__.py index 54ceead1..eccbd0be 100644 --- a/src/wfdb/io/__init__.py +++ b/src/wfdb/io/__init__.py @@ -25,6 +25,7 @@ SIGNAL_CLASSES, MultiRecord, Record, + SourceSegment, dl_database, iter_dataframes, rdheader, diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 0408205f..4fd02cf7 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -8,6 +8,7 @@ import re import shutil import tempfile +import typing import warnings import numpy as np @@ -159,6 +160,30 @@ } +class SourceSegment(typing.NamedTuple): + """The range of a flattened record's frames that came from one segment. + + `Record.source_segments` holds one of these for each segment of a + multi-segment record that contributed frames. It unpacks and compares like + a ``(name, start, stop)`` tuple. + + Attributes + ---------- + name : str + The name of the segment, or ``"~"`` for an empty segment. + start : int + The first frame of the segment in the flattened record. + stop : int + The frame after the last frame of the segment, so that the segment + covers ``start`` to ``stop - 1``. + + """ + + name: str + start: int + stop: int + + class BaseRecord: """The base WFDB class extended by the Record and MultiRecord classes. @@ -764,10 +789,10 @@ class Record(BaseRecord, _header.HeaderMixin, _signal.SignalMixin): A list of strings giving the signal name of each signal channel. comments : list, optional A list of string comments to be written to the header file. - source_segments : list of tuple, optional - For a record flattened from a multi-segment record, tuples of - ``(segment_name, start, stop)`` giving the source segment and its - half-open range in the returned record's frames. Empty segments have + source_segments : list of SourceSegment, optional + For a record flattened from a multi-segment record, the name of each + source segment and its range of the returned record's frames, as + `SourceSegment` tuples of ``(name, start, stop)``. Empty segments have the name ``"~"``. The zero-length layout header is omitted. This metadata is kept in memory and is not written to a WFDB header. @@ -1775,7 +1800,7 @@ def multi_to_single(self, physical, return_res=64, expanded=False): for name, length in zip(names, self.seg_len): stop = start + int(length) if stop > start: - source_segments.append((name, start, stop)) + source_segments.append(SourceSegment(name, start, stop)) start = stop # Remove multirecord fields diff --git a/tests/test_multi_record.py b/tests/test_multi_record.py index bba19769..4687b567 100644 --- a/tests/test_multi_record.py +++ b/tests/test_multi_record.py @@ -21,6 +21,18 @@ def test_flattened_variable_ranges_include_clipped_empty_segment(self): ] assert np.isnan(record.p_signal[:24740]).all() + def test_source_segments_are_named_tuples(self): + """Ranges can be used by field name or unpacked as plain tuples.""" + path = "sample-data/multi-segment/s25047/s25047-2704-05-04-10-44" + record = wfdb.rdrecord(path, sampfrom=1000, sampto=26000) + + gap, data = record.source_segments + assert isinstance(gap, wfdb.io.SourceSegment) + assert (gap.name, gap.start, gap.stop) == ("~", 0, 24740) + name, start, stop = data + assert (name, start, stop) == ("3234460_0001", 24740, 25000) + assert np.isnan(record.p_signal[gap.start : gap.stop]).all() + def test_flattened_range_inside_empty_segment(self): """A digital read retains the empty segment's clipped boundaries.""" path = "sample-data/multi-segment/s25047/s25047-2704-05-04-10-44"