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/pn-dir-physionet.rst
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 8 additions & 0 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,14 @@ 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.

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
-------------------
Expand Down
11 changes: 5 additions & 6 deletions src/wfdb/io/_coreio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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://"]
Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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,
Expand Down
5 changes: 2 additions & 3 deletions src/wfdb/io/convert/edf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions src/wfdb/io/convert/wav.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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")
Expand Down
131 changes: 108 additions & 23 deletions src/wfdb/io/download.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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)
Expand All @@ -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")
Expand Down Expand Up @@ -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)

Expand All @@ -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
Expand Down Expand Up @@ -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"):
Expand Down
10 changes: 5 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)


Expand Down
Loading
Loading