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
5 changes: 5 additions & 0 deletions changelog.d/flattened-segment-ranges.rst
Original file line number Diff line number Diff line change
@@ -0,0 +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. Each range is a ``wfdb.io.SourceSegment`` named tuple
of ``(name, start, stop)``.
3 changes: 3 additions & 0 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------------
Expand Down
1 change: 1 addition & 0 deletions src/wfdb/io/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
SIGNAL_CLASSES,
MultiRecord,
Record,
SourceSegment,
dl_database,
iter_dataframes,
rdheader,
Expand Down
58 changes: 55 additions & 3 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import re
import shutil
import tempfile
import typing
import warnings

import numpy as np
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -764,6 +789,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 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.

Examples
--------
Expand Down Expand Up @@ -803,6 +834,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
Expand Down Expand Up @@ -839,6 +871,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

Expand All @@ -859,9 +892,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:
Expand Down Expand Up @@ -1752,6 +1786,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(SourceSegment(name, start, stop))
start = stop

# Remove multirecord fields
for attr in ["segments", "seg_name", "seg_len", "n_seg"]:
del fields[attr]
Expand Down Expand Up @@ -1924,6 +1975,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
Expand Down
74 changes: 74 additions & 0 deletions tests/test_multi_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,80 @@
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_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"
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=[
Expand Down
Loading