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
208 changes: 114 additions & 94 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions changelog.d/recorddata-plot.rst
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 4 additions & 11 deletions demo.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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()"
]
},
Expand All @@ -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(...)`."
]
},
{
Expand Down Expand Up @@ -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()"
]
Expand Down
3 changes: 3 additions & 0 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs/plot.rst
Original file line number Diff line number Diff line change
@@ -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
20 changes: 20 additions & 0 deletions src/wfdb/io/signal_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading