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
2 changes: 2 additions & 0 deletions changelog.d/wfdb-to-wav-channels-invalid.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
**Fix channels and invalid samples in wfdb_to_wav**
``wfdb_to_wav`` now writes only the signals selected with ``channels``, which it used to ignore. Invalid samples are written as -32768, the format 16 invalid value, so they are read back as missing. For a resolution below 12 bits, they used to overflow and become 0. The samples are now read as digital values, instead of being read as physical values and converted back.
25 changes: 14 additions & 11 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, _url, download
from wfdb.io._signal import _digi_nan
from wfdb.io.record import rdrecord


Expand Down Expand Up @@ -62,6 +63,8 @@ def wfdb_to_wav(
pn_dir=pn_dir,
sampfrom=sampfrom,
sampto=sampto,
channels=channels,
physical=False,
smooth_frames=True,
)
record_name_out = record_name.split(os.sep)[-1].replace("-", "_")
Expand All @@ -76,6 +79,16 @@ def wfdb_to_wav(
offset = record.adc_zero
shift = [(16 - v) for v in record.adc_res]

# Offset the samples by the ADC zero and shift them to fill 16 bits.
# Invalid samples are written as the format 16 invalid value, since
# shifting them could overflow.
samples = np.left_shift(record.d_signal.astype(np.int64) - offset, shift)
for ch, fmt in enumerate(record.fmt):
invalid = _digi_nan(fmt)
if invalid is not None:
samples[record.d_signal[:, ch] == invalid, ch] = _digi_nan("16")
sig_data = samples.astype(np.int16).reshape((1, -1))

# Start writing the file
if output_filename != "":
if not output_filename.endswith(".wav"):
Expand Down Expand Up @@ -109,17 +122,7 @@ def wfdb_to_wav(
f.write(struct.pack(">4s", b"data"))
# The number of bytes in the signal data chunk
f.write(struct.pack("<I", chunk_bytes))
# Write the signal data... the closest I can get to the original implementation
# Mismatched elements: 723881 / 15400000 (4.7%)
# Max absolute difference: 2
# Max relative difference: 0.00444444
# x: array([ -322, 3852, -9246, ..., 0, 0, 0], dtype=int16)
# y: array([ -322, 3852, -9246, ..., 0, 0, 0], dtype=int16)
sig_data = (
np.left_shift(np.subtract(record.adc(), offset), shift)
.reshape((1, -1))
.astype(np.int16)
)
# Write the multiplexed signal data
sig_data.tofile(f)

# If asked to write the accompanying header file
Expand Down
72 changes: 71 additions & 1 deletion tests/io/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from wfdb.io.convert import wfdb_to_wav
from wfdb.io.convert.csv import csv2ann, csv_to_wfdb
from wfdb.io.convert.edf import read_edf
from wfdb.io.record import rdheader, rdrecord
from wfdb.io.record import rdheader, rdrecord, wrsamp


class TestEdfToWfdb:
Expand Down Expand Up @@ -362,3 +362,73 @@ def test_write_header(self, tmp_path, monkeypatch, record_name):
expected = rdrecord(record_path)
assert record.samps_per_frame == [1] * expected.n_sig
np.testing.assert_array_equal(record.p_signal, expected.p_signal)

@staticmethod
def read_wav(wav_file, n_sig):
"""Read the samples of a .wav file as an array with one column per signal."""
with wave.open(wav_file, "rb") as wav:
assert wav.getnchannels() == n_sig
frames = wav.readframes(wav.getnframes())
return np.frombuffer(frames, dtype="<i2").reshape((-1, n_sig))

@staticmethod
def expected_samples(record):
"""Shift the digital samples of a record to fill 16 bits."""
shift = np.array([16 - res for res in record.adc_res])
return (record.d_signal - record.adc_zero) << shift

def test_sampfrom_sampto(self, tmp_path, monkeypatch):
"""Only the samples from sampfrom to sampto are written."""
record_path = os.path.abspath("sample-data/100")
monkeypatch.chdir(tmp_path)
wfdb_to_wav(record_path, sampfrom=100, sampto=600, write_header=True)

record = rdrecord(record_path, sampfrom=100, sampto=600, physical=False)
expected = self.expected_samples(record)
np.testing.assert_array_equal(self.read_wav("100.wav", 2), expected)
assert rdheader("100").init_value == expected[0].tolist()

def test_channels(self, tmp_path):
"""Only the selected channels are written."""
wav_file = str(tmp_path / "out.wav")
wfdb_to_wav("sample-data/100", channels=[1], output_filename=wav_file)

record = rdrecord("sample-data/100", channels=[1], physical=False)
expected = self.expected_samples(record)
np.testing.assert_array_equal(self.read_wav(wav_file, 1), expected)

@pytest.mark.parametrize("adc_res", [11, 12])
def test_invalid_samples(self, tmp_path, monkeypatch, adc_res):
"""Invalid samples are written as -32768, the format 16 invalid value."""
monkeypatch.chdir(tmp_path)
d_signal = np.array([[100], [-2048], [-200]])
wrsamp(
"invalid",
fs=100,
units=["mV"],
sig_name=["x"],
d_signal=d_signal,
fmt=["212"],
adc_gain=[200],
baseline=[0],
)
header = rdheader("invalid")
header.adc_res = [adc_res]
header.wrheader()

# Write the .wav file and its header in a separate directory
record_path = str(tmp_path / "invalid")
(tmp_path / "out").mkdir()
monkeypatch.chdir(tmp_path / "out")
wfdb_to_wav(record_path, write_header=True)

# -2048 is the format 212 invalid value
shift = 16 - adc_res
expected = [[100 << shift], [-32768], [-200 << shift]]
np.testing.assert_array_equal(self.read_wav("invalid.wav", 1), expected)

# Read back as missing
record = rdrecord("invalid")
expected = rdrecord(record_path)
np.testing.assert_array_equal(record.p_signal, expected.p_signal)
assert np.isnan(record.p_signal[1, 0])