TExcelTAD
Home › SciPy › SciPy Peaks and Convolution

SciPy Peaks and Convolution

Two everyday signal tasks: finding peaks (heartbeats in an ECG, spikes of traffic, peaks in a spectrum) and convolution / correlation (smoothing, matching a pattern, measuring a time delay). Both live in scipy.signal.

Finding peaks

find_peaks(x) returns the indices of all local maxima — samples larger than both neighbours — plus a dictionary of properties:

python · try it yourself
import numpy as np
from scipy.signal import find_peaks

x = np.array([0, 2, 1, 3, 7, 4, 2, 5, 4, 1, 0, 6, 5, 2])
peaks, props = find_peaks(x)
print("peak indices:", peaks)
print("peak values :", x[peaks])
peak indices: [ 1  4  7 11]
peak values : [2 7 5 6]

Real data has many tiny bumps, so you'll almost always add conditions:

Argument Keeps only peaks that…
height=h are at least h high
distance=d are at least d samples apart (keeps the taller one)
prominence=p stand out at least p above their surroundings
width=w are at least w samples wide
threshold=t rise at least t above their immediate neighbours
python · try it yourself
import numpy as np
from scipy.signal import find_peaks

x = np.array([0, 2, 1, 3, 7, 4, 2, 5, 4, 1, 0, 6, 5, 2])
print("height>=5   :", find_peaks(x, height=5)[0])
print("distance>=5 :", find_peaks(x, distance=5)[0])
peaks, props = find_peaks(x, prominence=4)
print("prominence>=4:", peaks, "prominences:", props["prominences"])
height>=5   : [ 4  7 11]
distance>=5 : [ 4 11]
prominence>=4: [ 4 11] prominences: [7. 4.]

Prominence is usually the most useful criterion: it measures how much a peak rises above the higher of the two lowest points separating it from taller peaks, so small bumps on a big hill are ignored.

Counting heartbeats

A synthetic pulse signal at 72 beats per minute with noise and baseline drift. distance prevents counting one beat twice, and prominence ignores noise:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import find_peaks

rng = np.random.default_rng(2)
fs = 100
t = np.arange(0, 10, 1 / fs)
beat_period = 60 / 72
phase = (t % beat_period) / beat_period
pulse = np.exp(-((phase - 0.3) / 0.04) ** 2)          # one sharp spike per beat
x = pulse + 0.2 * np.sin(2 * np.pi * 0.2 * t) + rng.normal(0, 0.05, t.size)

peaks, _ = find_peaks(x, prominence=0.5, distance=int(0.4 * fs))
intervals = np.diff(t[peaks])
print("beats found  :", len(peaks))
print(f"heart rate   : {60 / intervals.mean():.1f} bpm")

plt.plot(t, x)
plt.plot(t[peaks], x[peaks], "rx")
plt.xlabel("time (s)")
plt.title("Detected heartbeats")
plt.show()
beats found  : 12
heart rate   : 72.1 bpm

Convolution

Convolution slides one array (a kernel) across another, multiplying and summing at each position. With a kernel of equal weights you get a moving average; with other kernels you get derivatives, blurs or edge detectors. mode controls the output length:

python · try it yourself
import numpy as np
from scipy import signal

x = np.array([0, 0, 1, 2, 3, 2, 1, 0, 0], dtype=float)
avg = np.ones(3) / 3
diff = np.array([1, -1])                    # difference of neighbours

print("full :", np.round(signal.convolve(x, avg, mode="full"), 3))
print("same :", np.round(signal.convolve(x, avg, mode="same"), 3))
print("valid:", np.round(signal.convolve(x, avg, mode="valid"), 3))
print("slope:", signal.convolve(x, diff, mode="valid"))
full : [0.    0.    0.333 1.    2.    2.333 2.    1.    0.333 0.    0.   ]
same : [0.    0.333 1.    2.    2.333 2.    1.    0.333 0.   ]
valid: [0.333 1.    2.    2.333 2.    1.    0.333]
slope: [ 0.  1.  1.  1. -1. -1. -1.  0.]

For long signals, signal.fftconvolve (or signal.convolve, which chooses automatically) uses the FFT and is dramatically faster.

Cross-correlation: finding a delay

Cross-correlation measures how similar two signals are at every relative shift. Its peak tells you the shift that lines them up best — how sound-based ranging, GPS and echo detection work. correlation_lags gives the shift for each output position:

python · try it yourself
import numpy as np
from scipy import signal

rng = np.random.default_rng(9)
sent = rng.normal(size=200)                        # a random "ping"
delay = 37
received = np.concatenate([np.zeros(delay), sent])[:200] * 0.6
received += rng.normal(0, 0.3, 200)                # attenuated and noisy

corr = signal.correlate(received, sent, mode="full")
lags = signal.correlation_lags(received.size, sent.size, mode="full")
print("estimated delay:", lags[np.argmax(corr)], "samples (true 37)")

fs = 1000                                           # samples per second
print(f"distance at 343 m/s: {lags[np.argmax(corr)] / fs * 343 / 2:.2f} m (echo)")
estimated delay: 37 samples (true 37)
distance at 343 m/s: 6.35 m (echo)

Note: Convolution flips the kernel before sliding; correlation does not. For symmetric kernels like a moving average the two give the same result.

Test yourself

Which find_peaks option ignores small bumps sitting on top of a larger hill?

  1. height
  2. distance
  3. prominence
  4. width

What does convolving a signal with np.ones(5) / 5 do?

  1. Differentiates it
  2. Applies a 5-point moving average
  3. Shifts it by 5 samples
  4. Finds its peaks

How do you estimate the time delay between two signals?

  1. Find the peak of their cross-correlation
  2. Subtract their means
  3. Apply a high-pass filter
  4. Count their peaks