Skip to content

Read records from PhysioNet with physionet:// URIs - #657

Merged
tompollard merged 2 commits into
mainfrom
physionet-uris
Nov 23, 2026
Merged

tompollard merged 2 commits into
mainfrom
physionet-uris

Conversation

@tompollard

@tompollard tompollard commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

rdrecord, rdsamp, rdheader and rdann now accept physionet:// URIs, read through the physionet package, which becomes a dependency:

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

The URI is the database, its version (or latest) and the record name. Through the package's fsspec filesystem:

  • Files are read with HTTP range requests (stream=True, added in physionet 0.6.0), from the AWS open data mirror for open databases and from PhysioNet for restricted ones. For signal files, only the parts that hold the samples that are needed are read: 10 seconds from the end of a 7.4 MB FLAC-compressed MIMIC-IV signal file takes 0.04 MB. Header and annotation files are read in full, since rdann reads the whole annotation file.
  • Restricted databases can be read with the sign-in saved by physionet login (or PHYSIONET_TOKEN), which wfdb could not do before.
  • Files that the physionet package has already downloaded into its cache are read from there.

Changes

  • Every fsspec.open call (headers, signal files, annotations, signal length) now goes through a new _coreio._fsspec_open, which opens physionet:// files with stream=True and show_progress=False. Other paths are opened as before.
  • physionet:// is added to CLOUD_PROTOCOLS, so these URIs take the existing cloud path in rdheader, _rdrecord and the signal readers.
  • physionet >= 0.6.0 is a new dependency. It requires fsspec 2025.7.0 or later, so the minimum here is raised from 2023.10.0 to match. import wfdb does not load physionet (it is only loaded through fsspec when a physionet:// path is opened), and still takes 0.15 s.
  • Existing pn_dir reading is unchanged. Moving it onto physionet:// can follow separately.
  • Docs: a "Reading From PhysioNet" section in docs/io.rst, the supported URIs in the docstrings, and a changelog entry.

Testing

  • New tests/test_physionet_uri.py. The offline tests put sample records into a temporary physionet cache, make any request fail, and check that reading them through physionet:// (format 212, FLAC and a multi-segment record with rdrecord, plus rdheader and rdann) gives the same result as reading the local files. Without stream=True, the physionet package would first request the checksum list, so four of these fail if it is removed. A network test reads part of MIT-BIH record 100 and its annotations from PhysioNet, and checks that nothing is saved in the cache and no progress bars are shown.
  • tests/conftest.py now also skips network tests on server errors (5xx, 429) raised as requests.HTTPError, which is how the physionet package reports them.
  • uv run pytest -m "not network": 467 passed. The new network test passes.
  • With uv run --python 3.11 --resolution lowest-direct (fsspec 2025.7.0, physionet 0.6.0, pandas 2.2.3): 467 passed.
  • ruff format --check, ruff check and the docs build pass.

@tompollard 🟥 red 🦥 sloth

rdrecord, rdsamp, rdheader and rdann now accept physionet:// URIs such as
physionet://mitdb/1.0.0/100, read through the physionet package, which is
now a dependency. Its fsspec filesystem reads restricted databases with the
sign-in saved by `physionet login`, which wfdb could not do.

Every fsspec.open call goes through a new _coreio._fsspec_open, which
opens physionet:// files with stream=True, so that only the parts that
are needed are read with HTTP range requests rather than whole files
downloaded, and with show_progress=False. Files already in the physionet
cache are read from there.

The physionet package requires fsspec 2025.7.0 or later, so that is now
the minimum here too. The network tests also count server errors from
requests' HTTPError, which the physionet package raises, as PhysioNet
being unavailable.
@tompollard

Copy link
Copy Markdown
Member Author

Reviewed 398e29b. I found no blocking code issue; 467 offline tests and the live URI test passed locally. One documentation correction: docs/io.rst says only the needed parts of each file are read, but rdann() still reads the entire annotation file through load_byte_pairs() and util.fromfile(count=-1), even when sampto is small. Please narrow that claim to signal reads, or add incremental annotation reading separately. One CI job was still running when I checked.

Only signal files are read in parts: header files, and annotation files
(which rdann reads in full, even with sampto), are read whole. For a
FLAC-compressed MIMIC-IV signal file of 7.4 MB, reading 10 seconds from
the end reads 0.04 MB.
@tompollard

Copy link
Copy Markdown
Member Author

Thanks, good catch. Fixed in 4ca54a0.

docs/io.rst now says that, for signal files, only the parts that hold the samples that are needed are read, and that header and annotation files are read in full, with rdann reading the whole annotation file even with sampto. The changelog entry and the PR description say the same.

I checked the signal side against a large file before narrowing the wording, including FLAC, since it has to be decoded. Reading channel 0 of the 7.4 MB FLAC-compressed MIMIC-IV file 81739927_0008e.dat through physionet://:

Requests Transferred
First 10 seconds 2 0.03 MB
Last 10 seconds 4 0.04 MB

So the claim holds for signals, FLAC included. Reading annotations incrementally would need rdann to stop decoding at sampto instead of reading the file with util.fromfile(count=-1). I've left that for a separate change, since annotation files are usually small compared with signal files.

@tompollard
tompollard merged commit b9b7b31 into main Nov 23, 2026
18 checks passed
@tompollard
tompollard deleted the physionet-uris branch November 23, 2026 05:54
tompollard added a commit that referenced this pull request Nov 23, 2026
Follows #657. Files read with `pn_dir` now go through the `physionet`
package, as `physionet://` URIs do, and the latest version of a database
is looked up with `physionet.latest_version()` instead of from its web
page.

Reading 10 seconds from each of five MIT-BIH records (`rdrecord(name,
pn_dir="mitdb", sampto=3600)` for 100 to 104):

| | Time | Requests |
|---|---|---|
| `main` | 10.3 s | 30 (20 to physionet.org, 10 to the AWS mirror) |
| This PR | 1.5 s | 12 (1 to physionet.org, 11 to the AWS mirror) |

The signals are identical. The version is looked up once rather than for
every record, and open databases are read directly from the mirror
rather than through a redirect from physionet.org.

## Changes

- A new `download._open_pn_file(pn_dir, file_name)` opens a file in a
PhysioNet database directory as `physionet://<pn_dir>/<file_name>`, with
`stream=True` and `show_progress=False`, so only the parts of signal
files that are needed are read. `_stream_header`, `_stream_dat`,
`_stream_annotation`, `_remote_file_size` and `_coreio._open_file` (used
for FLAC signals) use it, and so do `read_edf` and `read_wav` for their
`pn_dir` downloads. Restricted databases can now be read with `pn_dir`
after `physionet login`.
- Only `encoding`, `errors` and `newline` are passed on for
`physionet://` files. Other options would make fsspec create a separate
filesystem for each call, without the shared connection and source
lookups.
- If the database index URL has been set to another server with
`set_db_index_url`, files are read from that server with `_url.openurl`,
as before.
- `get_version` now calls `physionet.latest_version` (through the
PhysioNet API) and remembers the result for each database until the
program ends. It retries connection errors, server errors and rate
limiting up to three times, after 1 and 2 seconds. A database that does
not exist still raises `FileNotFoundError`.
- Database downloads (`dl_database`, `dl_files`, `RECORDS` and
`ANNOTATORS`) still use `_url`. Moving them to `physionet.download()`
can follow separately.
- `tests/conftest.py` also treats the `physionet` package's API errors
with a 5xx or 429 status, and the built-in `ConnectionError` it raises,
as PhysioNet being unavailable, so those network tests are skipped
rather than failed. physionet.org returned 502 for a fair share of
requests while I was testing.
- Docs: `docs/io.rst` says that `pn_dir` reads the same way as
`physionet://`, and a changelog entry is added.

## Testing

- New tests in `tests/test_physionet_uri.py`. With every request made to
fail, `rdrecord` with `pn_dir` reads format 212, a header without a
signal length (which needs the file size), FLAC and a multi-segment
record from the `physionet` cache, and `rdheader` and `rdann` read a
header and annotations, all matching the local files. `get_version`
looks each database up once, retries a 502 and a connection error, does
not retry a 403, stops after three attempts, and raises
`FileNotFoundError` for a missing database. With `set_db_index_url` set
to another server, files are read from it with `_url.openurl`. Without
the change, 6 of these fail and 3 cannot run.
- `uv run pytest -m "not network"`: 476 passed, also with `--python 3.11
--resolution lowest-direct`.
- `uv run pytest -m network`: 18 passed, so the `physionet` variants of
the existing read tests, which all use `pn_dir`, pass against PhysioNet.
- `ruff format --check`, `ruff check` and the docs build pass.

The header-without-length case is read without `sampto`, since reading
such a header with `sampto` fails on `main` too, which #654 fixes.

<sub>@tompollard 🟥 red 🦥 sloth</sub>
tompollard added a commit that referenced this pull request Nov 23, 2026
Follows #657 and #658. `dl_database` and `dl_files` now download files
with `physionet.download()`, using the `files=` and `verbose=` arguments
added in physionet 0.7.0 (MIT-LCP/physionet#218) and `overwrite=` added
in 0.7.1 (MIT-LCP/physionet#221), so they keep their arguments and
folder layout.

Downloading the same files on `main` and on this branch against
PhysioNet gave identical files (13, including a file in a subfolder and
the `keep_subdirs=False` layout):

| | `main` | This PR |
|---|---|---|
| `dl_database("mitdb", records=["100", "101", "102"],
annotators=["atr"])` | 38 requests, 11.2 s | 20 requests, 4.9 s |
| `dl_files("mitdb", [...])` with 2 files | 4 requests, about 0.7 s | 6
requests, 1.7 s |

`dl_database` is faster mainly because it finds which annotation files
there are from the checksum list, rather than requesting each one. A
small `dl_files` call costs a little more, since `physionet.download()`
looks up the version, the checksum list and the source first.

## Changes

- A new `download._download_files(db_dir, dl_dir, files, keep_subdirs,
overwrite)` maps each file (relative to `db_dir`, which may include a
subdirectory) to where it is saved (the same path relative to `dl_dir`,
or its name with `keep_subdirs=False`), and calls
`physionet.download(slug, version, files=..., verbose=False,
show_progress=False, jobs=2, overwrite=overwrite)`. Two files at a time,
no progress bars and wfdb's own messages, as before.
- 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, and any other saved file is downloaded again. Before,
only sizes were compared, so a saved file of the right size but
different content was kept. With `overwrite=True`, physionet downloads
every file again, but only after checking all the requested files and
destinations, and replaces each saved file only once its new copy is
complete and checked, so wfdb removes nothing itself.
- Restricted databases can be downloaded after `physionet login`.
`get_record_list` and `get_annotators` read `RECORDS` and `ANNOTATORS`
with `_open_pn_file`, so through `physionet://` too.
- `dl_database` finds annotation files with a new
`download._project_files(db_dir)`, which lists the files from the
checksum list through the `physionet://` filesystem, instead of a
request for each record and annotator.
- `dl_files` no longer requests the database's web page first: physionet
reports a missing database, version or file before downloading anything.
Before, the files listed before a missing one were downloaded first.
- With `keep_subdirs=False`, two files with the same name now raise a
`ValueError` from physionet, instead of one silently replacing the
other.
- With a database index URL set by `set_db_index_url`, both functions
download from that server with the existing code.
- `physionet >= 0.7.1` is now required. The `overwrite` docs and a new
Notes section describe the behaviour, and a changelog entry is added.

## Testing

- New tests in `tests/test_physionet_uri.py` build a database in a
temporary `physionet` cache (`RECORDS`, `ANNOTATORS`, a single-segment,
a multi-segment and a subdirectory record, and a checksum list), make
every request fail, and replace `physionet.download` to record its
arguments. They check the files and where they are saved, a subdirectory
in `db_dir`, `keep_subdirs=False`, that `overwrite` is passed through
and wfdb removes nothing itself, `dl_files` with both layouts and
without a web page request, and `dl_files` with `set_db_index_url`.
Tests of `overwrite=True` with a path outside `dl_dir`, two files with
one name, and names that differ only in case run through the real
`physionet.download`, which refuses them before replacing anything.
- `uv run pytest -m "not network"`: 507 passed, also with `--python 3.11
--resolution lowest-direct`.
- `uv run pytest -m network`: 18 passed, including the existing
`dl_database` tests that download from PhysioNet's `afdb`.
- `ruff format --check`, `ruff check` and the docs build pass.

<sub>@tompollard 🟥 red 🦥 sloth</sub>
tompollard added a commit that referenced this pull request Nov 23, 2026
## Summary

Bump the version from 5.0.0 to 5.1.0, and collect the changelog entries
in `changelog.d/` into `docs/changes.rst` with `towncrier build --date
"Nov 2026"`, with a short summary at the top of the new section.

This is a minor release: it adds `physionet://` URIs and reads `pn_dir`
records and downloads databases through the `physionet` package, which
becomes a dependency (#657, #658, #659), speeds up `xqrs_detect` and
`gqrs_detect` (#655, #656), and fixes `rdann` and
`Annotation.apply_range` (#654, #660, #661). The one change existing
code may notice is that `rdann` now raises a `ValueError` when `sampto`
is not greater than `sampfrom`, including `sampto=0`, which used to
return every annotation. The summary calls it out.

It also raises the `physionet` requirement from 0.7.1 to 0.7.2, which
retries transient server errors when looking up a database's latest
version, as `pn_dir` without a version does, and updates that changelog
entry to match.

## Checks

- `uv run pytest -m "not network"`: 511 passed, also with `--python 3.11
--resolution lowest-direct` (physionet 0.7.2). `uv run pytest -m
network`: 18 passed.
- `ruff format --check`, `ruff check` and the Sphinx HTML build with
warnings as errors pass.
- The wheel and source distribution build, pass `twine check`, and have
`Version: 5.1.0` and `Requires-Dist: physionet>=0.7.2`.
- PyPI has no 5.1.0 release yet.

<sub>@tompollard 🟥 red 🦥 sloth</sub>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant