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/dl-physionet.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
**Download databases with the physionet package**
``dl_database`` and ``dl_files`` now download files with the ``physionet`` package (0.7.1 or later). Each file is checked against the database's checksum list, a file that is already saved with the right content is skipped, a partly downloaded one is completed, ``overwrite=True`` replaces each saved file only once its new copy is complete and checked, and restricted databases can be downloaded after ``physionet login``. ``dl_database`` finds which annotation files there are from the checksum list instead of requesting each one, which makes downloading three MIT-BIH records with their annotations take 20 requests instead of 38. ``dl_files`` reports a file that the database does not have before downloading anything. With a database index URL set by ``set_db_index_url``, files are downloaded from that server as before.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ dependencies = [
"requests >= 2.31.0",
"fsspec >= 2025.7.0",
"aiohttp >= 3.10.11",
"physionet >= 0.6.0",
"physionet >= 0.7.1",
]

[project.urls]
Expand Down
119 changes: 105 additions & 14 deletions src/wfdb/io/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,18 +340,16 @@ def get_record_list(db_dir, records="all"):
>>> wfdb.get_record_list('mitdb')

"""
# Full url PhysioNet database
if "/" not in db_dir:
db_url = posixpath.join(config.db_index_url, db_dir, get_version(db_dir))
else:
db_url = posixpath.join(config.db_index_url, db_dir)
db_dir = posixpath.join(db_dir, get_version(db_dir))

# Check for a RECORDS file
if records == "all":
try:
with _url.openurl(posixpath.join(db_url, "RECORDS"), "rb") as f:
with _open_pn_file(db_dir, "RECORDS") as f:
content = f.read()
except FileNotFoundError:
db_url = posixpath.join(config.db_index_url, db_dir)
raise ValueError("The database %s has no WFDB files to download" % db_url)

# Get each line as a string
Expand Down Expand Up @@ -391,7 +389,7 @@ def get_annotators(db_dir, annotators):
if annotators is not None:
# Check for an ANNOTATORS file
try:
with _url.openurl(posixpath.join(db_url, "ANNOTATORS"), "rb") as f:
with _open_pn_file(db_dir, "ANNOTATORS") as f:
content = f.read()
except FileNotFoundError:
if annotators == "all":
Expand Down Expand Up @@ -423,6 +421,82 @@ def get_annotators(db_dir, annotators):
return annotators


def _project_files(db_dir):
"""List the files in a PhysioNet database directory, from its checksum list.

Parameters
----------
db_dir : str
The PhysioNet database directory, including its version, such as
'mitdb/1.0.0'.

Returns
-------
set of str or None
The paths of the files, relative to `db_dir`, or None if the database
index URL has been set to a server other than PhysioNet.

"""
if _physionet_uri(db_dir, "") is None:
return None
fs = fsspec.filesystem("physionet", **PHYSIONET_OPEN_OPTIONS)
prefix = db_dir.rstrip("/") + "/"
return {path[len(prefix) :] for path in fs.find(db_dir) if path.startswith(prefix)}


def _download_files(db_dir, dl_dir, files, keep_subdirs, overwrite):
"""Download files from a PhysioNet database with the physionet package.

Each file is checked against the database's checksum list. A file that is
already saved with the right content is skipped, and one that was partly
downloaded is completed.

Parameters
----------
db_dir : str
The PhysioNet database directory, including its version, such as
'mitdb/1.0.0' or 'mimic3wdb/1.0/30'.
dl_dir : str
The local directory to save the files in.
files : list of str
The paths of the files to download, relative to `db_dir`.
keep_subdirs : bool
Whether to save the files in the same subdirectories as on PhysioNet
(True), or all in `dl_dir` (False).
overwrite : bool
Whether to download files again even if they are already saved.

Returns
-------
N/A

"""
import physionet

slug, version, *subdirs = db_dir.strip("/").split("/")
saved_as = {}
for file in files:
path = posixpath.join(*subdirs, file)
saved_as[path] = file if keep_subdirs else posixpath.basename(file)

if not os.path.isdir(dl_dir):
os.makedirs(dl_dir)
print("Created local base download directory: %s" % dl_dir)
# Two files at a time, as before, to avoid overloading the server. With
# overwrite, physionet replaces each saved file only after checking every
# requested file and destination, and once the new copy is complete.
physionet.download(
slug,
version,
output_dir=dl_dir,
files=saved_as,
verbose=False,
show_progress=False,
jobs=2,
overwrite=overwrite,
)


def make_local_dirs(dl_dir, dl_inputs, keep_subdirs):
"""Make any required local directories to prepare for downloading.

Expand Down Expand Up @@ -561,18 +635,27 @@ def dl_files(db, dl_dir, files, keep_subdirs=True, overwrite=False):
are organized in PhysioNet (True), or to download all files into the
same base directory (False).
overwrite : bool, optional
If True, all files will be redownloaded regardless. If False, existing
files with the same name and relative subdirectory will be checked.
If the local file is the same size as the online file, the download is
skipped. If the local file is larger, it will be deleted and the file
will be redownloaded. If the local file is smaller, the file will be
assumed to be partially downloaded and the remaining bytes will be
downloaded and appended.
If True, all files are downloaded again, and each saved file is only
replaced once its new copy is complete and checked. If False, a file
that is already saved with the right content (checked against the
database's checksum list) is skipped, a partly downloaded file is
completed, and any other saved file is downloaded again in its place,
which removes the saved file if the new download fails its checksum.

Returns
-------
N/A

Notes
-----
Files are downloaded with the `physionet` package, two at a time, from the
AWS open data mirror for open databases, and from PhysioNet for restricted
ones, which can be downloaded after signing in with `physionet login`.
Each file is checked against the database's checksum list. If the database
index URL has been set to another server with `set_db_index_url`, files are
downloaded from that server instead, comparing only their sizes when they
are already saved.

Examples
--------
>>> wfdb.dl_files('ahadb', os.getcwd(),
Expand All @@ -582,9 +665,17 @@ def dl_files(db, dl_dir, files, keep_subdirs=True, overwrite=False):
"""
# Full url PhysioNet database
db_dir = posixpath.join(db, get_version(db))
db_url = posixpath.join(PN_CONTENT_URL, db_dir) + "/"

# The physionet package reports a missing database, version or file
# before downloading anything
if _physionet_uri(db_dir, "") is not None:
print("Downloading files...")
_download_files(db_dir, dl_dir, files, keep_subdirs, overwrite)
print("Finished downloading files")
return

# Check if the database is valid
db_url = posixpath.join(PN_CONTENT_URL, db_dir) + "/"
_url.openurl(db_url, check_access=True)

# Construct the urls to download
Expand Down
38 changes: 30 additions & 8 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -3326,19 +3326,28 @@ def dl_database(
as they are organized in PhysioNet (True), or to download all
files into the same base directory (False).
overwrite : bool, optional
If True, all files will be redownloaded regardless. If False,
existing files with the same name and relative subdirectory will
be checked. If the local file is the same size as the online
file, the download is skipped. If the local file is larger, it
will be deleted and the file will be redownloaded. If the local
file is smaller, the file will be assumed to be partially
downloaded and the remaining bytes will be downloaded and
appended.
If True, all files are downloaded again, and each saved file is only
replaced once its new copy is complete and checked. If False, a file
that is already saved with the right content (checked against the
database's checksum list) is skipped, a partly downloaded file is
completed, and any other saved file is downloaded again in its place,
which removes the saved file if the new download fails its checksum.

Returns
-------
N/A

Notes
-----
Files are downloaded with the `physionet` package, two at a time, from the
AWS open data mirror for open databases, and from PhysioNet for restricted
ones, which can be downloaded after signing in with `physionet login`.
Each file is checked against the database's checksum list, and which
annotation files there are is found from that list. If the database index
URL has been set to another server with `set_db_index_url`, files are
downloaded from that server instead, comparing only their sizes when they
are already saved.

Examples
--------
>>> wfdb.dl_database('ahadb', os.getcwd())
Expand All @@ -3360,6 +3369,9 @@ def dl_database(
record_list = download.get_record_list(db_dir, records)
# Get the annotator extensions
annotators = download.get_annotators(db_dir, annotators)
# The files in the database, to check which annotation files there are
# (None if the database index URL is not PhysioNet's)
project_files = download._project_files(db_dir) if annotators else None

# All files to download (relative to the database's home directory)
all_files = []
Expand Down Expand Up @@ -3409,13 +3421,23 @@ def dl_database(
if annotators is not None:
for a in annotators:
ann_file = rec + "." + a
if project_files is not None:
if ann_file in project_files:
all_files.append(ann_file)
continue
url = posixpath.join(download.config.db_index_url, db_dir, ann_file)
try:
_url.openurl(url, check_access=True)
all_files.append(ann_file)
except FileNotFoundError:
pass

if download._physionet_uri(db_dir, "") is not None:
print("Downloading files...")
download._download_files(db_dir, dl_dir, all_files, keep_subdirs, overwrite)
print("Finished downloading files")
return

dl_inputs = [
(
os.path.split(file)[1],
Expand Down
Loading
Loading