From cf6910a73cc45d1b8f5130be72cc41ac301e769d Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 00:59:04 -0500 Subject: [PATCH] Read pn_dir files through the physionet package Records, headers, signal files and annotations read with pn_dir, and EDF and WAV files read by read_edf and read_wav, are now read as physionet:// URIs (with stream=True, so only the parts of signal files that are needed), through a new download._open_pn_file. Open databases are read directly from the AWS open data mirror rather than through a redirect from physionet.org, and restricted databases can be read after `physionet login`. If the database index URL has been set to another server with set_db_index_url, files are read from that server with wfdb's own HTTP client, as before. get_version now uses physionet.latest_version, through the PhysioNet API, instead of reading the database's web page, and remembers the result for each database until the program ends. It retries connection errors, server errors and rate limiting up to three times, and raises FileNotFoundError for a database that does not exist, as before. Reading 10 seconds from each of five MIT-BIH records with pn_dir="mitdb" now takes 12 requests and 1.5 s, instead of 30 requests and 10.3 s. --- changelog.d/pn-dir-physionet.rst | 2 + docs/io.rst | 8 ++ src/wfdb/io/_coreio.py | 11 ++- src/wfdb/io/convert/edf.py | 5 +- src/wfdb/io/convert/wav.py | 5 +- src/wfdb/io/download.py | 131 +++++++++++++++++++++++------ tests/conftest.py | 10 +-- tests/test_physionet_uri.py | 137 +++++++++++++++++++++++++++++++ 8 files changed, 269 insertions(+), 40 deletions(-) create mode 100644 changelog.d/pn-dir-physionet.rst diff --git a/changelog.d/pn-dir-physionet.rst b/changelog.d/pn-dir-physionet.rst new file mode 100644 index 00000000..b7cab2ee --- /dev/null +++ b/changelog.d/pn-dir-physionet.rst @@ -0,0 +1,2 @@ +**Read pn_dir records through the physionet package** + Records, headers and annotations read with ``pn_dir`` (and EDF and WAV files read with ``pn_dir`` by ``read_edf`` and ``read_wav``) are now read through the ``physionet`` package, as ``physionet://`` URIs are. Open databases are read directly from the AWS open data mirror, which makes reading part of a record from MIT-BIH about twice as fast, and restricted databases can be read after ``physionet login``. The latest version of a database, used when ``pn_dir`` has no version, is now looked up with the PhysioNet API once per database, and retried if PhysioNet is unavailable, instead of reading the database's web page on every call. With a database index URL set by ``set_db_index_url``, files are read from that server as before. diff --git a/docs/io.rst b/docs/io.rst index 1c4a36e3..32e716c3 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -165,6 +165,14 @@ and have signed in, by running ``physionet login`` once in a terminal (or setting ``PHYSIONET_TOKEN``). See the `physionet package `_ for details. +The ``pn_dir`` argument reads files the same way, so +``wfdb.rdrecord("100", pn_dir="mitdb")`` and +``wfdb.rdrecord("physionet://mitdb/1.0.0/100")`` read the same files. When +``pn_dir`` has no version, the latest version is looked up once per database, +and used until the program ends. If the database index URL has been changed +with ``wfdb.io.download.set_db_index_url``, files are read from that server +instead, as before. + Reading From Memory ------------------- diff --git a/src/wfdb/io/_coreio.py b/src/wfdb/io/_coreio.py index c7dcd688..d258c865 100644 --- a/src/wfdb/io/_coreio.py +++ b/src/wfdb/io/_coreio.py @@ -3,8 +3,7 @@ import fsspec -from wfdb.io import _url -from wfdb.io.download import config +from wfdb.io import download # Cloud protocols CLOUD_PROTOCOLS = ["az://", "azureml://", "s3://", "gs://", "memory://", "physionet://"] @@ -33,7 +32,7 @@ def _fsspec_open(path, mode="rb", **kwargs): """ if os.fspath(path).startswith("physionet://"): - kwargs = {"stream": True, "show_progress": False, **kwargs} + kwargs = {**download.PHYSIONET_OPEN_OPTIONS, **kwargs} return fsspec.open(path, mode, **kwargs) @@ -145,9 +144,9 @@ def _open_file( "Cloud paths should be passed under record_name, not under pn_dir" ) - url = posixpath.join(config.db_index_url, pn_dir, file_name) - return _url.openurl( - url, + return download._open_pn_file( + pn_dir, + file_name, mode, buffering=buffering, encoding=encoding, diff --git a/src/wfdb/io/convert/edf.py b/src/wfdb/io/convert/edf.py index c8ca23d4..3be6ae04 100644 --- a/src/wfdb/io/convert/edf.py +++ b/src/wfdb/io/convert/edf.py @@ -8,7 +8,7 @@ import numpy as np import pandas as pd -from wfdb.io import _url, download +from wfdb.io import download from wfdb.io.annotation import Annotation, format_ann_from_df, wrann from wfdb.io.record import SIG_UNITS, Record, rdrecord @@ -135,10 +135,9 @@ def read_edf( dir_list[0], download.get_version(dir_list[0]), *dir_list[1:] ) - file_url = posixpath.join(download.PN_INDEX_URL, pn_dir, record_name) # Currently must download file for MNE to read it though can give the # user the option to delete it immediately afterwards - with _url.openurl(file_url, "rb") as f: + with download._open_pn_file(pn_dir, record_name) as f: open(record_name, "wb").write(f.read()) # Open the desired file diff --git a/src/wfdb/io/convert/wav.py b/src/wfdb/io/convert/wav.py index 50b83f82..fa057b39 100644 --- a/src/wfdb/io/convert/wav.py +++ b/src/wfdb/io/convert/wav.py @@ -4,7 +4,7 @@ import numpy as np -from wfdb.io import Record, _url, download +from wfdb.io import Record, download from wfdb.io._signal import _digi_nan from wfdb.io.record import rdrecord @@ -227,10 +227,9 @@ def read_wav(record_name, pn_dir=None, delete_file=True, record_only=False): dir_list[0], download.get_version(dir_list[0]), *dir_list[1:] ) - file_url = posixpath.join(download.PN_INDEX_URL, pn_dir, record_name) # Currently must download file to read it though can give the # user the option to delete it immediately afterwards - with _url.openurl(file_url, "rb") as f: + with download._open_pn_file(pn_dir, record_name) as f: open(record_name, "wb").write(f.read()) wave_file = open(record_name, mode="rb") diff --git a/src/wfdb/io/download.py b/src/wfdb/io/download.py index ce84846f..324b6431 100644 --- a/src/wfdb/io/download.py +++ b/src/wfdb/io/download.py @@ -1,8 +1,11 @@ +import functools import json import multiprocessing.dummy import os import posixpath +import time +import fsspec import numpy as np from wfdb.io import _url @@ -46,6 +49,74 @@ def set_db_index_url(db_index_url=PN_INDEX_URL): config.db_index_url = db_index_url +# Options for opening physionet:// files: read only the parts of a file that +# are needed, with HTTP range requests, and show no progress bars +PHYSIONET_OPEN_OPTIONS = {"stream": True, "show_progress": False} + + +def _physionet_uri(pn_dir, file_name): + """Return the physionet:// URI of a file in a PhysioNet database. + + Parameters + ---------- + pn_dir : str + The PhysioNet database directory, including its version, such as + 'mitdb/1.0.0'. + file_name : str + The name of the file in that directory. + + Returns + ------- + str or None + The URI, or None if the database index URL has been set to a server + other than PhysioNet (with `set_db_index_url`). + + """ + if config.db_index_url.rstrip("/") != PN_INDEX_URL.rstrip("/"): + return None + return "physionet://" + posixpath.join(pn_dir, file_name) + + +def _open_pn_file(pn_dir, file_name, mode="rb", **kwargs): + """Open a file in a PhysioNet database directory. + + Files on PhysioNet are read through the physionet package, which reads + only the parts of a file that are needed, and reads restricted databases + with the sign-in saved by `physionet login`. Files on another server, set + with `set_db_index_url`, are read with `wfdb.io._url.openurl`. + + Parameters + ---------- + pn_dir : str + The PhysioNet database directory, including its version. + file_name : str + The name of the file in that directory. + mode : str, optional + The mode to open the file in: "rb" (the default) or "r". + kwargs : dict, optional + Passed to `wfdb.io._url.openurl` for another server. For PhysioNet, + only `encoding`, `errors` and `newline` are used. + + Returns + ------- + file + The file to open, as a context manager. + + """ + uri = _physionet_uri(pn_dir, file_name) + if uri is None: + url = posixpath.join(config.db_index_url, pn_dir, file_name) + return _url.openurl(url, mode, **kwargs) + # Other options would make fsspec create a separate filesystem, without + # the connection and lookups that are shared by every physionet:// file + text_options = { + name: kwargs[name] + for name in ("encoding", "errors", "newline") + if kwargs.get(name) is not None + } + return fsspec.open(uri, mode, **PHYSIONET_OPEN_OPTIONS, **text_options) + + def _remote_file_size(url=None, file_name=None, pn_dir=None): """Get the remote file size in bytes. @@ -67,9 +138,9 @@ def _remote_file_size(url=None, file_name=None, pn_dir=None): Size of the file in bytes. """ - # Option to construct the url if file_name and pn_dir: - url = posixpath.join(config.db_index_url, pn_dir, file_name) + with _open_pn_file(pn_dir, file_name) as f: + return f.seek(0, os.SEEK_END) with _url.openurl(url, "rb") as f: remote_file_size = f.seek(0, os.SEEK_END) @@ -95,11 +166,8 @@ def _stream_header(file_name: str, pn_dir: str) -> str: The text contained in the header file """ - # Full url of header location - url = posixpath.join(config.db_index_url, pn_dir, file_name) - # Get the content of the remote file - with _url.openurl(url, "rb") as f: + with _open_pn_file(pn_dir, file_name) as f: content = f.read() return content.decode("iso-8859-1") @@ -127,11 +195,8 @@ def _stream_dat(file_name, pn_dir, byte_count, start_byte, dtype): The data read from the dat file. """ - # Full url of dat file - url = posixpath.join(config.db_index_url, pn_dir, file_name) - # Get the content - with _url.openurl(url, "rb", buffering=0) as f: + with _open_pn_file(pn_dir, file_name, buffering=0) as f: f.seek(start_byte) content = f.read(byte_count) @@ -157,11 +222,8 @@ def _stream_annotation(file_name, pn_dir): The resulting data stream in numpy array format. """ - # Full url of annotation file - url = posixpath.join(config.db_index_url, pn_dir, file_name) - # Get the content - with _url.openurl(url, "rb") as f: + with _open_pn_file(pn_dir, file_name) as f: content = f.read() # Convert to numpy array @@ -219,18 +281,41 @@ def get_version(pn_dir): Returns ------- version_number : str - The version number of the most recent database. + The version number of the most recent database. It is looked up + once per database, and remembered until the program ends. """ - db_dir = pn_dir.split("/")[0] - url = posixpath.join(PN_CONTENT_URL, db_dir) + "/" - with _url.openurl(url, "rb") as f: - content = f.read() - contents = [line.decode("utf-8").strip() for line in content.splitlines()] - version_number = [v for v in contents if "Version:" in v] - version_number = version_number[0].split(":")[-1].strip().split("<")[0] + return _latest_version(pn_dir.split("/")[0]) + + +# How many times to try looking up a version, if PhysioNet is unavailable +VERSION_ATTEMPTS = 3 + - return version_number +@functools.cache +def _latest_version(db_dir): + """Look up the latest version of a PhysioNet database. + + Connection errors, server errors and rate limiting are retried, after 1 + and then 2 seconds. + + """ + import physionet + from physionet.api.exceptions import NotFoundError, PhysioNetAPIError + + for attempt in range(VERSION_ATTEMPTS): + try: + return physionet.latest_version(db_dir) + except NotFoundError as exc: + raise FileNotFoundError(f"PhysioNet has no database {db_dir!r}") from exc + except (ConnectionError, PhysioNetAPIError) as exc: + status = getattr(getattr(exc, "response", None), "status_code", None) + unavailable = isinstance(exc, ConnectionError) or ( + status is not None and (status >= 500 or status == 429) + ) + if not unavailable or attempt == VERSION_ATTEMPTS - 1: + raise + time.sleep(2**attempt) def get_record_list(db_dir, records="all"): diff --git a/tests/conftest.py b/tests/conftest.py index 7c464f96..99a33ef3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,6 +5,8 @@ # Errors that mean PhysioNet is unreachable or too slow (not that a test failed) NETWORK_ERRORS = ( + # Raised by the physionet package, for example when looking up a version + ConnectionError, requests.exceptions.ConnectionError, requests.exceptions.ChunkedEncodingError, requests.exceptions.Timeout, @@ -16,14 +18,12 @@ 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. physionet:// files are read - # with the physionet package, which raises requests' HTTPError. + # like 404 or 403 which indicate a real problem 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 + # requests' HTTPError and the physionet package's API errors + status = getattr(getattr(exc, "response", None), "status_code", None) return status is not None and (status >= 500 or status == 429) diff --git a/tests/test_physionet_uri.py b/tests/test_physionet_uri.py index 5de837d4..24a6f91f 100644 --- a/tests/test_physionet_uri.py +++ b/tests/test_physionet_uri.py @@ -1,5 +1,6 @@ """Tests for reading records and annotations with physionet:// URIs.""" +import io import shutil from pathlib import Path @@ -113,3 +114,139 @@ def test_rdrecord_from_physionet(physionet_cache, capsys): path.suffix in {".dat", ".hea"} for path in physionet_cache.rglob("*") ) assert "%|" not in capsys.readouterr().err + + +@pytest.mark.parametrize( + ("record_name", "names", "kwargs"), + [ + ("100", ["100.hea", "100.dat"], {"sampfrom": 1000, "sampto": 5000}), + # The signal length is worked out from the size of the signal file + ("100-no-len", ["100-no-len.hea", "100.dat"], {}), + ( + "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", "no-length", "flac", "multi-segment"], +) +def test_pn_dir_reads_through_physionet( + physionet_cache, offline, record_name, names, kwargs +): + """pn_dir reads go through physionet://, so cached files need no requests.""" + folder = ( + SAMPLE_DATA / "multi-segment" / "041s" if record_name == "041s" else SAMPLE_DATA + ) + cache_sample_files(physionet_cache, "demo", names, folder) + + record = wfdb.rdrecord(record_name, pn_dir="demo/1.0", **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_pn_dir_rdheader_and_rdann(physionet_cache, offline): + cache_sample_files(physionet_cache, "demo", ["100.hea", "100.atr"]) + + header = wfdb.rdheader("100", pn_dir="demo/1.0") + annotation = wfdb.rdann("100", "atr", pn_dir="demo/1.0") + + 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) + + +@pytest.fixture +def versions(monkeypatch): + """Replace physionet.latest_version, recording calls, and clear the cache.""" + import physionet + + calls = [] + results = {} + + def latest_version(db_dir): + calls.append(db_dir) + result = results.get(db_dir, "1.0.0") + if isinstance(result, list): + result = result.pop(0) + if isinstance(result, Exception): + raise result + return result + + monkeypatch.setattr(physionet, "latest_version", latest_version) + monkeypatch.setattr(wfdb.io.download.time, "sleep", lambda seconds: None) + wfdb.io.download._latest_version.cache_clear() + yield calls, results + wfdb.io.download._latest_version.cache_clear() + + +def api_error(status): + from physionet.api.exceptions import PhysioNetAPIError + + response = requests.Response() + response.status_code = status + return PhysioNetAPIError(f"HTTP {status}", response=response) + + +def test_get_version_is_looked_up_once_per_database(versions): + calls, _ = versions + assert wfdb.io.download.get_version("mitdb") == "1.0.0" + assert wfdb.io.download.get_version("mitdb/x") == "1.0.0" + assert wfdb.io.download.get_version("afdb") == "1.0.0" + assert calls == ["mitdb", "afdb"] + + +def test_get_version_retries_while_physionet_is_unavailable(versions): + calls, results = versions + results["mitdb"] = [api_error(502), ConnectionError("unreachable"), "1.0.0"] + assert wfdb.io.download.get_version("mitdb") == "1.0.0" + assert calls == ["mitdb"] * 3 + + +def test_get_version_errors(versions): + from physionet.api.exceptions import NotFoundError, PhysioNetAPIError + + calls, results = versions + results["nosuchdb"] = NotFoundError("Not found") + with pytest.raises(FileNotFoundError, match="no database 'nosuchdb'"): + wfdb.io.download.get_version("nosuchdb") + + # Other errors are not retried, and server errors only so many times + results["private"] = api_error(403) + with pytest.raises(PhysioNetAPIError): + wfdb.io.download.get_version("private") + results["down"] = [api_error(503)] * 5 + with pytest.raises(PhysioNetAPIError): + wfdb.io.download.get_version("down") + assert calls.count("private") == 1 + assert calls.count("down") == wfdb.io.download.VERSION_ATTEMPTS + + +def test_other_servers_are_read_without_physionet(monkeypatch): + """With set_db_index_url, pn_dir files are read from that server, as before.""" + opened = [] + + def openurl(url, mode="r", **kwargs): + opened.append(url) + return io.BytesIO(b"100 1 360 10\n") + + monkeypatch.setattr(wfdb.io._url, "openurl", openurl) + wfdb.io.download.set_db_index_url("https://mirror.example.org/files/") + try: + assert wfdb.io.download._physionet_uri("mitdb/1.0.0", "100.hea") is None + assert wfdb.io.download._stream_header("100.hea", "mitdb/1.0.0").startswith( + "100" + ) + finally: + wfdb.io.download.set_db_index_url() + assert opened == ["https://mirror.example.org/files/mitdb/1.0.0/100.hea"] + assert ( + wfdb.io.download._physionet_uri("mitdb/1.0.0", "100.hea") + == "physionet://mitdb/1.0.0/100.hea" + )