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
17 changes: 11 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,14 @@ 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.fs) # Sampling frequency: 360 Hz
print(record.sig_name) # ['MLII', 'V5']
print(record.p_signal.shape) # (3600, 2): samples x channels
print(record.metadata.fs) # Sampling frequency: 360 Hz
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, annotation=annotation, title="Record 100")
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
Expand All @@ -50,8 +52,11 @@ record = wfdb.read_record("path/to/record", layout="uniform")
annotation = wfdb.read_annotations("path/to/record.atr")
```

`record.p_signal` is a NumPy array of signals in physical units. Use
`kind="digital"` with `read_record` to read digital values in `record.d_signal`.
`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.

## Write a record
Expand Down
8 changes: 8 additions & 0 deletions changelog.d/recorddata-read-record.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
**Make read_record return RecordData in 6.0**
``read_record`` now returns a ``RecordData`` with one selected signal form,
fixed metadata, editable arrays, and source provenance. Use ``read_segments``
for uncombined segments. ``read_signals`` and the public ``SignalRead``
aliases are removed; ``wfdb.io.signal_values.SignalRead`` remains for old
pickles. Errors for removed names and the old ``combine_segments`` argument
name their replacements. The mutable ``Record`` and ``MultiRecord`` remain
available through ``rdrecord``. See the migration guide for code changes.
177 changes: 76 additions & 101 deletions docs/io.rst

Large diffs are not rendered by default.

109 changes: 76 additions & 33 deletions docs/migration.rst
Original file line number Diff line number Diff line change
@@ -1,22 +1,37 @@
.. _migration:

Migrating from the legacy API
=============================
Migrating to WFDB-Python 6.0
============================

WFDB-Python now has readable names for its functions, arguments and
attributes, alongside the names inherited from the WFDB C tools. This page
maps the older names to the newer ones and lists the differences that matter
when switching.

The newer function signatures are still being refined before the next major
release. Incompatible changes to recently added names will be called out in
release notes. Legacy names remain available while their replacements are
completed.
The 6.0 release changes the recently introduced selected-record API:

``read_signals`` now returns ``RecordData``. The former ``SignalRead`` name is
a deprecated alias for the same class. Accessing it through ``wfdb`` or
``wfdb.io`` warns; reading a record does not. These two public aliases will be
removed in 6.0. The internal class path remains so older pickles keep loading.
.. list-table::
:header-rows: 1

* - 5.18.0
- 6.0
* - ``read_signals(path, layout=...)`` returns ``RecordData``.
- ``read_record(path, layout=...)`` returns ``RecordData``.
* - ``read_record(path, layout=...)`` returns a mutable ``Record`` or
``MultiRecord``.
- Use ``rdrecord`` for a mutable ``Record`` or ``MultiRecord``.
* - ``read_record(..., combine_segments=False)`` returns a ``MultiRecord``.
- Use ``read_segments`` for a ``SegmentedRecordData`` with uncombined
segments, or ``rdrecord(..., m2s=False)`` for a mutable ``MultiRecord``.
* - ``wfdb.SignalRead`` and ``wfdb.io.SignalRead`` are deprecated aliases.
- Use ``RecordData``. The private ``wfdb.io.signal_values.SignalRead``
alias remains so older pickles can load.

``read_signals`` is removed without a 5.x warning because its replacement
only starts returning ``RecordData`` in 6.0. The legacy API remains available,
including ``rdrecord``, ``rdsamp``, ``rdheader``, ``wrsamp``, ``Record`` and
``MultiRecord``. Existing deprecation warnings stay; there is no planned
removal date for these legacy names.

The older names keep working, so you can switch one call at a time. Calling a
legacy function, such as ``rdrecord`` or ``Record.wrsamp``, emits a
Expand All @@ -35,6 +50,36 @@ To find the calls that need updating, run your code or tests with
deprecation warnings shown as errors, for example
``python -W error::DeprecationWarning script.py``.

Code that used 5.x ``read_record`` will now receive ``RecordData``. Its
signal values live in ``signals.values``; ``kind`` and ``layout`` determine
which form is loaded. The common field changes are:

.. list-table::
:header-rows: 1

* - 5.x mutable ``Record``
- 6.0 ``RecordData``
* - ``p_signal`` or ``d_signal``
- ``signals.values`` with ``kind="physical"`` or ``"digital"`` and
``layout="uniform"``.
* - ``e_p_signal`` or ``e_d_signal``
- ``signals.values`` with ``layout="expanded"``. Each channel is a
separate one-dimensional array.
* - ``fs``, ``n_sig``, ``sig_len``
- ``metadata.fs``, ``metadata.n_signals``, ``metadata.n_frames``.
* - ``sig_name``, ``units``
- ``[s.name for s in metadata.signals]`` and
``[s.units for s in metadata.signals]``.
* - Assigning metadata or replacing arrays
- Use ``with_channels``, ``with_comments``, ``with_calibration``,
``shift_time``, ``select``, or ``with_values``.
* - ``rec.wrsamp()``
- ``write_record(path, data)`` or ``data.write(path)``.

If you need to assign legacy fields directly, use ``rdrecord`` to get a
mutable ``Record``. In 6.0, attempts to access common legacy fields on
``RecordData`` raise ``AttributeError`` with the corresponding replacement.


A first example
---------------
Expand Down Expand Up @@ -76,8 +121,8 @@ The newer functions take one path or URI as their first argument, use
``start`` and an exclusive ``stop`` for sample ranges, and accept their other
options as keywords.

``read_signals(kind="digital")`` now returns NumPy masked arrays. Existing
code that compares digital values with a
``read_record(kind="digital")`` returns a ``RecordData`` whose
``signals.values`` are NumPy masked arrays. Existing code that compares them with a
format-specific missing marker should use
``np.ma.getmaskarray(read.signals.values)`` instead. An expanded read has one
masked array per channel. ``np.asarray`` and ``.data`` discard the mask, so
Expand All @@ -101,17 +146,16 @@ edit, smoothing, or skew alignment.

For example::

data = wfdb.read_signals("100", kind="physical", layout="uniform")
data = wfdb.read_record("100", kind="physical", layout="uniform")
data = data.select(start=100, stop=1100)
data = data.with_channels(names=["Lead II", "Lead V5"])
wfdb.write_record("output/copy", data)

``read_segments`` returns a ``SegmentedRecordData`` when the original segment
boundaries matter. Its entries retain their order and frame positions;
``~`` gaps have no data, and real segments contain ``RecordData`` values.
The segments are loaded eagerly. In 5.x, ``read_record`` still returns the
mutable ``Record`` or ``MultiRecord``; its 6.0 return-type change has not
landed in this release.
The segments are loaded eagerly. ``read_record`` always returns one combined
``RecordData``; use ``read_segments`` to retain source boundaries.

``shift_time`` leaves the source header, comments, annotations, and counter
fields unchanged. Check those separately when preparing de-identified data.
Expand Down Expand Up @@ -155,9 +199,10 @@ Functions
- Notes
* - ``rdrecord``
- ``read_record``
- Returns the same mutable ``Record`` or ``MultiRecord``.
- Returns ``RecordData`` with fixed metadata and editable signal values.
Use ``rdrecord`` when the mutable ``Record`` is needed.
* - ``rdsamp``
- ``read_signals``
- ``read_record``
- Returns a ``RecordData`` with ``signals`` and ``metadata`` rather than
an ``(array, fields)`` pair. ``layout`` is required.
* - ``rdheader``
Expand Down Expand Up @@ -238,14 +283,12 @@ Reading arguments
-
* - ``smooth_frames=True`` or ``False``
- ``layout="uniform"`` or ``"expanded"``
- ``read_signals`` and ``read_record`` both require ``layout``.
- ``read_record`` requires ``layout``.
* - ``m2s``
- ``combine_segments``
- ``read_signals`` always combines segments. ``read_segments`` returns a
``SegmentedRecordData`` with each source segment preserved. In 5.x,
``read_record(..., combine_segments=False)`` still returns a
``MultiRecord``; 6.0 will remove that option in favor of
``read_segments``. ``rdrecord`` keeps its ``MultiRecord`` path.
- ``read_segments``
- ``read_record`` always combines segments. ``read_segments`` returns a
``SegmentedRecordData`` with each source segment preserved.
``rdrecord(..., m2s=False)`` still returns a mutable ``MultiRecord``.
* - ``return_res``
- ``resolution``
- Selects the numeric width in bits.
Expand All @@ -262,8 +305,8 @@ Reading arguments
- A ``physionet://`` or HTTP URL in ``path``
- See `Remote sources`_.

``ignore_skew=True`` becomes ``signal_alignment="raw"`` on ``read_record``,
``read_signals``, and ``iter_dataframes``. Their default is ``"aligned"``.
``ignore_skew=True`` becomes ``signal_alignment="raw"`` on ``read_record``
and ``iter_dataframes``. Their default is ``"aligned"``.
The legacy ``rdrecord`` keeps ``ignore_skew``. ``channels``,
``channel_names`` and ``force_channels`` keep their names.

Expand All @@ -273,7 +316,7 @@ The legacy ``rdrecord`` keeps ``ignore_skew``. ``channels``,
``return_res`` with ``resolution``, and ``pn_dir`` with a complete
``physionet://`` URI in ``path``. It always returns uniform DataFrames,
averaging channels with multiple samples per frame; there is no ``layout``
argument. Use ``read_signals`` with ``layout="expanded"`` when every channel
argument. Use ``read_record`` with ``layout="expanded"`` when every channel
sample is needed.


Expand Down Expand Up @@ -392,11 +435,11 @@ Put the source in the path instead:
* - ``rdrecord("100", pn_dir="mitdb/1.0.0")``
- ``read_record("physionet://mitdb/1.0.0/100", layout="uniform")``
* - ``rdrecord("100", pn_dir="mitdb")``
- ``read_record("physionet://mitdb/latest/100", layout="uniform")``; pin a version for
reproducible results
- ``read_record("physionet://mitdb/latest/100", layout="uniform")``;
pin a version for reproducible results
* - ``set_db_index_url(url)`` with ``pn_dir``
- A complete HTTP URL, such as
``read_record("https://mirror.example.org/files/mitdb/1.0.0/100", layout="uniform")``
``read_record("https://mirror.example.org/mitdb/100", layout="uniform")``

See :ref:`reading-from-physionet` and :ref:`reading-from-custom-http-server`.
Cloud storage URIs such as ``s3://`` and local ``.wfdb`` archives work the
Expand All @@ -410,12 +453,12 @@ Behaviour differences
The newer functions are stricter in a few places, so that mistakes fail
clearly instead of producing surprising results:

- ``read_record`` and ``read_signals`` raise ``ValueError`` for channel names
- ``read_record`` raises ``ValueError`` for channel names
that are not in the record, listing the available names. Pass
``missing_channels="ignore"`` to skip them, as ``rdrecord`` does. Duplicate
channels, an empty selection, or a single name passed as a string also
raise errors.
- ``read_signals`` returns the same container type whatever the number of
- ``read_record`` returns the same container type whatever the number of
channels: a 2D array for ``layout="uniform"``, and a tuple of 1D arrays for
``layout="expanded"``. For one channel, use ``values[:, 0]`` or
``values[0]``.
Expand Down
22 changes: 7 additions & 15 deletions src/wfdb/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import warnings
from typing import TYPE_CHECKING

from wfdb.io.annotation import (
Annotation,
merge_annotations,
Expand Down Expand Up @@ -61,7 +58,6 @@
read_header,
read_multi_segment_headers,
read_record,
read_signals,
sampfreq,
signame,
wfdbdesc,
Expand All @@ -75,19 +71,15 @@
from wfdb.plot.plot import plot_all_records, plot_items, plot_wfdb
from wfdb.version import __version__

if TYPE_CHECKING:
SignalRead = RecordData


def __getattr__(name: str):
"""Warn when the historical name for a loaded record is requested."""
"""Explain the 6.0 replacements for removed selected-read names."""
if name == "read_signals":
raise AttributeError(
"wfdb.read_signals was removed in 6.0; use wfdb.read_record instead"
)
if name == "SignalRead":
warnings.warn(
"wfdb.SignalRead is deprecated; use wfdb.RecordData instead (see "
"the migration guide). The legacy name will be removed in a "
"future major release.",
DeprecationWarning,
stacklevel=2,
raise AttributeError(
"wfdb.SignalRead was removed in 6.0; use wfdb.RecordData instead"
)
return RecordData
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
22 changes: 7 additions & 15 deletions src/wfdb/io/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import warnings
from typing import TYPE_CHECKING

from wfdb.io._signal import est_res, wr_dat_file
from wfdb.io.annotation import (
Annotation,
Expand Down Expand Up @@ -62,7 +59,6 @@
read_header,
read_multi_segment_headers,
read_record,
read_signals,
sampfreq,
signame,
wfdbdesc,
Expand All @@ -74,19 +70,15 @@
from wfdb.io.signal_values import ExpandedSignals, RecordData, UniformSignals
from wfdb.io.signal_write import write_signals

if TYPE_CHECKING:
SignalRead = RecordData


def __getattr__(name: str):
"""Warn when the historical name for a loaded record is requested."""
"""Explain the 6.0 replacements for removed selected-read names."""
if name == "read_signals":
raise AttributeError(
"wfdb.io.read_signals was removed in 6.0; use wfdb.io.read_record instead"
)
if name == "SignalRead":
warnings.warn(
"wfdb.io.SignalRead is deprecated; use wfdb.io.RecordData instead "
"(see the migration guide). The legacy name will be removed in "
"a future major release.",
DeprecationWarning,
stacklevel=2,
raise AttributeError(
"wfdb.io.SignalRead was removed in 6.0; use wfdb.io.RecordData instead"
)
return RecordData
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
Loading
Loading