Skip to content

Commit d7087ea

Browse files
authored
Read EDF and WAV files from physionet:// and other URIs (#674)
Part of #534: the first step towards phasing out `pn_dir`, which is that every function that takes `pn_dir` also takes a `physionet://` URI. Of the 15 public functions that take `pn_dir`, all but three already accepted a `physionet://` URI as `record_name`, because they read through `rdrecord`, `rdheader` or `rdann`. The other three, `read_edf`, `rdedfann` and `read_wav`, opened the path with `open()`, so `read_edf("physionet://chbmit/1.0.0/chb01/chb01_01.edf")` failed with `FileNotFoundError`. They also couldn't read `s3://` or `memory://` paths. - A new helper, `_coreio._open_input_file`, opens a local file as before, or reads a URI into memory (through `fsspec`, so `physionet://` uses the physionet package, with its cache and sign-in). - `read_edf` and `read_wav` read the samples with `np.frombuffer` and the file size with `seek`, instead of `np.fromfile` and `os.path.getsize`, which need a local file. `read_wav` now also closes its file. - Output names (`record_name` of the returned record, and the files written by `wfdb_to_edf` and `wfdb_to_wav`) use the last part of a URI on every platform, instead of splitting on `os.sep`. URIs are read without saving a copy, unlike `pn_dir`, which downloads the file into the current directory (and `read_edf` leaves it there). That `pn_dir` behaviour is unchanged here. ## Testing - New offline tests read `n16.edf`, `SC4001E0-PSG.wav` and `test_edfann.edf` with `physionet://` (from the cache) and `memory://` URIs, and compare them with the local files. They also check that nothing is written to the current directory. These fail on `main`. Another test checks that `wfdb_to_mat` and `sigavg` read `physionet://` URIs, as they already did. - Local files give identical results to `main` (signals, names, initial values and checksums) for `n16.edf`, `wave_4.edf`, `SC4001E0-PSG.wav` and the `rdedfann` output of `test_edfann.edf`. - `read_edf("physionet://chbmit/1.0.0/chb01/chb01_01.edf")` reads all 23 signals from PhysioNet in about 14 seconds. - `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 3739fb8 + b02b38e commit d7087ea

5 files changed

Lines changed: 182 additions & 18 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
**Read EDF and WAV files from physionet:// and other URIs**
2+
``read_edf``, ``rdedfann`` and ``read_wav`` now take a cloud URI as
3+
``record_name``, such as ``physionet://chbmit/1.0.0/chb01/chb01_01.edf``,
4+
``s3://`` or ``memory://``, as ``rdrecord`` and ``rdann`` do, and read the
5+
file without saving a copy. All of the functions that take ``pn_dir`` now
6+
also take a ``physionet://`` URI. Output files written by ``wfdb_to_edf``
7+
and ``wfdb_to_wav`` for a URI are named after the record, on every platform.

‎src/wfdb/io/_coreio.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,31 @@ def _split_path(record_name):
6363
return os.path.split(path)
6464

6565

66+
def _open_input_file(path):
67+
"""Open a local file, or a file at a cloud URI, to read in binary mode.
68+
69+
A file at a cloud URI, such as a `physionet://` URI, is read as it is
70+
needed (for `physionet://`, with HTTP range requests), so that reading
71+
only the start of a file does not fetch the rest. It can be sought and
72+
sized like a local file.
73+
74+
Parameters
75+
----------
76+
path : str or os.PathLike
77+
The path of a local file, or a cloud URI.
78+
79+
Returns
80+
-------
81+
file
82+
The open file.
83+
84+
"""
85+
path = os.fspath(path)
86+
if any(path.startswith(proto) for proto in CLOUD_PROTOCOLS):
87+
return _fsspec_open(path, "rb").open()
88+
return open(path, "rb")
89+
90+
6691
def _join_path(dir_name, file_name):
6792
"""Join a local directory or cloud URI with a file name.
6893

‎src/wfdb/io/convert/edf.py‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import pandas as pd
1010

1111
from wfdb.io import download
12+
from wfdb.io._coreio import _open_input_file, _split_path
1213
from wfdb.io._signal import _checksums
1314
from wfdb.io.annotation import Annotation, format_ann_from_df, wrann
1415
from wfdb.io.record import SIG_UNITS, Record, rdrecord
@@ -43,7 +44,11 @@ def read_edf(
4344
Parameters
4445
----------
4546
record_name : str
46-
The name of the input EDF record to be read.
47+
The path of the input EDF file to be read, including its
48+
extension. This can also be a cloud URI, such as
49+
'physionet://chbmit/1.0.0/chb01/chb01_01.edf' or 's3://...', which
50+
is read without saving a copy of the file. With `header_only`,
51+
only the header is read.
4752
pn_dir : str, optional
4853
Option used to stream data from Physionet. The Physionet
4954
database directory from which to find the required record files.
@@ -142,7 +147,7 @@ def read_edf(
142147
open(record_name, "wb").write(f.read())
143148

144149
# Open the desired file
145-
edf_file = open(record_name, mode="rb")
150+
edf_file = _open_input_file(record_name)
146151

147152
# Version of this data format (8 bytes)
148153
version = struct.unpack("<8s", edf_file.read(8))[0].decode(encoding)
@@ -323,9 +328,7 @@ def read_edf(
323328
struct.unpack("<32s", edf_file.read(32))[0].decode(encoding)
324329

325330
# Pre-process the acquired data before creating the record
326-
record_name_out = (
327-
record_name.split(os.sep)[-1].replace("-", "_").replace(".edf", "")
328-
)
331+
record_name_out = _split_path(record_name)[1].replace("-", "_").replace(".edf", "")
329332
sample_rate = [int(i / block_duration) for i in samps_per_block]
330333
fs = functools.reduce(math.gcd, sample_rate)
331334
samps_per_frame = [int(s / min(samps_per_block)) for s in samps_per_block]
@@ -374,6 +377,7 @@ def read_edf(
374377
)
375378

376379
if header_only:
380+
edf_file.close()
377381
return {
378382
"fs": fs,
379383
"sig_len": sig_len,
@@ -386,7 +390,9 @@ def read_edf(
386390
}
387391

388392
sig_data = np.empty((sig_len, n_sig))
389-
temp_sig_data = np.fromfile(edf_file, dtype=np.int16)
393+
# Read the rest of the file, ignoring a final odd byte
394+
data = edf_file.read()
395+
temp_sig_data = np.frombuffer(data, dtype=np.int16, count=len(data) // 2)
390396
temp_sig_data = temp_sig_data.reshape((-1, sum(samps_per_block)))
391397
temp_all_sigs = np.hsplit(temp_sig_data, np.cumsum(samps_per_block)[:-1])
392398

@@ -578,7 +584,7 @@ def wfdb_to_edf(
578584
smooth_frames=False,
579585
channels=channels,
580586
)
581-
record_name_out = record_name.split(os.sep)[-1].replace("-", "_")
587+
record_name_out = _split_path(record_name)[1].replace("-", "_")
582588

583589
# Maximum data block length, in bytes
584590
edf_max_block = 61440
@@ -1000,7 +1006,10 @@ def rdedfann(
10001006
Parameters
10011007
----------
10021008
record_name : str
1003-
The name of the input EDF record to be read.
1009+
The path of the input EDF file to be read, including its
1010+
extension. This can also be a cloud URI, such as
1011+
'physionet://chbmit/1.0.0/chb01/chb01_01.edf' or 's3://...', which
1012+
is read without saving a copy of the file.
10041013
pn_dir : str, optional
10051014
Option used to stream data from Physionet. The Physionet
10061015
database directory from which to find the required record files.
@@ -1152,7 +1161,7 @@ def rdedfann(
11521161
)
11531162
df_out = format_ann_from_df(df_in)
11541163
# Remove extension from input file name
1155-
record_name = record_name.split(os.sep)[-1].split(".")[0]
1164+
record_name = _split_path(record_name)[1].split(".")[0]
11561165
extension = "atr"
11571166
fs = rec.fs
11581167
sample = (df_out["onset"].to_numpy() * fs).astype(np.int64)

‎src/wfdb/io/convert/wav.py‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import numpy as np
66

77
from wfdb.io import Record, download
8+
from wfdb.io._coreio import _open_input_file, _split_path
89
from wfdb.io._signal import _checksums, _digi_nan
910
from wfdb.io.record import rdrecord
1011

@@ -67,7 +68,7 @@ def wfdb_to_wav(
6768
physical=False,
6869
smooth_frames=True,
6970
)
70-
record_name_out = record_name.split(os.sep)[-1].replace("-", "_")
71+
record_name_out = _split_path(record_name)[1].replace("-", "_")
7172

7273
# Get information needed for the header and format chunks
7374
num_samps = record.sig_len
@@ -159,7 +160,10 @@ def read_wav(record_name, pn_dir=None, delete_file=True, record_only=False):
159160
Parameters
160161
----------
161162
record_name : str
162-
The name of the input .wav record to be read.
163+
The path of the input .wav file to be read, including its
164+
extension. This can also be a cloud URI, such as
165+
'physionet://<database>/<version>/<file>.wav' or 's3://...', which
166+
is read without saving a copy of the file.
163167
pn_dir : str, optional
164168
Option used to stream data from Physionet. The Physionet
165169
database directory from which to find the required record files.
@@ -232,16 +236,16 @@ def read_wav(record_name, pn_dir=None, delete_file=True, record_only=False):
232236
with download._open_pn_file(pn_dir, record_name) as f:
233237
open(record_name, "wb").write(f.read())
234238

235-
wave_file = open(record_name, mode="rb")
236-
record_name_out = (
237-
record_name.split(os.sep)[-1].replace("-", "_").replace(".wav", "")
238-
)
239+
wave_file = _open_input_file(record_name)
240+
file_size = wave_file.seek(0, os.SEEK_END)
241+
wave_file.seek(0)
242+
record_name_out = _split_path(record_name)[1].replace("-", "_").replace(".wav", "")
239243

240244
chunk_ID = "".join([s.decode() for s in struct.unpack(">4s", wave_file.read(4))])
241245
if chunk_ID != "RIFF":
242246
raise Exception(f"{record_name} is not a .wav-format file")
243247

244-
correct_chunk_size = os.path.getsize(record_name) - 8
248+
correct_chunk_size = file_size - 8
245249
chunk_size = struct.unpack("<I", wave_file.read(4))[0]
246250
if chunk_size != correct_chunk_size:
247251
raise Exception(
@@ -298,16 +302,20 @@ def read_wav(record_name, pn_dir=None, delete_file=True, record_only=False):
298302
if subchunk2_ID != "data":
299303
raise Exception("Format chunk missing or corrupt")
300304

301-
correct_subchunk2_size = os.path.getsize(record_name) - 44
305+
correct_subchunk2_size = file_size - 44
302306
subchunk2_size = struct.unpack("<I", wave_file.read(4))[0]
303307
if subchunk2_size != correct_subchunk2_size:
304308
raise Exception(
305309
f"Data chunk has incorrect length.. (is {subchunk2_size} should be {correct_subchunk2_size})"
306310
)
307311
sig_len = int(subchunk2_size / block_align)
308312

313+
data = wave_file.read()
314+
wave_file.close()
309315
sig_data = (
310-
np.fromfile(wave_file, dtype=np.int16).reshape((-1, num_channels))
316+
np.frombuffer(data, dtype=np.int16, count=len(data) // 2).reshape(
317+
(-1, num_channels)
318+
)
311319
/ (2 * adc_res)
312320
).astype(np.int16)
313321

‎tests/test_physionet_uri.py‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,3 +521,118 @@ def test_get_dbs_from_physionet():
521521
dbs = wfdb.get_dbs()
522522
assert ["mitdb", "MIT-BIH Arrhythmia Database"] in dbs
523523
assert len({slug for slug, title in dbs}) == len(dbs)
524+
525+
526+
@pytest.mark.parametrize("protocol", ["physionet", "memory"])
527+
def test_converters_read_uris(
528+
physionet_cache, offline, tmp_path, monkeypatch, protocol
529+
):
530+
"""read_edf, read_wav and rdedfann read URIs, without saving a copy."""
531+
from wfdb.io.convert.edf import rdedfann, read_edf
532+
from wfdb.io.convert.wav import read_wav
533+
534+
names = ["n16.edf", "SC4001E0-PSG.wav", "test_edfann.edf"]
535+
if protocol == "physionet":
536+
cache_sample_files(physionet_cache, "demo", names)
537+
base = "physionet://demo/1.0"
538+
else:
539+
memory = fsspec.filesystem("memory")
540+
for name in names:
541+
memory.pipe(f"/converters/{name}", (SAMPLE_DATA / name).read_bytes())
542+
base = "memory://converters"
543+
workdir = tmp_path / "workdir"
544+
workdir.mkdir()
545+
monkeypatch.chdir(workdir)
546+
local = Path(__file__).parent.parent / SAMPLE_DATA
547+
548+
edf = read_edf(f"{base}/n16.edf")
549+
wav = read_wav(f"{base}/SC4001E0-PSG.wav")
550+
ann = rdedfann(f"{base}/test_edfann.edf")
551+
552+
expected = read_edf(str(local / "n16.edf"))
553+
assert edf.record_name == expected.record_name == "n16"
554+
np.testing.assert_array_equal(edf.p_signal, expected.p_signal)
555+
expected = read_wav(str(local / "SC4001E0-PSG.wav"))
556+
assert wav.record_name == expected.record_name
557+
np.testing.assert_array_equal(wav.d_signal, expected.d_signal)
558+
assert ann == rdedfann(str(local / "test_edfann.edf"))
559+
assert list(workdir.iterdir()) == []
560+
if protocol == "memory":
561+
fsspec.filesystem("memory").rm("/converters", recursive=True)
562+
563+
564+
def test_record_converters_read_physionet_uris(
565+
physionet_cache, offline, tmp_path, monkeypatch
566+
):
567+
"""Functions that read a record with rdrecord also take physionet:// URIs."""
568+
from wfdb.io.convert.matlab import wfdb_to_mat
569+
from wfdb.processing import sigavg
570+
571+
cache_sample_files(physionet_cache, "demo", ["100.hea", "100.dat", "100.atr"])
572+
local = Path(__file__).parent.parent / SAMPLE_DATA / "100"
573+
workdir = tmp_path / "workdir"
574+
workdir.mkdir()
575+
monkeypatch.chdir(workdir)
576+
577+
wfdb_to_mat("physionet://demo/1.0/100", sampto=1000)
578+
averaged = sigavg("physionet://demo/1.0/100", "atr", stop_range=1, return_df=True)
579+
580+
assert sorted(p.name for p in workdir.iterdir()) == ["100m.hea", "100m.mat"]
581+
expected = sigavg(str(local), "atr", stop_range=1, return_df=True)
582+
assert averaged.equals(expected)
583+
584+
585+
class CountingFile:
586+
"""A file that counts the bytes read from it."""
587+
588+
def __init__(self, f, counts):
589+
self._f = f
590+
self._counts = counts
591+
592+
def read(self, *args):
593+
data = self._f.read(*args)
594+
self._counts.append(len(data))
595+
return data
596+
597+
def __getattr__(self, name):
598+
return getattr(self._f, name)
599+
600+
def __enter__(self):
601+
return self
602+
603+
def __exit__(self, *exc):
604+
self._f.close()
605+
606+
607+
@pytest.mark.parametrize("protocol", ["physionet", "memory"])
608+
def test_read_edf_header_only_reads_only_the_header(
609+
physionet_cache, offline, monkeypatch, protocol
610+
):
611+
"""A URI is read as needed, so header_only does not fetch the signals."""
612+
from wfdb.io.convert.edf import read_edf
613+
614+
if protocol == "physionet":
615+
cache_sample_files(physionet_cache, "demo", ["n16.edf"])
616+
uri = "physionet://demo/1.0/n16.edf"
617+
else:
618+
fsspec.filesystem("memory").pipe(
619+
"/header-only/n16.edf", (SAMPLE_DATA / "n16.edf").read_bytes()
620+
)
621+
uri = "memory://header-only/n16.edf"
622+
filesystem = type(fsspec.filesystem(protocol))
623+
real_open = filesystem._open
624+
counts = []
625+
monkeypatch.setattr(
626+
filesystem,
627+
"_open",
628+
lambda self, *args, **kwargs: CountingFile(
629+
real_open(self, *args, **kwargs), counts
630+
),
631+
)
632+
633+
header = read_edf(uri, header_only=True)
634+
635+
assert sum(counts) == 256 * (header["n_sig"] + 1)
636+
assert sum(counts) < (SAMPLE_DATA / "n16.edf").stat().st_size
637+
if protocol == "memory":
638+
fsspec.filesystem("memory").rm("/header-only", recursive=True)

0 commit comments

Comments
 (0)