From 7de38183f572073c4efb8b3812fab00cdb84e86f Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 16:54:16 -0500 Subject: [PATCH 1/2] Plot segmented records on one master timeline --- README.md | 7 +++ changelog.d/plot-segments.rst | 4 ++ docs/io.rst | 2 + docs/plot.rst | 8 +++ src/wfdb/io/segment_values.py | 39 +++++++++++++ src/wfdb/plot/plot.py | 106 ++++++++++++++++++++++++++++++++++ tests/test_plot.py | 83 ++++++++++++++++++++++++++ 7 files changed, 249 insertions(+) create mode 100644 changelog.d/plot-segments.rst diff --git a/README.md b/README.md index cda1d4c5..11203918 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,13 @@ For a local annotation, pass its filename, such as `"path/to/record.atr"`. `plot_wfdb` also accepts `RecordData` directly, while continuing to support legacy `Record` objects. +For a multi-segment record, plot the original pieces and gaps together: + +```python +segments = wfdb.read_segments("path/to/record", layout="uniform") +segments.plot() # one figure with segment boundaries and shaded gaps +``` + ## Write records Use `write_record` to save a loaded or edited `RecordData`; it already has diff --git a/changelog.d/plot-segments.rst b/changelog.d/plot-segments.rst new file mode 100644 index 00000000..13af4183 --- /dev/null +++ b/changelog.d/plot-segments.rst @@ -0,0 +1,4 @@ +**Plot a segmented record in one figure** + ``SegmentedRecordData.plot()`` plots loaded segments on their master-record + timeline without rereading them. Segment boundaries are marked, ``~`` gaps + are shaded, and expanded channels use their own samples-per-frame positions. diff --git a/docs/io.rst b/docs/io.rst index 940d1ea9..301f4092 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -810,6 +810,8 @@ there. A real entry can therefore have zero channels. The layout header is never an entry, and selected channels are not padded across segments. A segment with values can be written on its own with ``data.write(path)``; writing a zero-channel entry raises ``ValueError``. +Call ``segments.plot()`` to show all loaded entries on one master-record +timeline, with segment boundaries marked and gaps shaded. .. autoclass:: wfdb.io.SegmentedRecordData :no-index: diff --git a/docs/plot.rst b/docs/plot.rst index 929d75c5..1bf9fd28 100644 --- a/docs/plot.rst +++ b/docs/plot.rst @@ -5,5 +5,13 @@ plot optional annotations. ``plot_wfdb`` accepts both modern ``RecordData`` and legacy ``Record`` objects. +``SegmentedRecordData.plot(...)`` plots every loaded segment on one figure. +Use ``read_segments(path, layout="uniform").plot()`` to show the original +segment boundaries and shaded ``~`` gaps without reading the files again. +The x axis uses positions in the master record, including when reading only +a window. For expanded reads, each channel's samples are positioned using +its samples per frame. Plot an individual segment with +``segments.segments[index].data.plot()`` when its ``data`` is not ``None``. + .. automodule:: wfdb.plot :members: plot_items, plot_wfdb, plot_all_records diff --git a/src/wfdb/io/segment_values.py b/src/wfdb/io/segment_values.py index 2392a00e..203dff19 100644 --- a/src/wfdb/io/segment_values.py +++ b/src/wfdb/io/segment_values.py @@ -67,6 +67,45 @@ def n_frames(self) -> int: """Return the number of selected master-record frames.""" return self.source_selection.stop - self.source_selection.start + def plot( + self, + *, + time_units="samples", + title=None, + figsize=None, + return_fig=False, + ): + """Plot all selected segments on their master-record timeline. + + Segment boundaries are marked, and ``~`` gaps are shaded. Time starts + at the beginning of the master record, including for a selected window. + + Parameters + ---------- + time_units : {"samples", "seconds", "minutes", "hours"}, optional + Units for the master-record time axis. + title : str, optional + Figure title. Defaults to the master record name. + figsize : tuple, optional + Figure width and height in inches. + return_fig : bool, optional + Return the figure instead of showing it. + + Returns + ------- + matplotlib.figure.Figure or None + The figure when ``return_fig=True``; otherwise show the plot. + """ + from wfdb.plot.plot import _plot_segmented_record + + return _plot_segmented_record( + self, + time_units=time_units, + title=title, + figsize=figsize, + return_fig=return_fig, + ) + def _empty_segment_model(parsed, start, stop, kind, layout, resolution): """Describe a real segment with no selected channels without reading data.""" diff --git a/src/wfdb/plot/plot.py b/src/wfdb/plot/plot.py index c38ba547..784fc9f8 100644 --- a/src/wfdb/plot/plot.py +++ b/src/wfdb/plot/plot.py @@ -1047,6 +1047,112 @@ def visible(array): return visible(values) +def _plot_segmented_record( + record, *, time_units="samples", title=None, figsize=None, return_fig=False +): + """Plot loaded segments on one master-record timeline without rereading.""" + import matplotlib.pyplot as plt + + factors = {"samples": 1, "seconds": 1, "minutes": 60, "hours": 3600} + if time_units not in factors: + raise ValueError("time_units must be samples, seconds, minutes, or hours") + channels = record.source_selection.channels + if not channels: + raise ValueError("The record has no signal to plot") + headers = [record.channel_header.signals[channel] for channel in channels] + names = [header.name for header in headers] + kinds = { + segment.data.signals.kind + for segment in record.segments + if segment.data is not None and segment.data.metadata.n_signals + } + kind = next(iter(kinds), "physical") + if len(kinds) > 1: + raise ValueError("All segments must have the same signal kind to plot") + + fs = record.source_header.fs + scale = factors[time_units] * (1 if time_units == "samples" else fs) + fig, axes = _create_figure(len(channels), True, False, figsize) + try: + units = ["adu" if kind == "digital" else header.units for header in headers] + for segment in record.segments: + if segment.data is None: + for axis in axes: + axis.axvspan( + segment.master_start / scale, + segment.master_stop / scale, + color="0.9", + zorder=0, + ) + continue + + data = segment.data + values = _record_data_plot_values(data) + present = [signal.name for signal in data.metadata.signals] + used = set() + for local, name in enumerate(present): + if record.layout == "fixed": + channel = local + else: + matches = ( + channel + for channel, wanted in enumerate(names) + if wanted == name and channel not in used + ) + channel = next(matches, None) + if channel is None: + continue + used.add(channel) + if kind == "physical": + segment_units = data.metadata.signals[local].units + if units[channel] is None: + units[channel] = segment_units + elif segment_units != units[channel]: + raise ValueError( + f"Channel {name!r} has different units across segments" + ) + signal = ( + values[local] + if isinstance(data.signals, ExpandedSignals) + else values[:, local] + ) + samples_per_frame = ( + data.signals.samples_per_frame[local] + if isinstance(data.signals, ExpandedSignals) + else 1 + ) + x = ( + segment.master_start + np.arange(len(signal)) / samples_per_frame + ) / scale + axes[channel].plot(x, signal, color=f"C{channel % 10}", zorder=3) + + for segment in record.segments[1:]: + boundary = segment.master_start / scale + for axis in axes: + axis.axvline(boundary, color="0.5", linestyle="--", linewidth=0.8) + for axis in axes: + axis.set_xlim( + record.source_selection.start / scale, + record.source_selection.stop / scale, + ) + _label_figure( + axes, + len(channels), + time_units, + [str(name) for name in names], + [str(unit) for unit in units], + None, + None, + title or f"Record: {record.source_header.record_name}", + ) + except BaseException: + plt.close(fig) + raise + if return_fig: + return fig + plt.show() + + def _get_wfdb_plot_items(record, annotation, plot_sym, plot_aux=False): """Get items to plot from WFDB objects. diff --git a/tests/test_plot.py b/tests/test_plot.py index b3b16f5d..d50b4e5e 100644 --- a/tests/test_plot.py +++ b/tests/test_plot.py @@ -200,6 +200,89 @@ def test_record_data_plot_keeps_masked_samples_as_gaps(tmp_path, layout): assert values.dtype.kind == "i" +def test_segmented_plot_keeps_master_positions_and_boundaries(): + """One figure shows both selected segments at their original positions.""" + parts = wfdb.read_segments( + "sample-data/multi-segment/fixed1/v102s", + layout="uniform", + start=74996, + stop=75004, + channels=[3, 0], + ) + + fig = parts.plot(return_fig=True) + plt.close(fig) + + assert len(fig.axes) == 2 + for axis in fig.axes: + assert len(axis.lines) == 3 # two data segments and one boundary + np.testing.assert_array_equal( + axis.lines[0].get_xdata(), np.arange(74996, 75000) + ) + np.testing.assert_array_equal( + axis.lines[1].get_xdata(), np.arange(75000, 75004) + ) + assert axis.lines[2].get_xdata()[0] == 75000 + assert axis.get_xlim() == (74996, 75004) + + +def test_segmented_plot_shows_gaps_and_absent_channels(): + """A gap is shaded, while an absent channel has no invented samples.""" + parts = wfdb.read_segments( + "sample-data/multi-segment/s25047/s25047-2704-05-04-10-44", + layout="expanded", + start=25735, + stop=25750, + channel_names=["ABP", "II"], + ) + + fig = parts.plot(time_units="seconds", return_fig=True) + plt.close(fig) + + assert len(fig.axes) == 2 + assert all(len(axis.patches) == 1 for axis in fig.axes) + assert len(fig.axes[0].lines) == 1 # boundary only; ABP is absent + assert len(fig.axes[1].lines) == 2 + expected = np.arange(25740, 25750) / parts.source_header.fs + np.testing.assert_allclose(fig.axes[1].lines[0].get_xdata(), expected) + + +def test_segmented_plot_expanded_samples_use_frame_positions(): + """Four samples per frame occupy quarter-frame positions on the plot.""" + parts = wfdb.read_segments( + "sample-data/multi-segment/041s/041s", + layout="expanded", + stop=4, + channels=[0], + ) + + fig = parts.plot(return_fig=True) + plt.close(fig) + + np.testing.assert_allclose(fig.axes[0].lines[0].get_xdata(), np.arange(16) / 4) + np.testing.assert_array_equal( + fig.axes[0].lines[0].get_ydata(), parts.segments[0].data.signals.values[0] + ) + + +def test_segmented_plot_keeps_digital_masked_samples_as_gaps(tmp_path): + """Plotting segments does not turn missing digital values into markers.""" + shutil.copy("sample-data/binformats.d0", tmp_path / "part.dat") + (tmp_path / "part.hea").write_text( + "part 1 200 8\npart.dat 8 200/mV 12 0 -2047 -31143 0 I\n" + ) + (tmp_path / "multi.hea").write_text("multi/2 1 200 12\npart 8\n~ 4\n") + parts = wfdb.read_segments(tmp_path / "multi", kind="digital", layout="uniform") + + fig = parts.plot(return_fig=True) + plt.close(fig) + + plotted = fig.axes[0].lines[0].get_ydata() + mask = np.ma.getmaskarray(parts.segments[0].data.signals.values)[:, 0] + np.testing.assert_array_equal(np.isnan(plotted), mask) + assert fig.axes[0].patches[0].get_x() == 8 + + def test_annotations_outside_signal(): """Plot annotations before and after the signal at zero""" signal = np.arange(1, 101, dtype="float64") From bcd1fd25fa859d7ce1bc4f0e6b2404b1466bb45e Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 16:57:50 -0500 Subject: [PATCH 2/2] Keep digital units for empty selected segments --- src/wfdb/plot/plot.py | 2 +- tests/test_plot.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/wfdb/plot/plot.py b/src/wfdb/plot/plot.py index 784fc9f8..5604367d 100644 --- a/src/wfdb/plot/plot.py +++ b/src/wfdb/plot/plot.py @@ -1064,7 +1064,7 @@ def _plot_segmented_record( kinds = { segment.data.signals.kind for segment in record.segments - if segment.data is not None and segment.data.metadata.n_signals + if segment.data is not None } kind = next(iter(kinds), "physical") if len(kinds) > 1: diff --git a/tests/test_plot.py b/tests/test_plot.py index d50b4e5e..e3a59ffc 100644 --- a/tests/test_plot.py +++ b/tests/test_plot.py @@ -247,6 +247,29 @@ def test_segmented_plot_shows_gaps_and_absent_channels(): np.testing.assert_allclose(fig.axes[1].lines[0].get_xdata(), expected) +def test_segmented_plot_zero_channel_digital_segments_use_adu(): + """A selected channel absent from every segment still has digital units.""" + parts = wfdb.read_segments( + "sample-data/multi-segment/s25047/s25047-2704-05-04-10-44", + kind="digital", + layout="uniform", + stop=60000, + channel_names=["ABP"], + ) + assert parts.segments + assert any(segment.data is not None for segment in parts.segments) + assert all( + segment.data.metadata.n_signals == 0 + for segment in parts.segments + if segment.data is not None + ) + + fig = parts.plot(return_fig=True) + plt.close(fig) + + assert fig.axes[0].get_ylabel() == "ABP/adu" + + def test_segmented_plot_expanded_samples_use_frame_positions(): """Four samples per frame occupy quarter-frame positions on the plot.""" parts = wfdb.read_segments(