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/converters-read-uris.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
**Read EDF and WAV files from physionet:// and other URIs**
``read_edf``, ``rdedfann`` and ``read_wav`` now take a cloud URI as
``record_name``, such as ``physionet://chbmit/1.0.0/chb01/chb01_01.edf``,
``s3://`` or ``memory://``, as ``rdrecord`` and ``rdann`` do, and read the
file without saving a copy. All of the functions that take ``pn_dir`` now
also take a ``physionet://`` URI. Output files written by ``wfdb_to_edf``
and ``wfdb_to_wav`` for a URI are named after the record, on every platform.
25 changes: 25 additions & 0 deletions src/wfdb/io/_coreio.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,31 @@ def _split_path(record_name):
return os.path.split(path)


def _open_input_file(path):
"""Open a local file, or a file at a cloud URI, to read in binary mode.
A file at a cloud URI, such as a `physionet://` URI, is read as it is
needed (for `physionet://`, with HTTP range requests), so that reading
only the start of a file does not fetch the rest. It can be sought and
sized like a local file.
Parameters
----------
path : str or os.PathLike
The path of a local file, or a cloud URI.
Returns
-------
file
The open file.
"""
path = os.fspath(path)
if any(path.startswith(proto) for proto in CLOUD_PROTOCOLS):
return _fsspec_open(path, "rb").open()
return open(path, "rb")


def _join_path(dir_name, file_name):
"""Join a local directory or cloud URI with a file name.
Expand Down
27 changes: 18 additions & 9 deletions src/wfdb/io/convert/edf.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import pandas as pd

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

# Open the desired file
edf_file = open(record_name, mode="rb")
edf_file = _open_input_file(record_name)

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

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

if header_only:
edf_file.close()
return {
"fs": fs,
"sig_len": sig_len,
Expand All @@ -386,7 +390,9 @@ def read_edf(
}

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

Expand Down Expand Up @@ -578,7 +584,7 @@ def wfdb_to_edf(
smooth_frames=False,
channels=channels,
)
record_name_out = record_name.split(os.sep)[-1].replace("-", "_")
record_name_out = _split_path(record_name)[1].replace("-", "_")

# Maximum data block length, in bytes
edf_max_block = 61440
Expand Down Expand Up @@ -1000,7 +1006,10 @@ def rdedfann(
Parameters
----------
record_name : str
The name of the input EDF record to be read.
The path of the input EDF file to be read, including its
extension. This can also be a cloud URI, such as
'physionet://chbmit/1.0.0/chb01/chb01_01.edf' or 's3://...', which
is read without saving a copy of the file.
pn_dir : str, optional
Option used to stream data from Physionet. The Physionet
database directory from which to find the required record files.
Expand Down Expand Up @@ -1152,7 +1161,7 @@ def rdedfann(
)
df_out = format_ann_from_df(df_in)
# Remove extension from input file name
record_name = record_name.split(os.sep)[-1].split(".")[0]
record_name = _split_path(record_name)[1].split(".")[0]
extension = "atr"
fs = rec.fs
sample = (df_out["onset"].to_numpy() * fs).astype(np.int64)
Expand Down
26 changes: 17 additions & 9 deletions src/wfdb/io/convert/wav.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import numpy as np

from wfdb.io import Record, download
from wfdb.io._coreio import _open_input_file, _split_path
from wfdb.io._signal import _checksums, _digi_nan
from wfdb.io.record import rdrecord

Expand Down Expand Up @@ -67,7 +68,7 @@ def wfdb_to_wav(
physical=False,
smooth_frames=True,
)
record_name_out = record_name.split(os.sep)[-1].replace("-", "_")
record_name_out = _split_path(record_name)[1].replace("-", "_")

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

wave_file = open(record_name, mode="rb")
record_name_out = (
record_name.split(os.sep)[-1].replace("-", "_").replace(".wav", "")
)
wave_file = _open_input_file(record_name)
file_size = wave_file.seek(0, os.SEEK_END)
wave_file.seek(0)
record_name_out = _split_path(record_name)[1].replace("-", "_").replace(".wav", "")

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

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

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

data = wave_file.read()
wave_file.close()
sig_data = (
np.fromfile(wave_file, dtype=np.int16).reshape((-1, num_channels))
np.frombuffer(data, dtype=np.int16, count=len(data) // 2).reshape(
(-1, num_channels)
)
/ (2 * adc_res)
).astype(np.int16)

Expand Down
115 changes: 115 additions & 0 deletions tests/test_physionet_uri.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,3 +521,118 @@ def test_get_dbs_from_physionet():
dbs = wfdb.get_dbs()
assert ["mitdb", "MIT-BIH Arrhythmia Database"] in dbs
assert len({slug for slug, title in dbs}) == len(dbs)


@pytest.mark.parametrize("protocol", ["physionet", "memory"])
def test_converters_read_uris(
physionet_cache, offline, tmp_path, monkeypatch, protocol
):
"""read_edf, read_wav and rdedfann read URIs, without saving a copy."""
from wfdb.io.convert.edf import rdedfann, read_edf
from wfdb.io.convert.wav import read_wav

names = ["n16.edf", "SC4001E0-PSG.wav", "test_edfann.edf"]
if protocol == "physionet":
cache_sample_files(physionet_cache, "demo", names)
base = "physionet://demo/1.0"
else:
memory = fsspec.filesystem("memory")
for name in names:
memory.pipe(f"/converters/{name}", (SAMPLE_DATA / name).read_bytes())
base = "memory://converters"
workdir = tmp_path / "workdir"
workdir.mkdir()
monkeypatch.chdir(workdir)
local = Path(__file__).parent.parent / SAMPLE_DATA

edf = read_edf(f"{base}/n16.edf")
wav = read_wav(f"{base}/SC4001E0-PSG.wav")
ann = rdedfann(f"{base}/test_edfann.edf")

expected = read_edf(str(local / "n16.edf"))
assert edf.record_name == expected.record_name == "n16"
np.testing.assert_array_equal(edf.p_signal, expected.p_signal)
expected = read_wav(str(local / "SC4001E0-PSG.wav"))
assert wav.record_name == expected.record_name
np.testing.assert_array_equal(wav.d_signal, expected.d_signal)
assert ann == rdedfann(str(local / "test_edfann.edf"))
assert list(workdir.iterdir()) == []
if protocol == "memory":
fsspec.filesystem("memory").rm("/converters", recursive=True)


def test_record_converters_read_physionet_uris(
physionet_cache, offline, tmp_path, monkeypatch
):
"""Functions that read a record with rdrecord also take physionet:// URIs."""
from wfdb.io.convert.matlab import wfdb_to_mat
from wfdb.processing import sigavg

cache_sample_files(physionet_cache, "demo", ["100.hea", "100.dat", "100.atr"])
local = Path(__file__).parent.parent / SAMPLE_DATA / "100"
workdir = tmp_path / "workdir"
workdir.mkdir()
monkeypatch.chdir(workdir)

wfdb_to_mat("physionet://demo/1.0/100", sampto=1000)
averaged = sigavg("physionet://demo/1.0/100", "atr", stop_range=1, return_df=True)

assert sorted(p.name for p in workdir.iterdir()) == ["100m.hea", "100m.mat"]
expected = sigavg(str(local), "atr", stop_range=1, return_df=True)
assert averaged.equals(expected)


class CountingFile:
"""A file that counts the bytes read from it."""

def __init__(self, f, counts):
self._f = f
self._counts = counts

def read(self, *args):
data = self._f.read(*args)
self._counts.append(len(data))
return data

def __getattr__(self, name):
return getattr(self._f, name)

def __enter__(self):
return self

def __exit__(self, *exc):
self._f.close()


@pytest.mark.parametrize("protocol", ["physionet", "memory"])
def test_read_edf_header_only_reads_only_the_header(
physionet_cache, offline, monkeypatch, protocol
):
"""A URI is read as needed, so header_only does not fetch the signals."""
from wfdb.io.convert.edf import read_edf

if protocol == "physionet":
cache_sample_files(physionet_cache, "demo", ["n16.edf"])
uri = "physionet://demo/1.0/n16.edf"
else:
fsspec.filesystem("memory").pipe(
"/header-only/n16.edf", (SAMPLE_DATA / "n16.edf").read_bytes()
)
uri = "memory://header-only/n16.edf"
filesystem = type(fsspec.filesystem(protocol))
real_open = filesystem._open
counts = []
monkeypatch.setattr(
filesystem,
"_open",
lambda self, *args, **kwargs: CountingFile(
real_open(self, *args, **kwargs), counts
),
)

header = read_edf(uri, header_only=True)

assert sum(counts) == 256 * (header["n_sig"] + 1)
assert sum(counts) < (SAMPLE_DATA / "n16.edf").stat().st_size
if protocol == "memory":
fsspec.filesystem("memory").rm("/header-only", recursive=True)
Loading