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("