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
4 changes: 4 additions & 0 deletions changelog.d/comparison-integer-differences.rst
Original file line number Diff line number Diff line change
@@ -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.
29 changes: 20 additions & 9 deletions src/wfdb/processing/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
67 changes: 67 additions & 0 deletions tests/test_comparison_integer_precision.py
Original file line number Diff line number Diff line change
@@ -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)
Loading