From d5aa8e50fd29831920530fef2ecbf657585f31ce Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sat, 21 Nov 2026 15:11:57 -0500 Subject: [PATCH] Fix channels and invalid samples in wfdb_to_wav Read the digital samples directly instead of reading physical values and converting them back with adc(), and pass channels to rdrecord, which was ignored. Write invalid samples as the format 16 invalid value: shifting them overflowed to 0 for resolutions below 12 bits. Add tests for sampfrom and sampto, channels, and invalid samples. Fixes #637 Fixes #638 Fixes #639 Fixes #640 --- changelog.d/wfdb-to-wav-channels-invalid.rst | 2 + src/wfdb/io/convert/wav.py | 25 ++++--- tests/io/test_convert.py | 72 +++++++++++++++++++- 3 files changed, 87 insertions(+), 12 deletions(-) create mode 100644 changelog.d/wfdb-to-wav-channels-invalid.rst diff --git a/changelog.d/wfdb-to-wav-channels-invalid.rst b/changelog.d/wfdb-to-wav-channels-invalid.rst new file mode 100644 index 00000000..222cf236 --- /dev/null +++ b/changelog.d/wfdb-to-wav-channels-invalid.rst @@ -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. diff --git a/src/wfdb/io/convert/wav.py b/src/wfdb/io/convert/wav.py index 7bfc065f..50b83f82 100644 --- a/src/wfdb/io/convert/wav.py +++ b/src/wfdb/io/convert/wav.py @@ -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 @@ -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("-", "_") @@ -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"): @@ -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("