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
7 changes: 7 additions & 0 deletions changelog.d/pn-dir-record-folders.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
**Read PhysioNet records whose names include folders**
``rdrecord``, ``rdsamp``, ``rdheader`` and ``rdann`` with ``pn_dir`` now
read a record name that starts with folders, such as
``rdrecord("files/p1000/p10000032/s40689238/40689238",
pn_dir="mimic-iv-ecg/1.0")``, from those folders of the database. They used
to drop the folders and look for the record at the top of the database,
which failed with a "file not found" error.
10 changes: 7 additions & 3 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,13 @@ setting ``PHYSIONET_TOKEN``). See the `physionet package

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
``wfdb.rdrecord("physionet://mitdb/1.0.0/100")`` read the same files. For a
record in a folder of the database, the folders can be given in either
argument, so ``wfdb.rdrecord("files/p1000/p10000032/s40689238/40689238",
pn_dir="mimic-iv-ecg/1.0")`` and ``wfdb.rdrecord("40689238",
pn_dir="mimic-iv-ecg/1.0/files/p1000/p10000032/s40689238")`` read the same
record. 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.

Expand Down
16 changes: 4 additions & 12 deletions src/wfdb/io/annotation.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import copy
import os
import posixpath
import re
import sys

import numpy as np
import pandas as pd

from wfdb.io import _header, download, record, util
from wfdb.io._coreio import CLOUD_PROTOCOLS, _fsspec_open
from wfdb.io._coreio import _fsspec_open
from wfdb.io.archive import WFDBArchive, is_archive_path


Expand Down Expand Up @@ -1964,6 +1963,8 @@ def rdann(
Option used to stream data from Physionet. The PhysioNet database
directory from which to find the required annotation file. eg. For
record '100' in 'http://physionet.org/content/mitdb': pn_dir='mitdb'.
Folders in the database may be given in `record_name`, in `pn_dir`,
or split between them.
return_label_elements : list, optional
The label elements that are to be returned from reading the annotation
file. A list with at least one of the following options: 'symbol',
Expand Down Expand Up @@ -2000,16 +2001,7 @@ def rdann(
record._check_archive_read_args(record_name, pn_dir)

if pn_dir is not None:
# check to make sure a cloud path isn't being passed under pn_dir
if any(pn_dir.startswith(proto) for proto in CLOUD_PROTOCOLS):
raise ValueError(
"Cloud paths should be passed under record_name, not under pn_dir"
)
if "." not in pn_dir:
dir_list = pn_dir.split("/")
pn_dir = posixpath.join(
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
)
record_name, pn_dir = record._resolve_pn_dir(record_name, pn_dir)

return_label_elements = check_read_inputs(sampfrom, sampto, return_label_elements)

Expand Down
111 changes: 68 additions & 43 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ class BaseRecord:
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -696,8 +696,8 @@ class Record(BaseRecord, _header.HeaderMixin, _signal.SignalMixin):
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -1083,8 +1083,8 @@ class MultiRecord(BaseRecord, _header.MultiHeaderMixin):
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -1830,6 +1830,44 @@ def check_np_array(item, field_name, ndim, parent_class, channel_num=None):
# ------------------------- Reading Records --------------------------- #


def _resolve_pn_dir(record_name, pn_dir):
"""Find the PhysioNet directory and name of a record to read.
Adds the latest version of the database to `pn_dir` if it has no version,
and moves any folders in `record_name` to the end of `pn_dir`, so that
reading "files/p1/100" with pn_dir="demo" reads "100" with
pn_dir="demo/<latest version>/files/p1".
Parameters
----------
record_name : str
The name of the record, which may start with folders in the database.
pn_dir : str
The PhysioNet database, with an optional version and folders.
Returns
-------
record_name : str
The name of the record, without folders.
pn_dir : str
The PhysioNet directory that holds the record.
"""
if any(pn_dir.startswith(proto) for proto in CLOUD_PROTOCOLS):
raise ValueError(
"Cloud paths should be passed under record_name, not under pn_dir"
)
if "." not in pn_dir:
dir_list = pn_dir.split("/")
pn_dir = posixpath.join(
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
)
folders, record_name = posixpath.split(record_name)
if folders:
pn_dir = posixpath.join(pn_dir, folders)
return record_name, pn_dir


def rdheader(record_name, pn_dir=None, rd_segments=False):
"""Read a WFDB header file and return a `Record` or `MultiRecord`.
Expand All @@ -1842,8 +1880,8 @@ def rdheader(record_name, pn_dir=None, rd_segments=False):
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -1893,18 +1931,8 @@ def rdheader(record_name, pn_dir=None, rd_segments=False):
# If the PhysioNet database path is provided, construct the download path using the
# database version
elif pn_dir is not None:
# check to make sure a cloud path isn't being passed under pn_dir
if any(pn_dir.startswith(proto) for proto in CLOUD_PROTOCOLS):
raise ValueError(
"Cloud paths should be passed under record_name, not under pn_dir"
)

if "." not in pn_dir:
dir_list = pn_dir.split("/")
pn_dir = posixpath.join(
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
)

base_record_name, pn_dir = _resolve_pn_dir(record_name, pn_dir)
file_name = f"{base_record_name}.hea"
header_content = download._stream_header(file_name, pn_dir)

# If it isn't a cloud path or a PhysioNet path, we treat as a local file
Expand Down Expand Up @@ -1953,6 +1981,8 @@ def _read_record_header(record_name, dir_name, pn_dir, wfdb_archive):
"""
if wfdb_archive is not None:
return _parse_header_content(wfdb_archive.read_header(record_name))
if pn_dir is not None:
return rdheader(record_name, pn_dir=pn_dir)
return rdheader(_join_path(dir_name, record_name), pn_dir=pn_dir)


Expand Down Expand Up @@ -2075,8 +2105,8 @@ def rdrecord(
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -2222,16 +2252,7 @@ def _rdrecord(

# Read the header fields
if pn_dir is not None:
# check to make sure a cloud path isn't being passed under pn_dir
if any(pn_dir.startswith(proto) for proto in CLOUD_PROTOCOLS):
raise ValueError(
"Cloud paths should be passed under record_name, not under pn_dir"
)
if "." not in pn_dir:
dir_list = pn_dir.split("/")
pn_dir = posixpath.join(
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
)
record_name, pn_dir = _resolve_pn_dir(record_name, pn_dir)

if wfdb_archive is not None:
segment_name = None if is_archive_path(record_name) else record_name
Expand Down Expand Up @@ -2422,8 +2443,12 @@ def _rdrecord(
wfdb_archive=wfdb_archive,
)
else:
# On PhysioNet, the segments are in pn_dir, not in dir_name
segment_name = record.seg_name[seg_num]
if pn_dir is None:
segment_name = _join_path(dir_name, segment_name)
record.segments[seg_num] = rdrecord(
_join_path(dir_name, record.seg_name[seg_num]),
segment_name,
sampfrom=seg_ranges[i][0],
sampto=seg_ranges[i][1],
channels=seg_channels[i],
Expand Down Expand Up @@ -2479,8 +2504,8 @@ def rdsamp(
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -2601,8 +2626,8 @@ def sampfreq(record_name, pn_dir=None):
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -2653,8 +2678,8 @@ def signame(record_name, pn_dir=None, sig_nums=[]):
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -2714,8 +2739,8 @@ def wfdbdesc(record_name, pn_dir=None):
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down Expand Up @@ -2850,8 +2875,8 @@ def wfdbtime(record_name, input_times, pn_dir=None):
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If `pn_dir` is set,
`record_name` should contain just the base record name, and the
files will be searched for remotely on PhysioNet. Otherwise,
the files are read from PhysioNet, and folders in the database may be
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
files are searched for locally, or when `record_name` is a
supported cloud URI, they are read directly from cloud storage
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
Expand Down
44 changes: 44 additions & 0 deletions tests/test_physionet_uri.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,50 @@ def test_pn_dir_rdheader_and_rdann(physionet_cache, offline):
np.testing.assert_array_equal(annotation.sample, expected.sample)


@pytest.mark.parametrize("pn_dir", ["demo/1.0", "demo/1.0/files", "demo"])
def test_pn_dir_record_name_with_folders(physionet_cache, offline, versions, pn_dir):
"""Folders at the start of the record name are folders in the database."""
_, results = versions
results["demo"] = "1.0"
target = physionet_cache / "physionet.org" / "demo" / "1.0" / "files" / "p1"
target.mkdir(parents=True)
for name in ["100.hea", "100.dat", "100.atr"]:
shutil.copy(SAMPLE_DATA / name, target / name)
record_name = "p1/100" if pn_dir.endswith("files") else "files/p1/100"

header = wfdb.rdheader(record_name, pn_dir=pn_dir)
record = wfdb.rdrecord(record_name, pn_dir=pn_dir, sampto=1000)
annotation = wfdb.rdann(record_name, "atr", pn_dir=pn_dir, sampto=1000)

assert header.sig_name == ["MLII", "V5"]
expected = wfdb.rdrecord("sample-data/100", sampto=1000)
np.testing.assert_array_equal(record.p_signal, expected.p_signal)
expected_ann = wfdb.rdann("sample-data/100", "atr", sampto=1000)
np.testing.assert_array_equal(annotation.sample, expected_ann.sample)
assert annotation.record_name == "100"


def test_pn_dir_multi_segment_record_in_a_folder(physionet_cache, offline):
folder = SAMPLE_DATA / "multi-segment" / "041s"
target = physionet_cache / "physionet.org" / "demo" / "1.0" / "subjects" / "041"
target.mkdir(parents=True)
for name in ["041s.hea", "041s01.hea", "041s01.dat", "041s02.hea", "041s02.dat"]:
shutil.copy(folder / name, target / name)

record = wfdb.rdrecord("subjects/041/041s", pn_dir="demo/1.0", sampto=1000)

expected = wfdb.rdrecord(str(folder / "041s"), sampto=1000)
np.testing.assert_array_equal(record.p_signal, expected.p_signal)


@pytest.mark.network
def test_pn_dir_record_name_with_folders_from_physionet():
header = wfdb.rdheader(
"files/p1000/p10000032/s40689238/40689238", pn_dir="mimic-iv-ecg/1.0"
)
assert header.sig_len == 5000


@pytest.fixture
def versions(monkeypatch):
"""Replace physionet.latest_version, recording calls, and clear the cache."""
Expand Down
Loading