Skip to content
Closed
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-mat-fixes.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
**Fix wfdb_to_mat encoding, slicing, and header metadata**
``wfdb_to_mat`` now passes ``channels`` to ``rdrecord``, computes output length from the sliced record, writes 8-bit (offset binary) and 32-bit MAT-files with proper data types and 8-byte MAT v5 padding, preserves missing samples without overflow, clears already-applied channel skew, handles unset ``adc_res``/``adc_zero`` fields, updates header checksums, and handles forward-slash record paths cross-platform.
73 changes: 50 additions & 23 deletions src/wfdb/io/convert/matlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import numpy as np

from wfdb.io._signal import _digi_nan
from wfdb.io.record import rdrecord


Expand Down Expand Up @@ -91,8 +92,21 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None
The output file name is 100m.mat and 100m.hea

"""
record = rdrecord(record_name, pn_dir=pn_dir, sampfrom=sampfrom, sampto=sampto)
record_name_out = record_name.split(os.sep)[-1].replace("-", "_") + "m"
record = rdrecord(
record_name,
pn_dir=pn_dir,
sampfrom=sampfrom,
sampto=sampto,
channels=channels,
physical=False,
)
record_name_out = os.path.basename(os.fspath(record_name)).replace("-", "_") + "m"

adc_res = [r if r is not None else 0 for r in record.adc_res]
adc_zero = [z if z is not None else 0 for z in record.adc_zero]
baseline = [
b if b is not None else adc_zero[i] for i, b in enumerate(record.baseline)
]

# Some variables describing the format of the .mat file
field_version = 256 # 0x0100 or 256
Expand All @@ -107,16 +121,16 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None
# are needed per sample
bytes_per_element = 1
for i in range(record.n_sig):
if record.adc_res[i] > 0:
if record.adc_res[i] > 16:
if adc_res[i] > 0:
if adc_res[i] > 16:
bytes_per_element = 4
elif (record.adc_res[i] > 8) and (bytes_per_element < 2):
elif (adc_res[i] > 8) and (bytes_per_element < 2):
bytes_per_element = 2
else:
# adc_res not specified.. try to guess from format
if (record.fmt[i] == "24") or (record.fmt[i] == "32"):
if record.fmt[i] in ("24", "32", "524"):
bytes_per_element = 4
elif (record.fmt[i] != "80") and (bytes_per_element < 2):
elif (record.fmt[i] not in ("80", "508")) and (bytes_per_element < 2):
bytes_per_element = 2

if bytes_per_element == 1:
Expand All @@ -140,9 +154,7 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None

# Ensure the signal size does not exceed the 2^31 byte limit
max_length = int((2**31) / bytes_per_element / record.n_sig)
if sampto is None:
sampto = record.p_signal.shape[0]
desired_length = sampto - sampfrom
desired_length = record.sig_len
# Snip record
if desired_length > max_length:
raise Exception("Can't write .mat file: data size exceeds 2GB limit")
Expand Down Expand Up @@ -220,14 +232,21 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None
# + 56 byte subelements (48 byte default + 8 byte name)
# = 192

# Copy the selected data into the .mat file
out_data = record.p_signal * record.adc_gain + record.baseline - record.adc_zero
# Cast the data to the correct type base on the bytes_per_element
out_data = np.around(out_data).astype(out_type)
# out_data should be [r1c1, r1c2, r2c1, r2c2, etc.]
out_data = out_data.flatten()
out_fmt = "<%sh" % len(out_data)
f.write(struct.pack(out_fmt, *out_data))
# Copy the selected data into the .mat file, preserving missing samples
shifted_data = record.d_signal.astype(np.int64) - np.asarray(
adc_zero, dtype=np.int64
)
out_nan = _digi_nan(wfdb_type)
for i, fmt in enumerate(record.fmt):
orig_nan = _digi_nan(fmt)
if orig_nan is not None:
shifted_data[record.d_signal[:, i] == orig_nan, i] = out_nan
# Cast the data to the correct type based on bytes_per_element
# out_data is C-contiguous: [r1c1, r1c2, r2c1, r2c2, etc.]
out_data = np.ascontiguousarray(shifted_data + offset, dtype=out_type)
f.write(out_data.tobytes())
if bytes_remain:
f.write(b"\x00" * (8 - bytes_remain))

# Display some useful information
if record.base_time is None:
Expand All @@ -254,23 +273,31 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None
print(
"{:<7}{:<20}{:<17}{:<10}{:<10}".format("Row", "Signal", "Gain", "Base", "Units")
)
record.sig_name = [s.replace(" ", "_") for s in record.sig_name]
record.sig_name = [
s.replace(" ", "_") if s is not None else None for s in record.sig_name
]
for i in range(record.n_sig):
sig_name = record.sig_name[i] if record.sig_name[i] is not None else ""
unit = record.units[i] if record.units[i] is not None else ""
print(
f"{i:<7}{record.sig_name[i]:<20}{record.adc_gain[i]:<17}{record.baseline[i] - record.adc_zero[i] + offset:<10}{record.units[i]:<10}"
f"{i:<7}{sig_name:<20}{record.adc_gain[i]:<17}{baseline[i] - adc_zero[i] + offset:<10}{unit:<10}"
)

# Modify the record file to reflect the new data
num_channels = record.n_sig if (channels is None) else len(channels)
num_channels = record.n_sig
record.record_name = record_name_out
record.n_sig = num_channels
record.samps_per_frame = num_channels * [1]
record.skew = None
record.file_name = num_channels * [output_file]
record.fmt = num_channels * [wfdb_type]
record.byte_offset = num_channels * [192]
record.baseline = [b - record.adc_zero[i] for i, b in enumerate(record.baseline)]
record.adc_res = adc_res
record.baseline = [baseline[i] - adc_zero[i] for i in range(num_channels)]
record.adc_zero = num_channels * [0]
record.init_value = out_data[: record.n_sig].tolist()
record.block_size = num_channels * [0]
record.init_value = shifted_data[0].tolist()
record.checksum = [int(c) for c in np.sum(shifted_data, axis=0) % 65536]

# Write the header file RECm.hea
record.wrheader()
Expand Down
131 changes: 130 additions & 1 deletion tests/io/test_convert.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import os
from pathlib import Path

import numpy as np
import pytest
from scipy.io import loadmat

from wfdb.io.annotation import rdann
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.convert.matlab import wfdb_to_mat
from wfdb.io.record import rdheader, rdrecord, wrsamp


class TestEdfToWfdb:
Expand Down Expand Up @@ -322,3 +325,129 @@ def test_record_name_with_dots(self, tmp_path, monkeypatch):
out_dir.mkdir()
csv2ann(str(data_dir / "x.csv"), fs=100, write_dir=str(out_dir))
assert (out_dir / "x.atr").exists()


class TestWfdbToMat:
"""Tests for the io.convert.matlab module."""

SAMPLE_DATA = Path(__file__).resolve().parents[2] / "sample-data"

def test_basic_roundtrip_and_padding(self, tmp_path, monkeypatch):
"""16-bit MAT-file output pads to 8-byte boundary and round-trips cleanly."""
monkeypatch.chdir(tmp_path)
src = str(self.SAMPLE_DATA / "100")

# 2 channels * 5 samples * 2 bytes = 20 bytes (requires 4 bytes padding)
wfdb_to_mat(src, sampto=5)

mat_path = tmp_path / "100m.mat"
assert mat_path.stat().st_size == 192 + 24

mat_val = loadmat(mat_path)["val"]
orig_d = rdrecord(src, sampto=5, physical=False)
orig_p = rdrecord(src, sampto=5)
expected_val = (orig_d.d_signal - np.asarray(orig_d.adc_zero)).T
assert mat_val.dtype == np.int16
np.testing.assert_array_equal(mat_val, expected_val)

reloaded = rdrecord(str(tmp_path / "100m"))
reloaded_d = rdrecord(str(tmp_path / "100m"), physical=False)
np.testing.assert_allclose(reloaded.p_signal, orig_p.p_signal)
assert reloaded.checksum == reloaded_d.calc_checksum()

def test_channels_and_sampfrom_slice(self, tmp_path, monkeypatch):
"""channels selection and sampfrom without sampto produce valid output."""
monkeypatch.chdir(tmp_path)
sig = np.arange(40, dtype=np.int16).reshape(20, 2)
wrsamp(
"tiny",
fs=100,
units=["mV", "mV"],
sig_name=["I", "II"],
d_signal=sig,
fmt=["16", "16"],
adc_gain=[100, 200],
baseline=[0, 0],
write_dir=str(tmp_path),
)

# sampfrom > sig_len / 2 used to make desired_length negative
wfdb_to_mat(str(tmp_path / "tiny"), sampfrom=12, channels=[1])

mat_val = loadmat(tmp_path / "tinym.mat")["val"]
assert mat_val.shape == (1, 8)
np.testing.assert_array_equal(mat_val[0], sig[12:, 1])

reloaded = rdrecord(str(tmp_path / "tinym"))
orig = rdrecord(str(tmp_path / "tiny"), sampfrom=12, channels=[1])
assert reloaded.n_sig == 1
assert reloaded.sig_name == ["II"]
np.testing.assert_allclose(reloaded.p_signal, orig.p_signal)

def test_format_80_uint8(self, tmp_path, monkeypatch):
"""8-bit (format 80) records write offset-binary uint8 MAT-files."""
monkeypatch.chdir(tmp_path)
src = str(self.SAMPLE_DATA / "binformats")

wfdb_to_mat(src, sampto=10, channels=[3])

mat_val = loadmat(tmp_path / "binformatsm.mat")["val"]
orig_d = rdrecord(src, sampto=10, channels=[3], physical=False)
orig_p = rdrecord(src, sampto=10, channels=[3])
assert mat_val.dtype == np.uint8
np.testing.assert_array_equal(mat_val, (orig_d.d_signal + 128).T)

reloaded = rdrecord(str(tmp_path / "binformatsm"))
reloaded_d = rdrecord(str(tmp_path / "binformatsm"), physical=False)
assert reloaded.fmt == ["80"]
np.testing.assert_allclose(reloaded.p_signal, orig_p.p_signal)
assert reloaded.checksum == reloaded_d.calc_checksum()

def test_format_32_int32_and_missing_adc_fields(self, tmp_path, monkeypatch):
"""24/32-bit records and headers with unset adc_res/adc_zero write int32."""
monkeypatch.chdir(tmp_path)
src = str(self.SAMPLE_DATA / "n8_evoked_raw_95_F1_R9")

wfdb_to_mat(src, sampto=10)

mat_val = loadmat(tmp_path / "n8_evoked_raw_95_F1_R9m.mat")["val"]
orig_d = rdrecord(src, sampto=10, physical=False)
orig_p = rdrecord(src, sampto=10)
assert mat_val.dtype == np.int32
np.testing.assert_array_equal(mat_val, orig_d.d_signal.T)

reloaded = rdrecord(str(tmp_path / "n8_evoked_raw_95_F1_R9m"))
reloaded_d = rdrecord(str(tmp_path / "n8_evoked_raw_95_F1_R9m"), physical=False)
assert reloaded.fmt == ["32", "32"]
np.testing.assert_allclose(reloaded.p_signal, orig_p.p_signal)
assert reloaded.checksum == reloaded_d.calc_checksum()

def test_missing_samples_and_skew_preserved(self, tmp_path, monkeypatch):
"""Missing samples are preserved without overflow and skew is not doubled."""
monkeypatch.chdir(tmp_path)

# Missing samples with non-zero adc_zero (format 516)
mixed_src = str(self.SAMPLE_DATA / "mixedsignals")
wfdb_to_mat(mixed_src, sampto=20)
mixed_orig = rdrecord(mixed_src, sampto=20)
mixed_reloaded = rdrecord(str(tmp_path / "mixedsignalsm"))
np.testing.assert_allclose(
mixed_reloaded.p_signal, mixed_orig.p_signal, equal_nan=True
)

# Skewed record should not be skewed a second time when read back
skew_src = str(self.SAMPLE_DATA / "100skew")
wfdb_to_mat(skew_src, sampto=20)
skew_orig = rdrecord(skew_src, sampto=20)
skew_reloaded = rdrecord(str(tmp_path / "100skewm"))
np.testing.assert_allclose(skew_reloaded.p_signal, skew_orig.p_signal)

def test_forward_slash_path(self, tmp_path, monkeypatch):
"""Forward-slash record paths work cross-platform and write into cwd."""
monkeypatch.chdir(tmp_path)
src = (self.SAMPLE_DATA / "100").as_posix()

wfdb_to_mat(src, sampto=8)

assert (tmp_path / "100m.mat").exists()
assert (tmp_path / "100m.hea").exists()