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
2 changes: 2 additions & 0 deletions changelog.d/physionet-uris.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
**Read records from PhysioNet with physionet:// URIs**
``rdrecord``, ``rdsamp``, ``rdheader`` and ``rdann`` now accept ``physionet://`` URIs such as ``physionet://mitdb/1.0.0/100``, which read from PhysioNet through the ``physionet`` package, now a dependency. Only the parts of signal files that are needed are read (header and annotation files are read in full), and restricted databases can be read after ``physionet login``. ``fsspec`` 2025.7.0 or later is now required, as for the ``physionet`` package.
30 changes: 30 additions & 0 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,36 @@ handles credential discovery automatically.
against the configured PhysioNet index URL.


Reading From PhysioNet
----------------------

Records and annotations on PhysioNet can also be read with a
``physionet://`` URI, using the ``physionet`` package (a dependency of
``wfdb``). The URI is the database, its version and the record name, as in
``physionet://mitdb/1.0.0/100``. Use ``latest`` as the version to read the
newest one.

.. code-block:: python

import wfdb

record = wfdb.rdrecord("physionet://mitdb/1.0.0/100", sampto=3600)
ann = wfdb.rdann("physionet://mitdb/1.0.0/100", "atr")

Files are read with HTTP range requests: open databases from the AWS open
data mirror, and restricted ones from PhysioNet. For signal files, only the
parts that hold the samples that are needed are read, so reading a few
seconds of a long recording does not download the whole file. Header and
annotation files are read in full (``rdann`` reads the whole annotation
file, even with ``sampto``). Files that the ``physionet`` package has
already downloaded into its cache are read from there.

Restricted databases can be read once you have access to them on PhysioNet
and have signed in, by running ``physionet login`` once in a terminal (or
setting ``PHYSIONET_TOKEN``). See the `physionet package
<https://github.com/MIT-LCP/physionet>`_ for details.


Reading From Memory
-------------------

Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ dependencies = [
"soundfile >= 0.12.1",
"matplotlib >= 3.8.0",
"requests >= 2.31.0",
"fsspec >= 2023.10.0",
"fsspec >= 2025.7.0",
"aiohttp >= 3.10.11",
"physionet >= 0.6.0",
]

[project.urls]
Expand Down
31 changes: 29 additions & 2 deletions src/wfdb/io/_coreio.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,34 @@
from wfdb.io.download import config

# Cloud protocols
CLOUD_PROTOCOLS = ["az://", "azureml://", "s3://", "gs://", "memory://"]
CLOUD_PROTOCOLS = ["az://", "azureml://", "s3://", "gs://", "memory://", "physionet://"]


def _fsspec_open(path, mode="rb", **kwargs):
"""Open a local path or cloud URI with `fsspec.open`.

Files with a `physionet://` URI are read in parts as they are needed,
with HTTP range requests, instead of being downloaded in full, and
without progress bars.

Parameters
----------
path : str
The local path or cloud URI.
mode : str, optional
The mode to open the file in.
kwargs : dict, optional
Passed to `fsspec.open`.

Returns
-------
fsspec.core.OpenFile
The file to open, as a context manager.

"""
if os.fspath(path).startswith("physionet://"):
kwargs = {"stream": True, "show_progress": False, **kwargs}
return fsspec.open(path, mode, **kwargs)


def _split_path(record_name):
Expand Down Expand Up @@ -103,7 +130,7 @@ def _open_file(

"""
if pn_dir is None:
return fsspec.open(
return _fsspec_open(
file_name,
mode,
buffering=buffering,
Expand Down
7 changes: 4 additions & 3 deletions src/wfdb/io/_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import os
import sys

import fsspec
import numpy as np

from wfdb.io import _coreio, download, util
Expand Down Expand Up @@ -1709,7 +1708,7 @@ def _rd_dat_file(

# Local or cloud dat file
elif pn_dir is None:
with fsspec.open(_coreio._join_path(dir_name, file_name), "rb") as fp:
with _coreio._fsspec_open(_coreio._join_path(dir_name, file_name), "rb") as fp:
fp.seek(start_byte)
sig_data = util.fromfile(
fp, dtype=np.dtype(DATA_LOAD_TYPES[fmt]), count=element_count
Expand Down Expand Up @@ -2600,7 +2599,9 @@ def _infer_sig_len(

# If this is a cloud path, use fsspec to open the file
elif any(dir_name.startswith(proto) for proto in CLOUD_PROTOCOLS):
with fsspec.open(_coreio._join_path(dir_name, file_name), mode="rb") as f:
with _coreio._fsspec_open(
_coreio._join_path(dir_name, file_name), mode="rb"
) as f:
file_size = f.seek(0, os.SEEK_END)

# If the PhysioNet database path is provided, construct the download path using the
Expand Down
5 changes: 2 additions & 3 deletions src/wfdb/io/annotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
import re
import sys

import fsspec
import numpy as np
import pandas as pd

from wfdb.io import _header, download, record, util
from wfdb.io._coreio import CLOUD_PROTOCOLS
from wfdb.io._coreio import CLOUD_PROTOCOLS, _fsspec_open
from wfdb.io.archive import WFDBArchive, is_archive_path


Expand Down Expand Up @@ -2131,7 +2130,7 @@ def load_byte_pairs(record_name, extension, pn_dir):
"""
# local or cloud file
if pn_dir is None:
with fsspec.open(record_name + "." + extension, "rb") as f:
with _fsspec_open(record_name + "." + extension, "rb") as f:
filebytes = util.fromfile(f, "<u1").reshape([-1, 2])

# PhysioNet file
Expand Down
67 changes: 43 additions & 24 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
import posixpath
import re

import fsspec
import numpy as np
import pandas as pd

from wfdb.io import _header, _signal, _url, download, header, util
from wfdb.io._coreio import CLOUD_PROTOCOLS, _join_path, _split_path
from wfdb.io._coreio import CLOUD_PROTOCOLS, _fsspec_open, _join_path, _split_path
from wfdb.io.archive import WFDBArchive, archive_for_writing, is_archive_path

# -------------- WFDB Signal Calibration and Classification ---------- #
Expand Down Expand Up @@ -169,8 +168,10 @@ class BaseRecord:
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
n_sig : int, optional
Total number of signals.
fs : int, float, optional
Expand Down Expand Up @@ -700,8 +701,10 @@ class Record(BaseRecord, _header.HeaderMixin, _signal.SignalMixin):
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
n_sig : int, optional
Total number of signals.
fs : float, optional
Expand Down Expand Up @@ -1082,8 +1085,10 @@ class MultiRecord(BaseRecord, _header.MultiHeaderMixin):
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
n_sig : int, optional
Total number of signals.
fs : int, float, optional
Expand Down Expand Up @@ -1839,8 +1844,10 @@ def rdheader(record_name, pn_dir=None, rd_segments=False):
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
To read the header from a local .wfdb archive, pass the path of
the archive including the .wfdb extension.
pn_dir : str, optional
Expand Down Expand Up @@ -1877,7 +1884,7 @@ def rdheader(record_name, pn_dir=None, rd_segments=False):

# If this is a cloud path, use fsspec to open the file
if any(dir_name.startswith(proto) for proto in CLOUD_PROTOCOLS):
with fsspec.open(_join_path(dir_name, file_name), mode="r") as f:
with _fsspec_open(_join_path(dir_name, file_name), mode="r") as f:
header_content = f.read()

# If the PhysioNet database path is provided, construct the download path using the
Expand All @@ -1900,7 +1907,7 @@ def rdheader(record_name, pn_dir=None, rd_segments=False):
# If it isn't a cloud path or a PhysioNet path, we treat as a local file
else:
dir_name = os.path.abspath(dir_name)
with fsspec.open(
with _fsspec_open(
os.path.join(dir_name, file_name),
"r",
encoding="ascii",
Expand Down Expand Up @@ -2070,8 +2077,10 @@ def rdrecord(
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
To read a record from a local .wfdb archive, pass the path of
the archive including the .wfdb extension.
sampfrom : int, optional
Expand Down Expand Up @@ -2472,8 +2481,10 @@ def rdsamp(
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
sampfrom : int, optional
The starting sample number to read for all channels.
sampto : int, 'end', optional
Expand Down Expand Up @@ -2592,8 +2603,10 @@ def sampfreq(record_name, pn_dir=None):
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
pn_dir : str, optional
Option used to stream data from Physionet. The Physionet
database directory from which to find the required record files.
Expand Down Expand Up @@ -2642,8 +2655,10 @@ def signame(record_name, pn_dir=None, sig_nums=[]):
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
pn_dir : str, optional
Option used to stream data from Physionet. The Physionet
database directory from which to find the required record files.
Expand Down Expand Up @@ -2701,8 +2716,10 @@ def wfdbdesc(record_name, pn_dir=None):
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
pn_dir : str, optional
Option used to stream data from Physionet. The Physionet
database directory from which to find the required record files.
Expand Down Expand Up @@ -2835,8 +2852,10 @@ def wfdbtime(record_name, input_times, pn_dir=None):
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
`azureml://`, `memory://`. Other than for `memory://`, install the
appropriate `fsspec` backend (e.g., `s3fs`, `gcsfs`, `adlfs`).
`azureml://`, `memory://`, `physionet://`. Other than for `memory://`
and `physionet://`, install the appropriate `fsspec` backend (e.g.,
`s3fs`, `gcsfs`, `adlfs`). `physionet://` URIs read from PhysioNet,
including restricted databases after `physionet login`.
input_times : str, list
The desired times (or samples) to be converted and displayed for the
chosen record. This can either be a single string, or a list of
Expand Down
15 changes: 9 additions & 6 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@ def is_network_error(exc):
if isinstance(exc, NETWORK_ERRORS):
return True
# Server errors (for example 502 Bad Gateway) and rate limiting, but not errors
# like 404 or 403 which indicate a real problem
return (
isinstance(exc, NetFileError)
and exc.status_code is not None
and (exc.status_code >= 500 or exc.status_code == 429)
)
# like 404 or 403 which indicate a real problem. physionet:// files are read
# with the physionet package, which raises requests' HTTPError.
if isinstance(exc, NetFileError):
status = exc.status_code
elif isinstance(exc, requests.exceptions.HTTPError) and exc.response is not None:
status = exc.response.status_code
else:
return False
return status is not None and (status >= 500 or status == 429)


@pytest.fixture(scope="class")
Expand Down
Loading
Loading