From 5b5b6779309a1cabab62b47d2f77fe7e86313d9a Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sun, 22 Nov 2026 21:06:48 -0500 Subject: [PATCH 1/2] Vectorise find_local_peaks find_local_peaks checked each sample in a Python loop, slicing the window around it and calling max(). XQRS calls it twice on the whole signal, so it took most of the time in xqrs_detect. Find the largest value around every sample at once with scipy.ndimage.maximum_filter1d, and keep only the loop over the candidate peaks, which applies the existing rule of one peak every `radius` samples. maximum_filter1d does not handle NaN reliably, so NaN is replaced with -inf before filtering, and windows containing NaN are excluded as before. On MIT-BIH record 100, find_local_peaks takes 6 ms instead of 139 ms, and xqrs_detect 34 ms instead of 378 ms, with the same peaks. --- changelog.d/find-local-peaks-speed.rst | 2 ++ src/wfdb/processing/peaks.py | 33 ++++++++++++++++++----- tests/test_processing.py | 37 ++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) create mode 100644 changelog.d/find-local-peaks-speed.rst diff --git a/changelog.d/find-local-peaks-speed.rst b/changelog.d/find-local-peaks-speed.rst new file mode 100644 index 00000000..3bc0f1d7 --- /dev/null +++ b/changelog.d/find-local-peaks-speed.rst @@ -0,0 +1,2 @@ +**Speed up find_local_peaks and XQRS** + ``find_local_peaks`` now finds the largest value around each sample with ``scipy.ndimage.maximum_filter1d`` instead of checking each sample in a Python loop, and is about 20 times faster. ``XQRS`` uses it to find candidate peaks, so QRS detection with ``xqrs_detect`` is about 10 times faster (35 ms instead of 380 ms for the 30-minute MIT-BIH record 100). The peaks found are unchanged. diff --git a/src/wfdb/processing/peaks.py b/src/wfdb/processing/peaks.py index 43c6f8d2..0756e4d7 100644 --- a/src/wfdb/processing/peaks.py +++ b/src/wfdb/processing/peaks.py @@ -76,20 +76,39 @@ def find_local_peaks(sig, radius): The locations of all of the local peaks of the input signal. """ + from scipy.ndimage import maximum_filter1d + # TODO: Fix flat mountain scenarios. sig = np.asarray(sig) if np.min(sig) == np.max(sig): return np.empty(0) + size = 2 * radius + 1 + nan_locs = np.isnan(sig) if sig.dtype.kind in "fc" else None + has_nan = nan_locs is not None and nan_locs.any() + + # The largest value within `radius` samples of each sample. A NaN can + # spoil the result of maximum_filter1d well beyond its own window, so + # filter a copy with -inf in its place. + window_max = maximum_filter1d( + np.where(nan_locs, -np.inf, sig) if has_nan else sig, + size=size, + mode="nearest", + ) + is_candidate = sig == window_max + if has_nan: + # A window that contains NaN has no peak + nan_nearby = maximum_filter1d(nan_locs.view(np.uint8), size=size) + is_candidate &= nan_nearby == 0 + + # Take the candidates in order, skipping any within `radius` samples + # after the previous peak peak_inds = [] - - i = 0 - while i < len(sig): - if sig[i] == sig[max(0, i - radius) : i + radius + 1].max(): + next_allowed = 0 + for i in np.flatnonzero(is_candidate).tolist(): + if i >= next_allowed: peak_inds.append(i) - i += radius - else: - i += 1 + next_allowed = i + radius return np.array(peak_inds) diff --git a/tests/test_processing.py b/tests/test_processing.py index 21e5f876..b54006b2 100644 --- a/tests/test_processing.py +++ b/tests/test_processing.py @@ -117,6 +117,43 @@ def test_find_local_peaks_list(self): """A list works as well as an array.""" assert processing.find_local_peaks([0, 1, 2, 3, 2, 1, 0], 1).tolist() == [3] + @pytest.mark.parametrize("radius", [1, 3, 10, 200]) + @pytest.mark.parametrize("n", [2, 5, 50, 1000, 20000]) + def test_find_local_peaks_matches_scan(self, n, radius): + """Give the same peaks as a sample-by-sample scan of the signal.""" + + def scan(sig, radius): + peak_inds = [] + i = 0 + while i < len(sig): + if sig[i] == sig[max(0, i - radius) : i + radius + 1].max(): + peak_inds.append(i) + i += radius + else: + i += 1 + return peak_inds + + rng = np.random.default_rng(n * 1000 + radius) + # Few distinct values, to give ties and flat tops + ties = rng.integers(0, 4, n).astype(float) + with_nan = rng.normal(size=n) + with_nan[rng.random(n) < 0.05] = np.nan + integers = rng.integers(-100, 100, n) + for sig in (ties, with_nan, integers): + if np.min(sig) == np.max(sig): + continue + expected = scan(sig, radius) + assert processing.find_local_peaks(sig, radius).tolist() == expected + + def test_find_local_peaks_ecg(self): + """Peaks on an ECG signal are window maxima at least `radius` apart.""" + record = wfdb.rdrecord("sample-data/100", sampto=36000, channels=[0]) + sig = record.p_signal[:, 0] + peaks = processing.find_local_peaks(sig, 50) + for i in peaks: + assert sig[i] == sig[max(0, i - 50) : i + 51].max() + assert np.all(np.diff(peaks) >= 50) + def test_gqrs(self): record = wfdb.rdrecord( "sample-data/100", From 8d20f6632a916fe563d8703347960ece3630c32c Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sun, 22 Nov 2026 23:10:57 -0500 Subject: [PATCH 2/2] Keep all input types and low memory use in find_local_peaks maximum_filter1d does not support float16, long double, complex, object, datetime or timedelta arrays, which find_local_peaks accepted before. Convert float16 to float32, which is exact, and check the other types one sample at a time as before. On a long flat signal, almost every sample is a candidate peak, so listing them all as Python integers used about 110 MB for 2 million samples, and was slower than the old scan. Work on blocks of 65,536 samples (with `radius` samples on each side), and take the peaks in each run of consecutive candidates as a range, every `radius` samples. For 2 million zeros, this takes 13 ms and 3 MB, against 16 ms and 2 MB for the old scan. On MIT-BIH record 100 it takes 7 ms, against 139 ms. --- src/wfdb/processing/peaks.py | 91 +++++++++++++++++++++++++++--------- tests/test_processing.py | 62 ++++++++++++++++++------ 2 files changed, 115 insertions(+), 38 deletions(-) diff --git a/src/wfdb/processing/peaks.py b/src/wfdb/processing/peaks.py index 0756e4d7..c5d0b7e1 100644 --- a/src/wfdb/processing/peaks.py +++ b/src/wfdb/processing/peaks.py @@ -83,33 +83,78 @@ def find_local_peaks(sig, radius): if np.min(sig) == np.max(sig): return np.empty(0) + # The search continues at least one sample later + step = max(radius, 1) + # maximum_filter1d supports booleans, integers, float32 and float64. + # float16 values are all exactly float32 values. Other types (such as + # complex numbers) are checked one sample at a time. + if sig.dtype.type is np.float16: + sig = sig.astype(np.float32) + elif sig.dtype.kind not in "biu" and sig.dtype.type not in (np.float32, np.float64): + return _scan_local_peaks(sig, radius) + + n = len(sig) size = 2 * radius + 1 - nan_locs = np.isnan(sig) if sig.dtype.kind in "fc" else None - has_nan = nan_locs is not None and nan_locs.any() - - # The largest value within `radius` samples of each sample. A NaN can - # spoil the result of maximum_filter1d well beyond its own window, so - # filter a copy with -inf in its place. - window_max = maximum_filter1d( - np.where(nan_locs, -np.inf, sig) if has_nan else sig, - size=size, - mode="nearest", - ) - is_candidate = sig == window_max - if has_nan: - # A window that contains NaN has no peak - nan_nearby = maximum_filter1d(nan_locs.view(np.uint8), size=size) - is_candidate &= nan_nearby == 0 - - # Take the candidates in order, skipping any within `radius` samples - # after the previous peak peak_inds = [] next_allowed = 0 - for i in np.flatnonzero(is_candidate).tolist(): - if i >= next_allowed: - peak_inds.append(i) - next_allowed = i + radius + # Work on blocks of the signal, so that the arrays below stay small + for start in range(0, n, _PEAK_BLOCK_SIZE): + stop = min(start + _PEAK_BLOCK_SIZE, n) + # The block with the `radius` samples on each side + lo = max(0, start - radius) + hi = min(n, stop + radius) + seg = sig[lo:hi] + seg_nan = np.isnan(seg) if sig.dtype.kind == "f" else None + has_nan = seg_nan is not None and seg_nan.any() + + # The largest value within `radius` samples of each sample. A NaN + # can spoil the result of maximum_filter1d well beyond its own + # window, so filter a copy with -inf in its place. + window_max = maximum_filter1d( + np.where(seg_nan, -np.inf, seg) if has_nan else seg, + size=size, + mode="nearest", + )[start - lo : stop - lo] + is_candidate = sig[start:stop] == window_max + if has_nan: + # A window that contains NaN has no peak + nan_nearby = maximum_filter1d(seg_nan.view(np.uint8), size, mode="nearest") + is_candidate &= nan_nearby[start - lo : stop - lo] == 0 + + # Take the candidates in order, skipping any within `radius` samples + # after the previous peak. Within a run of consecutive candidates + # (such as a flat top), that is every `radius` samples. + edges = np.flatnonzero(np.diff(is_candidate.view(np.int8), prepend=0, append=0)) + for run_start, run_stop in zip(edges[0::2].tolist(), edges[1::2].tolist()): + first = max(start + run_start, next_allowed) + if first < start + run_stop: + run_peaks = range(first, start + run_stop, step) + peak_inds.extend(run_peaks) + next_allowed = run_peaks[-1] + step + + return np.array(peak_inds) + + +# The number of samples that find_local_peaks works on at a time +_PEAK_BLOCK_SIZE = 65536 + + +def _scan_local_peaks(sig, radius): + """Find local peaks by checking one sample at a time. + This is used by `find_local_peaks` for signal types that + scipy.ndimage.maximum_filter1d does not support. + + """ + step = max(radius, 1) + peak_inds = [] + i = 0 + while i < len(sig): + if sig[i] == sig[max(0, i - radius) : i + radius + 1].max(): + peak_inds.append(i) + i += step + else: + i += 1 return np.array(peak_inds) diff --git a/tests/test_processing.py b/tests/test_processing.py index b54006b2..1b9d9c9e 100644 --- a/tests/test_processing.py +++ b/tests/test_processing.py @@ -1,4 +1,5 @@ import math +import tracemalloc from unittest import mock import numpy as np @@ -117,34 +118,65 @@ def test_find_local_peaks_list(self): """A list works as well as an array.""" assert processing.find_local_peaks([0, 1, 2, 3, 2, 1, 0], 1).tolist() == [3] + @staticmethod + def _scan_peaks(sig, radius): + """Find local peaks one sample at a time, as find_local_peaks used to.""" + peak_inds = [] + i = 0 + while i < len(sig): + if sig[i] == sig[max(0, i - radius) : i + radius + 1].max(): + peak_inds.append(i) + i += radius + else: + i += 1 + return peak_inds + + @pytest.mark.parametrize("block_size", [65536, 1, 7]) @pytest.mark.parametrize("radius", [1, 3, 10, 200]) @pytest.mark.parametrize("n", [2, 5, 50, 1000, 20000]) - def test_find_local_peaks_matches_scan(self, n, radius): + def test_find_local_peaks_matches_scan(self, monkeypatch, n, radius, block_size): """Give the same peaks as a sample-by-sample scan of the signal.""" - - def scan(sig, radius): - peak_inds = [] - i = 0 - while i < len(sig): - if sig[i] == sig[max(0, i - radius) : i + radius + 1].max(): - peak_inds.append(i) - i += radius - else: - i += 1 - return peak_inds - + # Small blocks check peaks and flat tops that cross a block edge + monkeypatch.setattr(processing.peaks, "_PEAK_BLOCK_SIZE", block_size) rng = np.random.default_rng(n * 1000 + radius) # Few distinct values, to give ties and flat tops ties = rng.integers(0, 4, n).astype(float) with_nan = rng.normal(size=n) with_nan[rng.random(n) < 0.05] = np.nan + with_inf = rng.choice([0.0, 1.0, np.inf, -np.inf, np.nan], n) integers = rng.integers(-100, 100, n) - for sig in (ties, with_nan, integers): + for sig in (ties, with_nan, with_inf, integers): if np.min(sig) == np.max(sig): continue - expected = scan(sig, radius) + expected = self._scan_peaks(sig, radius) assert processing.find_local_peaks(sig, radius).tolist() == expected + @pytest.mark.parametrize( + "dtype", + ["bool", "uint8", "int16", "uint64", "float16", "float32", "longdouble"] + + ["complex64", "complex128", "object"], + ) + def test_find_local_peaks_dtypes(self, dtype): + """Work for any type of signal that can be compared.""" + sig = np.array([0, 2, 0, 3, 0, 0, 1, 1, 0], dtype=dtype) + expected = self._scan_peaks(sig, 1) + assert expected == [1, 3, 6, 7] + assert processing.find_local_peaks(sig, 1).tolist() == expected + + def test_find_local_peaks_flat(self): + """A long flat signal is fast and uses little memory.""" + sig = np.zeros(2_000_001) + sig[-1] = 1 + tracemalloc.start() + try: + peaks = processing.find_local_peaks(sig, 50) + peak_memory = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + assert peaks.tolist() == self._scan_peaks(sig, 50) + # Checking every sample at once used about 110 MB + assert peak_memory < 10 * 2**20 + def test_find_local_peaks_ecg(self): """Peaks on an ECG signal are window maxima at least `radius` apart.""" record = wfdb.rdrecord("sample-data/100", sampto=36000, channels=[0])