diff --git a/changelog.d/comparison-integer-differences.rst b/changelog.d/comparison-integer-differences.rst new file mode 100644 index 00000000..fa1131e3 --- /dev/null +++ b/changelog.d/comparison-integer-differences.rst @@ -0,0 +1,4 @@ +**Avoid integer overflow when comparing annotation samples** + ``processing.compare_annotations`` and ``Comparitor`` widen NumPy integer + sample positions before subtracting them, so unsigned positions can match + nearby later detections and large signed differences do not wrap. diff --git a/src/wfdb/processing/evaluate.py b/src/wfdb/processing/evaluate.py index 4a0023d5..aa3bd4c4 100644 --- a/src/wfdb/processing/evaluate.py +++ b/src/wfdb/processing/evaluate.py @@ -7,6 +7,15 @@ from wfdb.io.record import rdsamp +def _sample_difference(reference, test): + # Widen integer scalars before subtracting, without truncating float inputs. + if isinstance(reference, np.integer): + reference = int(reference) + if isinstance(test, np.integer): + test = int(test) + return reference - test + + class Comparitor: """The class to implement and hold comparisons between two sets of annotations. @@ -54,11 +63,11 @@ class Comparitor: """ def __init__(self, ref_sample, test_sample, window_width, signal=None): - if len(ref_sample) > 1 and len(test_sample) > 1: - if min(np.diff(ref_sample)) < 0 or min(np.diff(test_sample)) < 0: - raise ValueError( - "The sample locations must be monotonically" + " increasing" - ) + # Compare adjacent values directly: subtraction can overflow integer dtypes. + if np.any(np.less(ref_sample[1:], ref_sample[:-1])) or np.any( + np.less(test_sample[1:], test_sample[:-1]) + ): + raise ValueError("The sample locations must be monotonically increasing") self.ref_sample = ref_sample self.test_sample = test_sample @@ -207,8 +216,10 @@ def compare(self): # The previous test annotation is inspected closest_samp_num = closest_samp_num - 1 smallest_samp_diff = abs( - self.ref_sample[ref_samp_num] - - self.test_sample[closest_samp_num] + _sample_difference( + self.ref_sample[ref_samp_num], + self.test_sample[closest_samp_num], + ) ) # Assign the reference-test pair if close enough if smallest_samp_diff < self.window_width: @@ -263,7 +274,7 @@ def _get_closest_samp_num(self, ref_samp_num, start_test_samp_num): ref_samp = self.ref_sample[ref_samp_num] test_samp = self.test_sample[start_test_samp_num] - samp_diff = ref_samp - test_samp + samp_diff = _sample_difference(ref_samp, test_samp) # Initialize running parameters closest_samp_num = start_test_samp_num @@ -272,7 +283,7 @@ def _get_closest_samp_num(self, ref_samp_num, start_test_samp_num): # Iterate through the testing samples for test_samp_num in range(start_test_samp_num, self.n_test): test_samp = self.test_sample[test_samp_num] - samp_diff = ref_samp - test_samp + samp_diff = _sample_difference(ref_samp, test_samp) abs_samp_diff = abs(samp_diff) # Found a better match diff --git a/tests/test_comparison_integer_precision.py b/tests/test_comparison_integer_precision.py new file mode 100644 index 00000000..cfa6bcdb --- /dev/null +++ b/tests/test_comparison_integer_precision.py @@ -0,0 +1,67 @@ +import warnings + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from wfdb import processing + + +@pytest.mark.parametrize( + "dtype,offset", + [(np.uint32, 0), (np.uint64, 0), (np.uint64, 2**63), (np.int64, 2**60)], +) +@pytest.mark.parametrize("delta", [-1, 1]) +def test_integer_annotation_comparison(dtype, offset, delta): + reference = np.array([offset + 100, offset + 200], dtype=dtype) + detected = np.array([offset + 100 + delta, offset + 200 + delta], dtype=dtype) + original_ref, original_test = reference.copy(), detected.copy() + + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + result = processing.compare_annotations(reference, detected, 5) + + assert (result.tp, result.fp, result.fn) == (2, 0, 0) + assert_array_equal(result.matching_sample_nums, [0, 1]) + assert_array_equal(reference, original_ref) + assert_array_equal(detected, original_test) + + +def test_fractional_annotation_comparison_preserves_distances(): + result = processing.compare_annotations( + np.array([100.2, 200.2]), np.array([100.8, 200.8]), 0.5 + ) + assert (result.tp, result.fp, result.fn) == (0, 2, 2) + + +def test_signed_integer_span_does_not_overflow(): + result = processing.compare_annotations( + np.array([-(2**63)], dtype=np.int64), np.array([2**63 - 1], dtype=np.int64), 5 + ) + assert (result.tp, result.fp, result.fn) == (0, 1, 1) + + +@pytest.mark.parametrize("side", ["reference", "detected"]) +@pytest.mark.parametrize("other_length", [1, 2]) +def test_sorted_signed_integer_span_is_accepted(side, other_length): + spanning = np.array([-(2**63), 2**63 - 1], dtype=np.int64) + other = spanning.copy() if other_length == 2 else spanning[:1].copy() + reference, detected = ( + (spanning, other) if side == "reference" else (other, spanning) + ) + result = processing.compare_annotations(reference, detected, 5) + assert result.tp == other_length + assert result.fp == len(detected) - other_length + assert result.fn == len(reference) - other_length + + +@pytest.mark.parametrize("side", ["reference", "detected"]) +@pytest.mark.parametrize("other_length", [1, 2]) +def test_descending_unsigned_samples_are_rejected(side, other_length): + descending = np.array([200, 100], dtype=np.uint64) + other = np.array([100, 200], dtype=np.uint64)[:other_length] + reference, detected = ( + (descending, other) if side == "reference" else (other, descending) + ) + with pytest.raises(ValueError, match="monotonically"): + processing.compare_annotations(reference, detected, 5)