diff --git a/changelog.d/local-peaks-integer-precision.rst b/changelog.d/local-peaks-integer-precision.rst new file mode 100644 index 00000000..82034ae1 --- /dev/null +++ b/changelog.d/local-peaks-integer-precision.rst @@ -0,0 +1,4 @@ +**Preserve small differences in large integer local-peak inputs** + ``processing.find_local_peaks`` uses its exact scanning path for integer + values outside the range represented exactly by a double, avoiding false + or missing peaks caused by rounding in the fast maximum filter. diff --git a/src/wfdb/processing/peaks.py b/src/wfdb/processing/peaks.py index bcf4d6be..08e7b286 100644 --- a/src/wfdb/processing/peaks.py +++ b/src/wfdb/processing/peaks.py @@ -84,9 +84,17 @@ def find_local_peaks(sig, radius): # TODO: Fix flat mountain scenarios. sig = np.asarray(sig) - if np.min(sig) == np.max(sig): + min_value, max_value = np.min(sig), np.max(sig) + if min_value == max_value: return np.empty(0) + # maximum_filter1d uses doubles internally, losing small differences in + # 64-bit integers outside the exact integer range of a double. + if sig.dtype.kind in "iu" and ( + int(min_value) < -(1 << 53) or int(max_value) > (1 << 53) + ): + return _scan_local_peaks(sig, radius) + # The search continues at least one sample later step = max(radius, 1) # maximum_filter1d supports booleans, integers, float32 and float64. diff --git a/tests/test_local_peaks_precision.py b/tests/test_local_peaks_precision.py new file mode 100644 index 00000000..723d3be0 --- /dev/null +++ b/tests/test_local_peaks_precision.py @@ -0,0 +1,35 @@ +import numpy as np +import pytest + +from wfdb import processing + + +@pytest.mark.parametrize( + "dtype,offset", [(np.int64, 2**60), (np.int64, -(2**60)), (np.uint64, 2**63)] +) +@pytest.mark.parametrize("radius", [1, 2]) +@pytest.mark.parametrize("shape", [[0, 1, 0], [0, 1, 1, 0], [0, 2, 1, 3, 1, 0]]) +def test_large_integer_local_peaks_preserve_small_differences( + dtype, offset, radius, shape +): + signal = np.array([offset + value for value in shape], dtype=dtype) + original = signal.copy() + expected = [] + index = 0 + while index < len(shape): + if shape[index] == max(shape[max(0, index - radius) : index + radius + 1]): + expected.append(index) + index += max(radius, 1) + else: + index += 1 + + actual = processing.find_local_peaks(signal, radius) + + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(signal, original) + + +@pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.int32, np.float64]) +def test_local_peaks_small_values_unchanged(dtype): + signal = np.array([0, 1, 0, 2, 0], dtype=dtype) + np.testing.assert_array_equal(processing.find_local_peaks(signal, 1), [1, 3])