diff --git a/changelog.d/physionet-uris.rst b/changelog.d/physionet-uris.rst new file mode 100644 index 00000000..c900f5e3 --- /dev/null +++ b/changelog.d/physionet-uris.rst @@ -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. diff --git a/docs/io.rst b/docs/io.rst index 10595198..1c4a36e3 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -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 +`_ for details. + + Reading From Memory ------------------- diff --git a/pyproject.toml b/pyproject.toml index a5fc41ea..e2c55df7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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] diff --git a/src/wfdb/io/_coreio.py b/src/wfdb/io/_coreio.py index c8040c4c..c7dcd688 100644 --- a/src/wfdb/io/_coreio.py +++ b/src/wfdb/io/_coreio.py @@ -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): @@ -103,7 +130,7 @@ def _open_file( """ if pn_dir is None: - return fsspec.open( + return _fsspec_open( file_name, mode, buffering=buffering, diff --git a/src/wfdb/io/_signal.py b/src/wfdb/io/_signal.py index 92e52741..c7a1f3a2 100644 --- a/src/wfdb/io/_signal.py +++ b/src/wfdb/io/_signal.py @@ -3,7 +3,6 @@ import os import sys -import fsspec import numpy as np from wfdb.io import _coreio, download, util @@ -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 @@ -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 diff --git a/src/wfdb/io/annotation.py b/src/wfdb/io/annotation.py index e2154588..213cc385 100644 --- a/src/wfdb/io/annotation.py +++ b/src/wfdb/io/annotation.py @@ -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 @@ -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, "= 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") diff --git a/tests/test_physionet_uri.py b/tests/test_physionet_uri.py new file mode 100644 index 00000000..5de837d4 --- /dev/null +++ b/tests/test_physionet_uri.py @@ -0,0 +1,115 @@ +"""Tests for reading records and annotations with physionet:// URIs.""" + +import shutil +from pathlib import Path + +import fsspec +import numpy as np +import pytest +import requests + +import wfdb + +SAMPLE_DATA = Path("sample-data") + + +@pytest.fixture +def physionet_cache(tmp_path, monkeypatch): + """A physionet package cache, with a fresh filesystem for each test.""" + cache = tmp_path / "cache" + monkeypatch.setenv("PHYSIONET_CACHE", str(cache)) + fsspec.filesystem("physionet").clear_instance_cache() + yield cache + fsspec.filesystem("physionet").clear_instance_cache() + + +@pytest.fixture +def offline(monkeypatch): + """Fail any request that is made.""" + + def refuse(session, request, **kwargs): + raise AssertionError(f"Unexpected request: {request.method} {request.url}") + + monkeypatch.setattr(requests.Session, "send", refuse) + + +def cache_sample_files(cache, project, names, folder=SAMPLE_DATA): + """Copy sample files into the cache, as if physionet had downloaded them.""" + target = cache / "physionet.org" / project / "1.0" + target.mkdir(parents=True, exist_ok=True) + for name in names: + shutil.copy(folder / name, target / name) + + +@pytest.mark.parametrize( + ("record_name", "names", "kwargs"), + [ + ("100", ["100.hea", "100.dat"], {"sampfrom": 1000, "sampto": 5000}), + ( + "flacformats", + ["flacformats.hea", "flacformats.d0", "flacformats.d1", "flacformats.d2"], + {}, + ), + ( + "041s", + ["041s.hea", "041s01.hea", "041s01.dat", "041s02.hea", "041s02.dat"], + {"sampto": 1000}, + ), + ], + ids=["format-212", "flac", "multi-segment"], +) +def test_rdrecord_reads_cached_files_without_requests( + physionet_cache, offline, record_name, names, kwargs +): + """Files already in the physionet cache are read without any requests. + + That is only so with stream=True: otherwise the physionet package first gets + the project's checksum list, which is not cached here. + """ + folder = ( + SAMPLE_DATA / "multi-segment" / "041s" if record_name == "041s" else SAMPLE_DATA + ) + cache_sample_files(physionet_cache, "demo", names, folder) + + record = wfdb.rdrecord(f"physionet://demo/1.0/{record_name}", **kwargs) + + expected = wfdb.rdrecord(str(folder / record_name), **kwargs) + assert record.sig_name == expected.sig_name + np.testing.assert_array_equal(record.p_signal, expected.p_signal) + + +def test_rdheader_and_rdann(physionet_cache, offline): + cache_sample_files(physionet_cache, "demo", ["100.hea", "100.atr"]) + + header = wfdb.rdheader("physionet://demo/1.0/100") + annotation = wfdb.rdann("physionet://demo/1.0/100", "atr") + + assert header.sig_name == wfdb.rdheader("sample-data/100").sig_name + expected = wfdb.rdann("sample-data/100", "atr") + np.testing.assert_array_equal(annotation.sample, expected.sample) + assert annotation.symbol == expected.symbol + + +def test_files_not_in_the_cache_are_requested(physionet_cache, offline): + cache_sample_files(physionet_cache, "demo", ["100.hea"]) + # 100.dat is not cached, so it is requested from PhysioNet + with pytest.raises(AssertionError, match="Unexpected request"): + wfdb.rdrecord("physionet://demo/1.0/100") + + +@pytest.mark.network +def test_rdrecord_from_physionet(physionet_cache, capsys): + """Read part of a record from PhysioNet, without downloading whole files.""" + record = wfdb.rdrecord("physionet://mitdb/1.0.0/100", sampfrom=1000, sampto=4600) + annotation = wfdb.rdann("physionet://mitdb/1.0.0/100", "atr", sampto=4600) + + expected = wfdb.rdrecord("sample-data/100", sampfrom=1000, sampto=4600) + np.testing.assert_array_equal(record.p_signal, expected.p_signal) + np.testing.assert_array_equal( + annotation.sample, wfdb.rdann("sample-data/100", "atr", sampto=4600).sample + ) + # Nothing is downloaded into the cache, and no progress bars are shown + assert not any( + path.suffix in {".dat", ".hea"} for path in physionet_cache.rglob("*") + ) + assert "%|" not in capsys.readouterr().err