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
41 changes: 38 additions & 3 deletions src/wfdb/io/_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
MAX_I32 = 2147483647
MIN_I32 = -2147483648

CHECKSUM_MODULUS = 65536

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: the new function now sits between MIN_I32 and the format constants below (ALIGNED_FMTS and so on). Keeping CHECKSUM_MODULUS with the other constants and moving _checksum after them would keep the constants together.


# 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
Expand Down Expand Up @@ -111,6 +113,40 @@
}


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 [_checksum(channel) for channel in np.transpose(signal)]


class SignalMixin:
"""Mixin class with signal methods. Inherited by Record class.

Expand Down Expand Up @@ -940,10 +976,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 = _checksums(self.d_signal)
return cs

def wr_dat_files(self, expanded=False, write_dir="", wfdb_archive=None):
Expand Down
5 changes: 2 additions & 3 deletions src/wfdb/io/convert/edf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()

Expand Down
31 changes: 14 additions & 17 deletions src/wfdb/io/convert/matlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import numpy as np

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


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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("<I", record.n_sig))
# Number of rows (4 bytes)
f.write(struct.pack("<I", desired_length))
f.write(struct.pack("<I", record.sig_len))

# Subelement 3: Array name
# Subtag 3: data type (4 bytes)
Expand Down Expand Up @@ -293,9 +292,9 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None

print(f"Source: record {record_name}\t\tStart: {datetime_string}")
print(
f"val has {record.n_sig} rows (signals) and {desired_length} columns (samples/signal)"
f"val has {record.n_sig} rows (signals) and {record.sig_len} columns (samples/signal)"
)
duration_string = str(datetime.timedelta(seconds=desired_length / record.fs))
duration_string = str(datetime.timedelta(seconds=record.sig_len / record.fs))
print(f"Duration: {duration_string}")
print(f"Sampling frequency: {record.fs} Hz\tSampling interval: {1 / record.fs} sec")
print(
Expand All @@ -312,20 +311,18 @@ def wfdb_to_mat(record_name, pn_dir=None, sampfrom=0, sampto=None, channels=None
)

# Modify the record file to reflect the new data
num_channels = record.n_sig
record.record_name = record_name_out
record.n_sig = num_channels
record.samps_per_frame = num_channels * [1]
record.samps_per_frame = record.n_sig * [1]
record.skew = None
record.file_name = num_channels * [output_file]
record.fmt = num_channels * [wfdb_type]
record.byte_offset = num_channels * [192]
record.file_name = record.n_sig * [output_file]
record.fmt = record.n_sig * [wfdb_type]
record.byte_offset = record.n_sig * [192]
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.block_size = num_channels * [0]
record.baseline = [baseline[i] - adc_zero[i] for i in range(record.n_sig)]
record.adc_zero = record.n_sig * [0]
record.block_size = record.n_sig * [0]
record.init_value = shifted_data[0].tolist()
record.checksum = [int(c) for c in np.sum(shifted_data, axis=0) % 65536]
record.checksum = _checksums(shifted_data)

# Write the header file RECm.hea
record.wrheader()
Expand Down
6 changes: 2 additions & 4 deletions src/wfdb/io/convert/wav.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)
Expand Down
5 changes: 4 additions & 1 deletion src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 8 additions & 3 deletions tests/io/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,8 +648,8 @@ def test_shifted_samples_exceed_int32(self, tmp_path, monkeypatch):
wfdb_to_mat("too_large")
assert not (tmp_path / "too_largem.mat").exists()

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

# Missing samples with non-zero adc_zero (format 516)
Expand All @@ -661,7 +661,10 @@ def test_missing_samples_and_skew_preserved(self, tmp_path, monkeypatch):
mixed_reloaded.p_signal, mixed_orig.p_signal, equal_nan=True
)

# Skewed record should not be skewed a second time when read back
def test_skew_not_applied_twice(self, tmp_path, monkeypatch):
"""Skewed record should not be skewed a second time when read back."""
monkeypatch.chdir(tmp_path)

skew_src = str(self.SAMPLE_DATA / "100skew")
wfdb_to_mat(skew_src, sampto=20)
skew_orig = rdrecord(skew_src, sampto=20)
Expand All @@ -671,6 +674,8 @@ def test_missing_samples_and_skew_preserved(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)
# 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)
Expand Down
49 changes: 49 additions & 0 deletions tests/test_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -1828,3 +1828,52 @@ 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):
"""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_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
Loading