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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions changelog.d/plot-segments.rst
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions docs/plot.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
39 changes: 39 additions & 0 deletions src/wfdb/io/segment_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
106 changes: 106 additions & 0 deletions src/wfdb/plot/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
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.

Expand Down
106 changes: 106 additions & 0 deletions tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,112 @@ 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_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(
"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")
Expand Down
Loading