diff --git a/README.md b/README.md index bfbce19e..cda1d4c5 100644 --- a/README.md +++ b/README.md @@ -1,148 +1,168 @@ # WFDB for Python -Read, write, plot, and process physiologic waveforms and annotations with -Python. WFDB works with local files and records hosted on -[PhysioNet](https://physionet.org/), so you can move from a published dataset -to NumPy arrays in a few lines of code. +Read, write, and analyze physiologic waveforms and annotations in the +[WFDB format](https://wfdb.io/). WFDB-Python works with local files, records +published on [PhysioNet](https://physionet.org/), and supported cloud storage. [![PyPI](https://img.shields.io/pypi/v/wfdb)](https://pypi.org/project/wfdb/) [![Docs](https://img.shields.io/badge/docs-online-blue)](https://wfdb.readthedocs.io/) -![ECG](https://raw.githubusercontent.com/MIT-LCP/wfdb-python/main/demo-img.png) +![ECG example](https://raw.githubusercontent.com/MIT-LCP/wfdb-python/main/demo-img.png) ## Install -WFDB requires Python 3.11 or newer. Install it from PyPI: +WFDB-Python requires Python 3.11 or newer: ```sh pip install wfdb ``` -If you use [uv](https://docs.astral.sh/uv/), run `uv add wfdb` instead. On -some systems, the `soundfile` dependency also needs a separate installation -of `libsndfile`; see the -[soundfile installation notes](https://pypi.org/project/soundfile/). +With [uv](https://docs.astral.sh/uv/), use `uv add wfdb`. On some systems, +`soundfile` also needs a separate installation of `libsndfile`; see its +[installation notes](https://pypi.org/project/soundfile/). -## Quick start +## Start with a record -Read ten seconds of ECG and its beat annotations from the -[MIT-BIH Arrhythmia Database](https://physionet.org/content/mitdb/): +Read ten seconds of ECG from the +[MIT-BIH Arrhythmia Database](https://physionet.org/content/mitdb/) +directly from PhysioNet: ```python import wfdb record = wfdb.read_record("physionet://mitdb/1.0.0/100", layout="uniform", stop=3600) -annotation = wfdb.read_annotations("physionet://mitdb/1.0.0/100.atr", stop=3600) - -print(record.metadata.fs) # Sampling frequency: 360 Hz +print(record.signals.values.shape) # (3600, 2): frames x channels +print(record.metadata.fs) # 360 frames per second print([channel.name for channel in record.metadata.signals]) # ['MLII', 'V5'] -print(record.signals.values.shape) # (3600, 2): samples x channels -print(annotation.sample[:5]) # Sample positions of the first five annotations - -wfdb.plot_wfdb( - record=record.to_legacy_record(), annotation=annotation, title="Record 100" -) ``` -The `physionet://` URI reads data from PhysioNet. For local files, pass the -record stem to `read_record` and the annotation filename to `read_annotations`: +`read_record` returns `RecordData`: editable signal arrays, fixed metadata, +and information about the source. `layout="uniform"` gives one value per +channel per frame; `layout="expanded"` retains every sample when a channel +has several samples per frame. Physical values are the default. For digital +integers and a mask of missing samples, pass `kind="digital"`. + +For local files, pass a record stem or a `.hea` path instead of a URI: ```python record = wfdb.read_record("path/to/record", layout="uniform") -annotation = wfdb.read_annotations("path/to/record.atr") ``` -`record.signals.values` is a NumPy array of signals in physical units. Use -`kind="digital"` with `read_record` for digital values, including a mask for -missing samples. `read_record` returns a `RecordData` with fixed metadata and -editable signal values. `rdrecord` remains available when you need a mutable -legacy `Record`. -Annotations provide sample positions, symbols, and other label information. +| Task | API | +| --- | --- | +| Read a selected, combined record | `read_record` | +| Inspect a header without loading samples | `read_header` | +| Keep a multi-segment record's boundaries | `read_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` | +| Check files before sharing | `wfdb check` | + +## Annotations and plots + +Read beat annotations from the same record: + +```python +annotations = wfdb.read_annotations("physionet://mitdb/1.0.0/100.atr", stop=3600) +print(annotations.sample_indices[:5]) +print(annotations.symbols[:5]) + +record.plot( + annotation=annotations, + plot_sym=True, + title="MIT-BIH record 100", +) +``` + +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. -## Write a record +## Write records -Create a WFDB header and signal file from a NumPy array: +Use `write_record` to save a loaded or edited `RecordData`; it already has +channel names, sampling frequency, and other metadata: + +```python +selected = record.select(start=0, stop=1000) +wfdb.write_record("selected", selected) +``` + +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: ```python import numpy as np -import wfdb signal = np.array([0.0, 0.2, 0.0, -0.2])[:, None] -wfdb.wrsamp( +wfdb.write_signals( "example", + signal, fs=250, + kind="physical", + formats="16", + channel_names=["ECG"], units=["mV"], - sig_name=["ECG"], - p_signal=signal, - fmt=["16"], ) ``` -This writes `example.hea` and `example.dat` in the current directory. See -[`wrann`](https://wfdb.readthedocs.io/en/latest/io.html#wfdb.io.wrann) -to write annotations. +This writes `example.hea` and `example.dat`. The input has one column per +channel; `formats` specifies the WFDB storage format. See the +[writing guide](https://wfdb.readthedocs.io/en/latest/io.html) for expanded +signals, digital calibration, missing samples, archives, and +`write_annotations`. -## Check records before sharing +## Check a dataset -Check a local record or dataset directory for common WFDB file problems: +Before sharing local files, check a record or a whole directory: ```sh wfdb check path/to/record.hea wfdb check path/to/dataset ``` -The command checks `.hea` files and `.wfdb` archives, including header syntax, -record names, referenced signal and segment files, and the first signal frame. -It reports the affected file and exits with status 1 when it finds a problem. -Other files in the dataset, such as PDFs and CSVs, are ignored. This is a -preflight check; it does not read every sample or validate annotations. -See the [record checking documentation][record-checking] for the Python -`check_record()` and `check_dataset()` functions. - -[record-checking]: https://wfdb.readthedocs.io/en/latest/io.html#checking-wfdb-records - -## What else can you do? - -- **Work with remote data:** Use a `physionet://` URI for PhysioNet or a - complete HTTP URL for another server. Supported cloud URIs include `s3://` - and `gs://` when the corresponding `fsspec` backend is installed. The older - `pn_dir` argument still works with legacy readers such as `rdrecord` and - `rdann`, but is deprecated. Newer readers require a complete path or URI. -- **Find local records:** Use `find_record()` with an ordered list of - directories, or `wfdb_search_path()` to read local directories from the - `WFDB` environment variable. See the - [source location guide](https://wfdb.readthedocs.io/en/latest/io.html#source-locations). -- **Use WFDB archives:** Read local `.wfdb` archives containing a record and - its annotations. See the - [archive documentation](https://wfdb.readthedocs.io/en/latest/io.html#wfdb-archives). -- **Analyze signals:** Use the - [processing tools](https://wfdb.readthedocs.io/en/latest/processing.html) - for tasks such as resampling and QRS detection. -- **Convert formats:** See the - [conversion guide](https://wfdb.readthedocs.io/en/latest/convert.html) - for supported waveform formats. - -WFDB-Python follows the open -[WFDB specifications](https://github.com/wfdb/wfdb-spec/). It is inspired by -the original [WFDB Software Package](https://physionet.org/content/wfdb/), -but its Python API is documented separately. The -[WFDB project website](https://wfdb.io/) introduces the format and the -other WFDB implementations. - -## Documentation and help - -The [documentation](https://wfdb.readthedocs.io/) covers the full -[I/O API](https://wfdb.readthedocs.io/en/latest/io.html), -[plotting](https://wfdb.readthedocs.io/en/latest/plot.html), and -[processing](https://wfdb.readthedocs.io/en/latest/processing.html). The +The checker reports header syntax problems, missing referenced signal or +segment files, and problems in the first signal frame. It checks `.hea` files +and `.wfdb` archives while ignoring unrelated PDFs and CSVs. This is a +preflight check, not a full scan of every sample or annotation. See the +[checking guide](https://wfdb.readthedocs.io/en/latest/io.html#checking-wfdb-records) +for `check_record()` and `check_dataset()`. + +## More ways to use WFDB + +- **Remote records:** Use a `physionet://` URI, an HTTP URL, or a supported + `fsspec` cloud URI such as `s3://` or `gs://`. See + [source locations](https://wfdb.readthedocs.io/en/latest/io.html#source-locations). +- **Archives:** Read and write `.wfdb` archives. See the + [archive guide](https://wfdb.readthedocs.io/en/latest/io.html#wfdb-archives). +- **Signal processing:** Resample signals and detect beats with the + [processing tools](https://wfdb.readthedocs.io/en/latest/processing.html). +- **Conversions:** See the + [conversion guide](https://wfdb.readthedocs.io/en/latest/convert.html). + +## Upgrading from 5.x + +In 6.0, `read_record` returns `RecordData` instead of a mutable `Record` or +`MultiRecord`. `read_signals` has been removed; use `read_record` instead. +Use `read_segments` when you need uncombined segments, or `rdrecord` when you +need a mutable legacy object. The legacy API remains available. The +[6.0 migration guide](https://wfdb.readthedocs.io/en/latest/migration.html) +maps the old fields and calls to their replacements. + +## Documentation and community + +The [documentation](https://wfdb.readthedocs.io/) covers the full API. The [demo notebook](https://github.com/MIT-LCP/wfdb-python/blob/main/demo.ipynb) -is an offline walkthrough using bundled sample data. Report bugs or request -features in the -[issue tracker](https://github.com/MIT-LCP/wfdb-python/issues). - -## Contributing and citing +walks through bundled sample data offline. Report bugs and request features +in the [issue tracker](https://github.com/MIT-LCP/wfdb-python/issues). See [DEVELOPING.md](https://github.com/MIT-LCP/wfdb-python/blob/main/DEVELOPING.md) -for setup, testing, and contribution guidance. If you use WFDB-Python in -research, please cite its +to contribute. If you use WFDB-Python in research, please cite its [PhysioNet publication](https://physionet.org/content/wfdb-python/). + +WFDB-Python follows the open +[WFDB specifications](https://github.com/wfdb/wfdb-spec/) and is inspired by +the original [WFDB Software Package](https://physionet.org/content/wfdb/). +The [WFDB project website](https://wfdb.io/) introduces the format and its +other implementations. diff --git a/changelog.d/recorddata-plot.rst b/changelog.d/recorddata-plot.rst new file mode 100644 index 00000000..425e1f4d --- /dev/null +++ b/changelog.d/recorddata-plot.rst @@ -0,0 +1,6 @@ +**Plot RecordData directly** + ``RecordData.plot(...)`` now plots selected physical or digital values and + optional annotations without converting to a legacy ``Record``. The existing + ``plot_wfdb`` function also accepts ``RecordData``. Masked digital samples + appear as gaps, including for format 8. Channel labels retain their unit + separator when annotations name additional channels. diff --git a/demo.ipynb b/demo.ipynb index 6feba5a3..cd349d8b 100644 --- a/demo.ipynb +++ b/demo.ipynb @@ -68,11 +68,7 @@ "metadata": {}, "outputs": [], "source": [ - "fig = wfdb.plot_wfdb(\n", - " record=record.to_legacy_record(),\n", - " title=\"MIT-BIH record 100\",\n", - " return_fig=True,\n", - ")\n", + "fig = record.plot(title=\"MIT-BIH record 100\", return_fig=True)\n", "plt.show()" ] }, @@ -82,8 +78,7 @@ "source": [ "`read_record` loads one signal representation at a time. `kind=\"digital\"`\n", "returns masked integer arrays; `kind=\"physical\"` returns floating values.\n", - "`plot_wfdb` still takes a legacy `Record`, so the plot above uses\n", - "`to_legacy_record()` at that boundary." + "The record can be plotted directly with `record.plot(...)`." ] }, { @@ -122,10 +117,8 @@ "print(annotations.sample_indices[:5])\n", "print(annotations.symbols[:5])\n", "\n", - "fig = wfdb.plot_wfdb(\n", - " record=record.to_legacy_record(), annotation=annotations,\n", - " title=\"Signal and annotations\",\n", - " return_fig=True,\n", + "fig = record.plot(\n", + " annotation=annotations, title=\"Signal and annotations\", return_fig=True\n", ")\n", "plt.show()" ] diff --git a/docs/io.rst b/docs/io.rst index a8aaad58..940d1ea9 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -23,6 +23,9 @@ physical or digital values. The required ``layout`` is ``"uniform"`` to average multiple samples per frame or ``"expanded"`` to retain every sample. Multi-segment records are combined. Use ``read_segments`` for uncombined segments, or ``rdrecord`` for the mutable legacy ``Record`` or ``MultiRecord``. +Call ``record.plot(annotation=..., return_fig=True)`` to plot a ``RecordData`` +directly. ``plot_wfdb`` also accepts it alongside legacy ``Record`` objects. +Masked digital samples appear as gaps in the plot. When selecting channels by name, ``read_record`` raises an error if any requested name is absent from the source header. Use diff --git a/docs/plot.rst b/docs/plot.rst index ef947d3a..929d75c5 100644 --- a/docs/plot.rst +++ b/docs/plot.rst @@ -1,5 +1,9 @@ plot ---- +``RecordData.plot(...)`` plots the result of ``read_record`` directly, with +optional annotations. ``plot_wfdb`` accepts both modern ``RecordData`` and +legacy ``Record`` objects. + .. automodule:: wfdb.plot :members: plot_items, plot_wfdb, plot_all_records diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index 3c912cfe..261c9438 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -174,6 +174,26 @@ def __getattr__(self, name: str): raise AttributeError(f"RecordData has no attribute {name!r}; {hint}") raise AttributeError(f"RecordData has no attribute {name!r}") + def plot(self, annotation=None, **kwargs): + """Plot this record and optional annotations. + + Parameters + ---------- + annotation : Annotation, optional + Annotations to overlay on the signal channels. + **kwargs + Plot options accepted by ``plot_wfdb``, including + ``time_units``, ``title``, and ``return_fig``. + + Returns + ------- + matplotlib.figure.Figure or None + The figure when ``return_fig=True``; otherwise show the plot. + """ + from wfdb.plot.plot import plot_wfdb + + return plot_wfdb(record=self, annotation=annotation, **kwargs) + def __setstate__(self, state: dict) -> None: """Load saved reads that predate the private reader model.""" restored = dict(state) diff --git a/src/wfdb/plot/plot.py b/src/wfdb/plot/plot.py index 1d0d641c..c38ba547 100644 --- a/src/wfdb/plot/plot.py +++ b/src/wfdb/plot/plot.py @@ -4,6 +4,7 @@ import numpy as np from wfdb.io.record import rdrecord +from wfdb.io.signal_values import ExpandedSignals, RecordData from wfdb.io.util import downround, upround @@ -879,12 +880,10 @@ def plot_wfdb( This function implements the base functionality of the `plot_items` function, while allowing direct input of WFDB objects. - If the record object is input, the function will extract from it: - - signal values, from the `e_p_signal`, `e_d_signal`, `p_signal`, or - `d_signal` attribute (in that order of priority.) - - frame frequency, from the `fs` attribute - - signal names, from the `sig_name` attribute - - signal units, from the `units` attribute + If a ``Record`` or ``RecordData`` is input, the function extracts: + - loaded signal values, from the selected form on ``RecordData`` or + the first available signal array on ``Record`` + - frame frequency, channel names, and units from the record metadata If the annotation object is input, the function will extract from it: - sample locations, from the `sample` attribute @@ -896,8 +895,8 @@ def plot_wfdb( Parameters ---------- - record : WFDB Record, optional - The Record object to be plotted. + record : Record or RecordData, optional + The loaded record to be plotted. annotation : WFDB Annotation, optional The Annotation object to be plotted. plot_sym : bool, optional @@ -974,7 +973,14 @@ def plot_wfdb( ) if record: - if record.e_p_signal is not None or record.e_d_signal is not None: + if isinstance(record, RecordData): + if isinstance(record.signals, ExpandedSignals): + sampling_freq = [ + spf * record.metadata.fs for spf in record.signals.samples_per_frame + ] + else: + sampling_freq = record.metadata.fs + elif record.e_p_signal is not None or record.e_d_signal is not None: sampling_freq = [spf * record.fs for spf in record.samps_per_frame] else: sampling_freq = record.fs @@ -999,7 +1005,7 @@ def plot_wfdb( if annotation and annotation.fs is not None: ann_freq = annotation.fs elif record: - ann_freq = record.fs + ann_freq = fs else: ann_freq = None @@ -1025,13 +1031,29 @@ def plot_wfdb( ) +def _record_data_plot_values(record): + """Replace masked digital samples with gaps in a plotting-only view.""" + values = record.signals.values + if record.signals.kind != "digital": + return values + + def visible(array): + if np.ma.isMaskedArray(array) and np.ma.is_masked(array): + return array.astype("float64").filled(np.nan) + return array + + if isinstance(record.signals, ExpandedSignals): + return tuple(visible(array) for array in values) + return visible(values) + + def _get_wfdb_plot_items(record, annotation, plot_sym, plot_aux=False): """Get items to plot from WFDB objects. Parameters ---------- - record : WFDB Record - The Record object to be plotted + record : Record or RecordData + The loaded record to be plotted annotation : WFDB Annotation The Annotation object to be plotted plot_sym : bool @@ -1085,7 +1107,25 @@ def _get_wfdb_plot_items(record, annotation, plot_sym, plot_aux=False): """ # Get record attributes if record: - if record.e_p_signal is not None: + if isinstance(record, RecordData): + signal = _record_data_plot_values(record) + n_sig = ( + len(signal) + if isinstance(record.signals, ExpandedSignals) + else signal.shape[1] + ) + if n_sig == 0: + raise ValueError("The record has no signal to plot") + fs = record.metadata.fs + sig_name = [str(s.name) for s in record.metadata.signals] + sig_units = ( + [str(s.units) for s in record.metadata.signals] + if record.signals.kind == "physical" + else ["adu"] * n_sig + ) + record_name = "Record: %s" % record.metadata.record_name + ylabel = ["/".join(pair) for pair in zip(sig_name, sig_units)] + elif record.e_p_signal is not None: signal = record.e_p_signal n_sig = len(signal) physical = True @@ -1104,14 +1144,15 @@ def _get_wfdb_plot_items(record, annotation, plot_sym, plot_aux=False): else: raise ValueError("The record has no signal to plot") - fs = record.fs - sig_name = [str(s) for s in record.sig_name] - if physical: - sig_units = [str(s) for s in record.units] - else: - sig_units = ["adu"] * n_sig - record_name = "Record: %s" % record.record_name - ylabel = ["/".join(pair) for pair in zip(sig_name, sig_units)] + if not isinstance(record, RecordData): + fs = record.fs + sig_name = [str(s) for s in record.sig_name] + if physical: + sig_units = [str(s) for s in record.units] + else: + sig_units = ["adu"] * n_sig + record_name = "Record: %s" % record.record_name + ylabel = ["/".join(pair) for pair in zip(sig_name, sig_units)] else: signal = fs = ylabel = record_name = sig_units = None @@ -1180,7 +1221,7 @@ def _get_wfdb_plot_items(record, annotation, plot_sym, plot_aux=False): if compact_ann_aux is not None: compact_ann_aux.append(ann_aux[ch] if ch in ann_chans else None) if ch in sig_chans: - ylabel.append("".join([sig_name[ch], sig_units[ch]])) + ylabel.append("/".join([sig_name[ch], sig_units[ch]])) else: ylabel.append("ch_%d/NU" % ch) ann_samp = compact_ann_samp diff --git a/tests/test_plot.py b/tests/test_plot.py index 00558462..b3b16f5d 100644 --- a/tests/test_plot.py +++ b/tests/test_plot.py @@ -1,3 +1,4 @@ +import shutil import warnings import matplotlib.pyplot as plt @@ -133,6 +134,72 @@ def test_digital_multifrequency(self): ) +def test_record_data_plot_with_annotations(): + """RecordData plots its selected values and optional annotations.""" + record = wfdb.read_record("sample-data/100", layout="uniform", stop=1000) + annotation = wfdb.read_annotations("sample-data/100.atr", stop=1000) + + fig = record.plot(annotation=annotation, plot_sym=True, return_fig=True) + plt.close(fig) + + assert len(fig.axes) == 2 + np.testing.assert_array_equal( + fig.axes[0].lines[0].get_ydata(), record.signals.values[:, 0] + ) + assert fig.axes[0].get_ylabel() == "MLII/mV" + + +def test_plot_wfdb_accepts_record_data_directly(): + """The existing plotting function also accepts the modern read result.""" + record = wfdb.read_record( + "sample-data/100", kind="digital", layout="uniform", stop=100 + ) + + fig = wfdb.plot_wfdb(record, return_fig=True) + plt.close(fig) + + assert len(fig.axes) == 2 + np.testing.assert_array_equal( + fig.axes[0].lines[0].get_ydata(), record.signals.values[:, 0] + ) + assert fig.axes[0].get_ylabel() == "MLII/adu" + + +def test_record_data_plot_expanded_sample_frequencies(): + """Expanded channels use their own samples-per-frame frequencies.""" + record = wfdb.read_record("sample-data/test01_00s_frame", layout="expanded", stop=4) + + fig = record.plot(time_units="seconds", return_fig=True) + plt.close(fig) + + assert len(fig.axes) == 3 + for index, values in enumerate(record.signals.values): + np.testing.assert_array_equal(fig.axes[index].lines[0].get_ydata(), values) + expected = np.arange(len(values)) / ( + record.metadata.fs * record.signals.samples_per_frame[index] + ) + np.testing.assert_allclose(fig.axes[index].lines[0].get_xdata(), expected) + + +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_record_data_plot_keeps_masked_samples_as_gaps(tmp_path, layout): + """Digital gaps plot as missing, including in markerless format 8.""" + 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") + record = wfdb.read_record(tmp_path / "multi", kind="digital", layout=layout) + values = record.signals.values if layout == "uniform" else record.signals.values[0] + + fig = record.plot(return_fig=True) + plt.close(fig) + + yvalues = fig.axes[0].lines[0].get_ydata() + np.testing.assert_array_equal(np.isnan(yvalues), np.ma.getmaskarray(values).ravel()) + assert values.dtype.kind == "i" + + def test_annotations_outside_signal(): """Plot annotations before and after the signal at zero""" signal = np.arange(1, 101, dtype="float64") @@ -260,6 +327,7 @@ def test_plot_wfdb_aux_notes_with_sparse_channels(): plt.close(fig) assert len(fig.axes) == 3 + assert [ax.get_ylabel() for ax in fig.axes] == ["MLII/mV", "V5/mV", "ch_3/NU"] assert [text.get_text() for text in fig.axes[0].texts] == ["Lead note"] assert not fig.axes[1].texts assert [text.get_text() for text in fig.axes[2].texts] == ["Extra channel note"]