Skip to content

Commit 11a56cf

Browse files
authored
Read PhysioNet records whose names include folders (#666)
Fixes #467. `rdheader`, `rdrecord`, `rdsamp` and `rdann` with `pn_dir` dropped any folders at the start of the record name. So `rdrecord("files/p1000/p10000032/s40689238/40689238", pn_dir="mimic-iv-ecg/1.0")` looked for `40689238.hea` at the top of the database, and failed with "file not found". The folders now move to the end of `pn_dir`, so the folders can be given in either argument. - A new helper, `_resolve_pn_dir`, does this and also adds the latest version when `pn_dir` has none. That code was repeated in each of the three functions. - Segments of multi-segment records on PhysioNet are now read by name from `pn_dir`. Before, the local working directory was joined to the segment name and then dropped along with any other folders. A network test (`test_multi_variable_d[physionet]`) caught this. - `docs/io.rst` describes folders in either argument. ## Testing - New offline tests read a single-segment record (header, signal and annotations) and a multi-segment record from folders in a cached database, with `pn_dir` with a version, without one, and with some of the folders in `pn_dir`. They fail on `main`. A network test reads the MIMIC-IV-ECG record from the issue. - `pytest`: all offline and network tests pass, also with `--resolution lowest-direct`. Ruff and the docs build pass. <sub>@tompollard 🟥 red 🦥 sloth · aspen</sub>
2 parents dab676d + e7c1441 commit 11a56cf

5 files changed

Lines changed: 130 additions & 58 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
**Read PhysioNet records whose names include folders**
2+
``rdrecord``, ``rdsamp``, ``rdheader`` and ``rdann`` with ``pn_dir`` now
3+
read a record name that starts with folders, such as
4+
``rdrecord("files/p1000/p10000032/s40689238/40689238",
5+
pn_dir="mimic-iv-ecg/1.0")``, from those folders of the database. They used
6+
to drop the folders and look for the record at the top of the database,
7+
which failed with a "file not found" error.

‎docs/io.rst‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,13 @@ setting ``PHYSIONET_TOKEN``). See the `physionet package
167167

168168
The ``pn_dir`` argument reads files the same way, so
169169
``wfdb.rdrecord("100", pn_dir="mitdb")`` and
170-
``wfdb.rdrecord("physionet://mitdb/1.0.0/100")`` read the same files. When
171-
``pn_dir`` has no version, the latest version is looked up once per database,
172-
and used until the program ends. If the database index URL has been changed
170+
``wfdb.rdrecord("physionet://mitdb/1.0.0/100")`` read the same files. For a
171+
record in a folder of the database, the folders can be given in either
172+
argument, so ``wfdb.rdrecord("files/p1000/p10000032/s40689238/40689238",
173+
pn_dir="mimic-iv-ecg/1.0")`` and ``wfdb.rdrecord("40689238",
174+
pn_dir="mimic-iv-ecg/1.0/files/p1000/p10000032/s40689238")`` read the same
175+
record. When ``pn_dir`` has no version, the latest version is looked up once
176+
per database, and used until the program ends. If the database index URL has been changed
173177
with ``wfdb.io.download.set_db_index_url``, files are read from that server
174178
instead, as before.
175179

‎src/wfdb/io/annotation.py‎

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
import copy
22
import os
3-
import posixpath
43
import re
54
import sys
65

76
import numpy as np
87
import pandas as pd
98

109
from wfdb.io import _header, download, record, util
11-
from wfdb.io._coreio import CLOUD_PROTOCOLS, _fsspec_open
10+
from wfdb.io._coreio import _fsspec_open
1211
from wfdb.io.archive import WFDBArchive, is_archive_path
1312

1413

@@ -1967,6 +1966,8 @@ def rdann(
19671966
Option used to stream data from Physionet. The PhysioNet database
19681967
directory from which to find the required annotation file. eg. For
19691968
record '100' in 'http://physionet.org/content/mitdb': pn_dir='mitdb'.
1969+
Folders in the database may be given in `record_name`, in `pn_dir`,
1970+
or split between them.
19701971
return_label_elements : list, optional
19711972
The label elements that are to be returned from reading the annotation
19721973
file. A list with at least one of the following options: 'symbol',
@@ -2003,16 +2004,7 @@ def rdann(
20032004
record._check_archive_read_args(record_name, pn_dir)
20042005

20052006
if pn_dir is not None:
2006-
# check to make sure a cloud path isn't being passed under pn_dir
2007-
if any(pn_dir.startswith(proto) for proto in CLOUD_PROTOCOLS):
2008-
raise ValueError(
2009-
"Cloud paths should be passed under record_name, not under pn_dir"
2010-
)
2011-
if "." not in pn_dir:
2012-
dir_list = pn_dir.split("/")
2013-
pn_dir = posixpath.join(
2014-
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
2015-
)
2007+
record_name, pn_dir = record._resolve_pn_dir(record_name, pn_dir)
20162008

20172009
return_label_elements = check_read_inputs(sampfrom, sampto, return_label_elements)
20182010

‎src/wfdb/io/record.py‎

Lines changed: 68 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,8 @@ class BaseRecord:
163163
extensions. If the argument contains any path delimiter
164164
characters, the argument will be interpreted as PATH/BASE_RECORD.
165165
Both relative and absolute paths are accepted. If `pn_dir` is set,
166-
`record_name` should contain just the base record name, and the
167-
files will be searched for remotely on PhysioNet. Otherwise,
166+
the files are read from PhysioNet, and folders in the database may be
167+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
168168
files are searched for locally, or when `record_name` is a
169169
supported cloud URI, they are read directly from cloud storage
170170
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
@@ -696,8 +696,8 @@ class Record(BaseRecord, _header.HeaderMixin, _signal.SignalMixin):
696696
extensions. If the argument contains any path delimiter
697697
characters, the argument will be interpreted as PATH/BASE_RECORD.
698698
Both relative and absolute paths are accepted. If `pn_dir` is set,
699-
`record_name` should contain just the base record name, and the
700-
files will be searched for remotely on PhysioNet. Otherwise,
699+
the files are read from PhysioNet, and folders in the database may be
700+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
701701
files are searched for locally, or when `record_name` is a
702702
supported cloud URI, they are read directly from cloud storage
703703
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
@@ -1083,8 +1083,8 @@ class MultiRecord(BaseRecord, _header.MultiHeaderMixin):
10831083
extensions. If the argument contains any path delimiter
10841084
characters, the argument will be interpreted as PATH/BASE_RECORD.
10851085
Both relative and absolute paths are accepted. If `pn_dir` is set,
1086-
`record_name` should contain just the base record name, and the
1087-
files will be searched for remotely on PhysioNet. Otherwise,
1086+
the files are read from PhysioNet, and folders in the database may be
1087+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
10881088
files are searched for locally, or when `record_name` is a
10891089
supported cloud URI, they are read directly from cloud storage
10901090
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
@@ -1830,6 +1830,44 @@ def check_np_array(item, field_name, ndim, parent_class, channel_num=None):
18301830
# ------------------------- Reading Records --------------------------- #
18311831

18321832

1833+
def _resolve_pn_dir(record_name, pn_dir):
1834+
"""Find the PhysioNet directory and name of a record to read.
1835+
1836+
Adds the latest version of the database to `pn_dir` if it has no version,
1837+
and moves any folders in `record_name` to the end of `pn_dir`, so that
1838+
reading "files/p1/100" with pn_dir="demo" reads "100" with
1839+
pn_dir="demo/<latest version>/files/p1".
1840+
1841+
Parameters
1842+
----------
1843+
record_name : str
1844+
The name of the record, which may start with folders in the database.
1845+
pn_dir : str
1846+
The PhysioNet database, with an optional version and folders.
1847+
1848+
Returns
1849+
-------
1850+
record_name : str
1851+
The name of the record, without folders.
1852+
pn_dir : str
1853+
The PhysioNet directory that holds the record.
1854+
1855+
"""
1856+
if any(pn_dir.startswith(proto) for proto in CLOUD_PROTOCOLS):
1857+
raise ValueError(
1858+
"Cloud paths should be passed under record_name, not under pn_dir"
1859+
)
1860+
if "." not in pn_dir:
1861+
dir_list = pn_dir.split("/")
1862+
pn_dir = posixpath.join(
1863+
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
1864+
)
1865+
folders, record_name = posixpath.split(record_name)
1866+
if folders:
1867+
pn_dir = posixpath.join(pn_dir, folders)
1868+
return record_name, pn_dir
1869+
1870+
18331871
def rdheader(record_name, pn_dir=None, rd_segments=False):
18341872
"""Read a WFDB header file and return a `Record` or `MultiRecord`.
18351873
@@ -1842,8 +1880,8 @@ def rdheader(record_name, pn_dir=None, rd_segments=False):
18421880
extensions. If the argument contains any path delimiter
18431881
characters, the argument will be interpreted as PATH/BASE_RECORD.
18441882
Both relative and absolute paths are accepted. If `pn_dir` is set,
1845-
`record_name` should contain just the base record name, and the
1846-
files will be searched for remotely on PhysioNet. Otherwise,
1883+
the files are read from PhysioNet, and folders in the database may be
1884+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
18471885
files are searched for locally, or when `record_name` is a
18481886
supported cloud URI, they are read directly from cloud storage
18491887
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
@@ -1893,18 +1931,8 @@ def rdheader(record_name, pn_dir=None, rd_segments=False):
18931931
# If the PhysioNet database path is provided, construct the download path using the
18941932
# database version
18951933
elif pn_dir is not None:
1896-
# check to make sure a cloud path isn't being passed under pn_dir
1897-
if any(pn_dir.startswith(proto) for proto in CLOUD_PROTOCOLS):
1898-
raise ValueError(
1899-
"Cloud paths should be passed under record_name, not under pn_dir"
1900-
)
1901-
1902-
if "." not in pn_dir:
1903-
dir_list = pn_dir.split("/")
1904-
pn_dir = posixpath.join(
1905-
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
1906-
)
1907-
1934+
base_record_name, pn_dir = _resolve_pn_dir(record_name, pn_dir)
1935+
file_name = f"{base_record_name}.hea"
19081936
header_content = download._stream_header(file_name, pn_dir)
19091937

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

19581988

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

22232253
# Read the header fields
22242254
if pn_dir is not None:
2225-
# check to make sure a cloud path isn't being passed under pn_dir
2226-
if any(pn_dir.startswith(proto) for proto in CLOUD_PROTOCOLS):
2227-
raise ValueError(
2228-
"Cloud paths should be passed under record_name, not under pn_dir"
2229-
)
2230-
if "." not in pn_dir:
2231-
dir_list = pn_dir.split("/")
2232-
pn_dir = posixpath.join(
2233-
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
2234-
)
2255+
record_name, pn_dir = _resolve_pn_dir(record_name, pn_dir)
22352256

22362257
if wfdb_archive is not None:
22372258
segment_name = None if is_archive_path(record_name) else record_name
@@ -2422,8 +2443,12 @@ def _rdrecord(
24222443
wfdb_archive=wfdb_archive,
24232444
)
24242445
else:
2446+
# On PhysioNet, the segments are in pn_dir, not in dir_name
2447+
segment_name = record.seg_name[seg_num]
2448+
if pn_dir is None:
2449+
segment_name = _join_path(dir_name, segment_name)
24252450
record.segments[seg_num] = rdrecord(
2426-
_join_path(dir_name, record.seg_name[seg_num]),
2451+
segment_name,
24272452
sampfrom=seg_ranges[i][0],
24282453
sampto=seg_ranges[i][1],
24292454
channels=seg_channels[i],
@@ -2479,8 +2504,8 @@ def rdsamp(
24792504
extensions. If the argument contains any path delimiter
24802505
characters, the argument will be interpreted as PATH/BASE_RECORD.
24812506
Both relative and absolute paths are accepted. If `pn_dir` is set,
2482-
`record_name` should contain just the base record name, and the
2483-
files will be searched for remotely on PhysioNet. Otherwise,
2507+
the files are read from PhysioNet, and folders in the database may be
2508+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
24842509
files are searched for locally, or when `record_name` is a
24852510
supported cloud URI, they are read directly from cloud storage
24862511
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
@@ -2601,8 +2626,8 @@ def sampfreq(record_name, pn_dir=None):
26012626
extensions. If the argument contains any path delimiter
26022627
characters, the argument will be interpreted as PATH/BASE_RECORD.
26032628
Both relative and absolute paths are accepted. If `pn_dir` is set,
2604-
`record_name` should contain just the base record name, and the
2605-
files will be searched for remotely on PhysioNet. Otherwise,
2629+
the files are read from PhysioNet, and folders in the database may be
2630+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
26062631
files are searched for locally, or when `record_name` is a
26072632
supported cloud URI, they are read directly from cloud storage
26082633
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
@@ -2653,8 +2678,8 @@ def signame(record_name, pn_dir=None, sig_nums=[]):
26532678
extensions. If the argument contains any path delimiter
26542679
characters, the argument will be interpreted as PATH/BASE_RECORD.
26552680
Both relative and absolute paths are accepted. If `pn_dir` is set,
2656-
`record_name` should contain just the base record name, and the
2657-
files will be searched for remotely on PhysioNet. Otherwise,
2681+
the files are read from PhysioNet, and folders in the database may be
2682+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
26582683
files are searched for locally, or when `record_name` is a
26592684
supported cloud URI, they are read directly from cloud storage
26602685
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
@@ -2714,8 +2739,8 @@ def wfdbdesc(record_name, pn_dir=None):
27142739
extensions. If the argument contains any path delimiter
27152740
characters, the argument will be interpreted as PATH/BASE_RECORD.
27162741
Both relative and absolute paths are accepted. If `pn_dir` is set,
2717-
`record_name` should contain just the base record name, and the
2718-
files will be searched for remotely on PhysioNet. Otherwise,
2742+
the files are read from PhysioNet, and folders in the database may be
2743+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
27192744
files are searched for locally, or when `record_name` is a
27202745
supported cloud URI, they are read directly from cloud storage
27212746
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,
@@ -2850,8 +2875,8 @@ def wfdbtime(record_name, input_times, pn_dir=None):
28502875
extensions. If the argument contains any path delimiter
28512876
characters, the argument will be interpreted as PATH/BASE_RECORD.
28522877
Both relative and absolute paths are accepted. If `pn_dir` is set,
2853-
`record_name` should contain just the base record name, and the
2854-
files will be searched for remotely on PhysioNet. Otherwise,
2878+
the files are read from PhysioNet, and folders in the database may be
2879+
given in `record_name`, in `pn_dir`, or split between them. Otherwise,
28552880
files are searched for locally, or when `record_name` is a
28562881
supported cloud URI, they are read directly from cloud storage
28572882
via `fsspec`. Supported URIs: `s3://`, `gs://`, `az://`,

‎tests/test_physionet_uri.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,50 @@ def test_pn_dir_rdheader_and_rdann(physionet_cache, offline):
163163
np.testing.assert_array_equal(annotation.sample, expected.sample)
164164

165165

166+
@pytest.mark.parametrize("pn_dir", ["demo/1.0", "demo/1.0/files", "demo"])
167+
def test_pn_dir_record_name_with_folders(physionet_cache, offline, versions, pn_dir):
168+
"""Folders at the start of the record name are folders in the database."""
169+
_, results = versions
170+
results["demo"] = "1.0"
171+
target = physionet_cache / "physionet.org" / "demo" / "1.0" / "files" / "p1"
172+
target.mkdir(parents=True)
173+
for name in ["100.hea", "100.dat", "100.atr"]:
174+
shutil.copy(SAMPLE_DATA / name, target / name)
175+
record_name = "p1/100" if pn_dir.endswith("files") else "files/p1/100"
176+
177+
header = wfdb.rdheader(record_name, pn_dir=pn_dir)
178+
record = wfdb.rdrecord(record_name, pn_dir=pn_dir, sampto=1000)
179+
annotation = wfdb.rdann(record_name, "atr", pn_dir=pn_dir, sampto=1000)
180+
181+
assert header.sig_name == ["MLII", "V5"]
182+
expected = wfdb.rdrecord("sample-data/100", sampto=1000)
183+
np.testing.assert_array_equal(record.p_signal, expected.p_signal)
184+
expected_ann = wfdb.rdann("sample-data/100", "atr", sampto=1000)
185+
np.testing.assert_array_equal(annotation.sample, expected_ann.sample)
186+
assert annotation.record_name == "100"
187+
188+
189+
def test_pn_dir_multi_segment_record_in_a_folder(physionet_cache, offline):
190+
folder = SAMPLE_DATA / "multi-segment" / "041s"
191+
target = physionet_cache / "physionet.org" / "demo" / "1.0" / "subjects" / "041"
192+
target.mkdir(parents=True)
193+
for name in ["041s.hea", "041s01.hea", "041s01.dat", "041s02.hea", "041s02.dat"]:
194+
shutil.copy(folder / name, target / name)
195+
196+
record = wfdb.rdrecord("subjects/041/041s", pn_dir="demo/1.0", sampto=1000)
197+
198+
expected = wfdb.rdrecord(str(folder / "041s"), sampto=1000)
199+
np.testing.assert_array_equal(record.p_signal, expected.p_signal)
200+
201+
202+
@pytest.mark.network
203+
def test_pn_dir_record_name_with_folders_from_physionet():
204+
header = wfdb.rdheader(
205+
"files/p1000/p10000032/s40689238/40689238", pn_dir="mimic-iv-ecg/1.0"
206+
)
207+
assert header.sig_len == 5000
208+
209+
166210
@pytest.fixture
167211
def versions(monkeypatch):
168212
"""Replace physionet.latest_version, recording calls, and clear the cache."""

0 commit comments

Comments
 (0)