From 5fc2e5eb063f8bbc1e653eda5dd497113665ecb9 Mon Sep 17 00:00:00 2001 From: "Goktug Ozkan, MD" <232098340+goktugozkanmd@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:07:10 +0300 Subject: [PATCH 1/3] Tidy up wfdb_to_mat and its tests Follow-ups from the review of #633, tracked in #642. No behaviour change: the checksum helper is the same expression the inline code used. - Drop the no-op `record.n_sig = num_channels` assignment and the `num_channels` alias, and read `record.sig_len` directly instead of copying it into `desired_length`. - Share the WFDB checksum through `_signal._checksum`, so the header checksum in `wfdb_to_mat` and `calc_checksum` cannot drift apart. - Split `test_missing_samples_and_skew_preserved` into two tests, so a failure in the first part no longer hides the skew check. - Note in `test_forward_slash_path` that it only guards Windows paths. Closes #642. Tests: 397 passed, 3 skipped (`pytest -q`, Windows, CPython 3.12); `ruff check src tests` clean. The 3 skips are the POSIX-permission and network-dependent tests that skip on this machine regardless of the patch. --- src/wfdb/io/_signal.py | 25 ++++++++++++++++++++++--- src/wfdb/io/convert/matlab.py | 31 ++++++++++++++----------------- tests/io/test_convert.py | 11 ++++++++--- 3 files changed, 44 insertions(+), 23 deletions(-) diff --git a/src/wfdb/io/_signal.py b/src/wfdb/io/_signal.py index c7a1f3a2..4cef4b24 100644 --- a/src/wfdb/io/_signal.py +++ b/src/wfdb/io/_signal.py @@ -11,6 +11,26 @@ MAX_I32 = 2147483647 MIN_I32 = -2147483648 +CHECKSUM_MODULUS = 65536 + + +def _checksum(values): + """Return the WFDB checksum of one channel of digital samples. + + Parameters + ---------- + values : array_like + The digital samples of a single channel. + + Returns + ------- + int + The sum of the samples modulo 65536. + + """ + return int(np.sum(values) % CHECKSUM_MODULUS) + + # Formats in which all samples align with integer (power-of-two) boundaries ALIGNED_FMTS = ["8", "16", "32", "61", "80", "160"] # Formats in which not all samples align with integer boundaries @@ -940,10 +960,9 @@ def calc_checksum(self, expanded=False): """ if expanded: - cs = [int(np.sum(s) % 65536) for s in self.e_d_signal] + cs = [_checksum(s) for s in self.e_d_signal] else: - cs = np.sum(self.d_signal, 0) % 65536 - cs = [int(c) for c in cs] + cs = [_checksum(s) for s in self.d_signal.T] return cs def wr_dat_files(self, expanded=False, write_dir="", wfdb_archive=None): diff --git a/src/wfdb/io/convert/matlab.py b/src/wfdb/io/convert/matlab.py index 717c3ebd..6d2e7f83 100644 --- a/src/wfdb/io/convert/matlab.py +++ b/src/wfdb/io/convert/matlab.py @@ -4,7 +4,7 @@ import numpy as np -from wfdb.io._signal import _digi_nan +from wfdb.io._signal import _checksum, _digi_nan from wfdb.io.record import rdrecord @@ -185,13 +185,12 @@ 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) - desired_length = record.sig_len # Snip record - if desired_length > max_length: + if record.sig_len > max_length: raise Exception("Can't write .mat file: data size exceeds 2GB limit") # Bytes of actual data - bytes_of_data = bytes_per_element * record.n_sig * desired_length + bytes_of_data = bytes_per_element * record.n_sig * record.sig_len # This is the remaining number of bytes that don't fit into integer # multiple of 8: i.e. if 18 bytes, bytes_remain = 2, from 17 to 18 bytes_remain = bytes_of_data % 8 @@ -241,7 +240,7 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None # Number of signals (4 bytes) f.write(struct.pack(" Date: Sun, 22 Nov 2026 09:40:28 +0300 Subject: [PATCH 2/3] Use vectorized _checksums helper across converters and add unit tests --- src/wfdb/io/_signal.py | 54 +++++++++++++++++++++++------------ src/wfdb/io/convert/edf.py | 5 ++-- src/wfdb/io/convert/matlab.py | 4 +-- src/wfdb/io/convert/wav.py | 6 ++-- src/wfdb/io/record.py | 5 +++- tests/io/test_convert.py | 4 +-- tests/test_record.py | 48 +++++++++++++++++++++++++++++++ 7 files changed, 95 insertions(+), 31 deletions(-) diff --git a/src/wfdb/io/_signal.py b/src/wfdb/io/_signal.py index 4cef4b24..af7f1421 100644 --- a/src/wfdb/io/_signal.py +++ b/src/wfdb/io/_signal.py @@ -13,24 +13,6 @@ CHECKSUM_MODULUS = 65536 - -def _checksum(values): - """Return the WFDB checksum of one channel of digital samples. - - Parameters - ---------- - values : array_like - The digital samples of a single channel. - - Returns - ------- - int - The sum of the samples modulo 65536. - - """ - return int(np.sum(values) % CHECKSUM_MODULUS) - - # Formats in which all samples align with integer (power-of-two) boundaries ALIGNED_FMTS = ["8", "16", "32", "61", "80", "160"] # Formats in which not all samples align with integer boundaries @@ -131,6 +113,40 @@ def _checksum(values): } +def _checksum(values): + """Return the WFDB checksum of one channel of digital samples. + + Parameters + ---------- + values : array_like + The digital samples of a single channel. + + Returns + ------- + int + The sum of the samples modulo 65536. + + """ + return int(np.sum(values) % CHECKSUM_MODULUS) + + +def _checksums(signal): + """Return the WFDB checksum of each channel (column) of a 2-D signal array. + + Parameters + ---------- + signal : ndarray + A 2-D array of digital samples with one column per channel. + + Returns + ------- + list of int + The sum of each column modulo 65536. + + """ + return [int(c) for c in np.sum(signal, axis=0) % CHECKSUM_MODULUS] + + class SignalMixin: """Mixin class with signal methods. Inherited by Record class. @@ -962,7 +978,7 @@ def calc_checksum(self, expanded=False): if expanded: cs = [_checksum(s) for s in self.e_d_signal] else: - cs = [_checksum(s) for s in self.d_signal.T] + cs = _checksums(self.d_signal) return cs def wr_dat_files(self, expanded=False, write_dir="", wfdb_archive=None): diff --git a/src/wfdb/io/convert/edf.py b/src/wfdb/io/convert/edf.py index 3be6ae04..5e74366c 100644 --- a/src/wfdb/io/convert/edf.py +++ b/src/wfdb/io/convert/edf.py @@ -9,6 +9,7 @@ import pandas as pd from wfdb.io import download +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 @@ -424,9 +425,7 @@ def read_edf( # [ -5.004123, 43.546991, -99.481966, 51.64255 , -43.079939],... init_value = [int(s[0, 0]) for s in temp_all_sigs] - checksum = [ - int(np.sum(v) % 65536) for v in np.transpose(sig_data) - ] # not all values correct? + checksum = _checksums(sig_data) # not all values correct? edf_file.close() diff --git a/src/wfdb/io/convert/matlab.py b/src/wfdb/io/convert/matlab.py index 6d2e7f83..d365a8d3 100644 --- a/src/wfdb/io/convert/matlab.py +++ b/src/wfdb/io/convert/matlab.py @@ -4,7 +4,7 @@ import numpy as np -from wfdb.io._signal import _checksum, _digi_nan +from wfdb.io._signal import _checksums, _digi_nan from wfdb.io.record import rdrecord @@ -322,7 +322,7 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None record.adc_zero = record.n_sig * [0] record.block_size = record.n_sig * [0] record.init_value = shifted_data[0].tolist() - record.checksum = [_checksum(s) for s in shifted_data.T] + record.checksum = _checksums(shifted_data) # Write the header file RECm.hea record.wrheader() diff --git a/src/wfdb/io/convert/wav.py b/src/wfdb/io/convert/wav.py index fa057b39..de704d8f 100644 --- a/src/wfdb/io/convert/wav.py +++ b/src/wfdb/io/convert/wav.py @@ -5,7 +5,7 @@ import numpy as np from wfdb.io import Record, download -from wfdb.io._signal import _digi_nan +from wfdb.io._signal import _checksums, _digi_nan from wfdb.io.record import rdrecord @@ -312,9 +312,7 @@ def read_wav(record_name, pn_dir=None, delete_file=True, record_only=False): ).astype(np.int16) init_value = [int(s[0]) for s in np.transpose(sig_data)] - checksum = [ - int(np.sum(v) % 65536) for v in np.transpose(sig_data) - ] # not all values correct? + checksum = _checksums(sig_data) # not all values correct? if pn_dir is not None and delete_file: os.remove(record_name) diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index a9737d38..9d0768ca 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -936,7 +936,10 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): if self.checksum is not None and has_signal_files: checksums = self.calc_checksum(expanded=expanded) for ch, old_val in enumerate(self.checksum): - if old_val is None or (checksums[ch] - old_val) % 65536 == 0: + if ( + old_val is None + or (checksums[ch] - old_val) % _signal.CHECKSUM_MODULUS == 0 + ): checksums[ch] = old_val self.checksum = checksums diff --git a/tests/io/test_convert.py b/tests/io/test_convert.py index a2332115..f9708d40 100644 --- a/tests/io/test_convert.py +++ b/tests/io/test_convert.py @@ -674,8 +674,8 @@ def test_skew_not_applied_twice(self, tmp_path, monkeypatch): def test_forward_slash_path(self, tmp_path, monkeypatch): """Forward-slash record paths work cross-platform and write into cwd.""" monkeypatch.chdir(tmp_path) - # Only meaningful on Windows: elsewhere the old code handled this - # path already, so keep the test to guard the basename handling. + # The bug this guards against only appeared on Windows; on other + # platforms this checks that the basename is still used. src = (self.SAMPLE_DATA / "100").as_posix() wfdb_to_mat(src, sampto=8) diff --git a/tests/test_record.py b/tests/test_record.py index 481abbb9..0551b546 100644 --- a/tests/test_record.py +++ b/tests/test_record.py @@ -1828,3 +1828,51 @@ def test_expanded(self, fmt, tmp_path): written = (tmp_path / "x.dat").read_bytes() assert written == _pack_reference(fmt, [1, -2, 5, 3, -4, -6]) + + +class TestChecksumHelpers: + """Direct tests for the WFDB checksum helpers.""" + + @pytest.mark.parametrize( + ("values", "expected"), + [ + ([], 0), + ([0], 0), + ([100, -25, 5], 80), + ([30000, 30000, 10000], 4464), + ([-1], 65535), + ([-70000, -1], 61071), + ], + ) + def test_checksum_single_channel(self, values, expected): + """Wrap-around, negative sums, and empty channels return a Python int.""" + result = wfdb.io._signal._checksum(np.array(values, dtype=np.int64)) + assert type(result) is int + assert result == expected + + @pytest.mark.parametrize("dtype", [np.int8, np.int16, np.int32, np.int64]) + def test_checksums_2d_and_dtypes(self, dtype): + """Vectorized per-channel checksums match _checksum across integer dtypes.""" + rows = 1000 + signal = np.column_stack( + [ + np.full(rows, 100, dtype=dtype), + np.full(rows, -100, dtype=dtype), + np.zeros(rows, dtype=dtype), + ] + ) + result = wfdb.io._signal._checksums(signal) + expected = [wfdb.io._signal._checksum(col) for col in signal.T] + assert result == expected + assert all(type(c) is int for c in result) + assert result == [34464, 31072, 0] + + def test_checksums_empty_signal(self): + """A 2-D signal with zero samples produces zero checksums per channel.""" + signal = np.empty((0, 3), dtype=np.int16) + assert wfdb.io._signal._checksums(signal) == [0, 0, 0] + + def test_checksums_rejects_1d(self): + """A 1-D array raises TypeError rather than returning per-sample values.""" + with pytest.raises(TypeError): + wfdb.io._signal._checksums(np.arange(10, dtype=np.int16)) From 530375c19b6034be78e46be244e4b84378dfc16a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=B6ktu=C4=9F=20=C3=96zkan=2C=20MD?= <232098340+goktugozkanmd@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:02:38 +0300 Subject: [PATCH 3/3] Delegate _checksums to _checksum per column to preserve float parity --- src/wfdb/io/_signal.py | 2 +- tests/test_record.py | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/wfdb/io/_signal.py b/src/wfdb/io/_signal.py index af7f1421..409bd003 100644 --- a/src/wfdb/io/_signal.py +++ b/src/wfdb/io/_signal.py @@ -144,7 +144,7 @@ def _checksums(signal): The sum of each column modulo 65536. """ - return [int(c) for c in np.sum(signal, axis=0) % CHECKSUM_MODULUS] + return [_checksum(channel) for channel in np.transpose(signal)] class SignalMixin: diff --git a/tests/test_record.py b/tests/test_record.py index 0551b546..a77f7f64 100644 --- a/tests/test_record.py +++ b/tests/test_record.py @@ -1852,7 +1852,7 @@ def test_checksum_single_channel(self, values, expected): @pytest.mark.parametrize("dtype", [np.int8, np.int16, np.int32, np.int64]) def test_checksums_2d_and_dtypes(self, dtype): - """Vectorized per-channel checksums match _checksum across integer dtypes.""" + """Per-channel checksums match _checksum across integer dtypes.""" rows = 1000 signal = np.column_stack( [ @@ -1872,7 +1872,8 @@ def test_checksums_empty_signal(self): signal = np.empty((0, 3), dtype=np.int16) assert wfdb.io._signal._checksums(signal) == [0, 0, 0] - def test_checksums_rejects_1d(self): - """A 1-D array raises TypeError rather than returning per-sample values.""" - with pytest.raises(TypeError): - wfdb.io._signal._checksums(np.arange(10, dtype=np.int16)) + def test_checksums_float_matches_per_channel_sum(self): + """Float signals sum each column individually, preserving read_edf parity.""" + signal = np.array([[0.1, 0.0]] * 10) + expected = [int(np.sum(col) % 65536) for col in np.transpose(signal)] + assert wfdb.io._signal._checksums(signal) == expected