Correlation and Matched Filtering
An ultrasonic range finder sends a short coded burst and listens for the echo, which comes back weaker than the receiver's noise. Two microphones on a machine hear the same knock a fraction of a millisecond apart, and the difference tells you where the knock came from. A radio receiver must find the start of a packet in a stream of noise. All three are solved by one operation: correlation, sliding a known pattern along a signal and measuring how well they match at each shift. Done with the right template it becomes the matched filter, the linear filter that gives the best possible signal-to-noise ratio for detecting a known shape in white noise. Correlation and its spectrum (the power spectrum) are introduced in Power Spectrum; here we use them to detect and to measure delays.
Cross-correlation and autocorrelation
For real sequences, the cross-correlation at lag is
It is a convolution with one signal reversed, with , so it can be computed with FFTs. If is a delayed, noisy copy of , peaks at the delay. The autocorrelation peaks at with the signal's energy, and its Fourier transform is the energy (or power) spectrum. Normalised by , the peak is the correlation coefficient, between and .
In SciPy, scipy.signal.correlate(x, y) returns the full correlation and scipy.signal.correlation_lags(len(x), len(y)) the matching lags; method='fft' is chosen automatically for long inputs.
The matched filter
Suppose a known pulse ( samples, energy ) arrives in white noise of variance . Of all FIR filters, the one that maximises the output signal-to-noise ratio at the moment the pulse ends is the time-reversed pulse,
Filtering with is the same as correlating with . The result does not depend on the pulse's shape, only on its energy: a long, low-amplitude coded pulse is as detectable as a short, strong one with the same energy. For samples of amplitude the input SNR per sample is and the output SNR is , a processing gain of ( dB). This is how radar, sonar, GPS and spread-spectrum radios work below the noise.
The pulse shape decides the sidelobes: the correlation of the pulse with itself away from its peak. A plain rectangular burst has a triangular autocorrelation, a peak as wide as the burst itself; a Barker code has the lowest possible sidelobes for a binary sequence. The 13-chip Barker code has an autocorrelation peak of 13 and sidelobes of at most 1, i.e. .
Worked example: a Barker-13 burst in noise
Given: a Barker-13 burst with chips of , one sample per chip, buried in white noise with (input SNR per sample), starting at sample 137 of a 400-sample record.
Find: the expected matched-filter peak and noise level, the processing gain, and whether the burst can be located.
Solve: . At the correct lag the signal part of the correlation is ; the noise part has standard deviation . Output SNR , i.e. , a processing gain of over the per-sample SNR. A threshold at about half the peak (6.5) is noise standard deviations, so occasional false peaks are possible in a long record; longer codes or repeated bursts raise the margin.
Check: run it.
import numpy as np
from scipy.signal import correlate, correlation_lags
barker13 = np.array([1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1], dtype=float)
ac = correlate(barker13, barker13)
print("Barker-13 autocorrelation:", " ".join(str(int(v)) for v in ac))
print(f"peak {ac.max():.0f}, max sidelobe {np.max(np.abs(ac[:12])):.0f} -> {20 * np.log10(1 / 13):.1f} dB")
rng = np.random.default_rng(42)
N, start, sigma = 400, 137, 1.0
x = sigma * rng.standard_normal(N)
x[start:start + 13] += barker13 # the burst, 0 dB SNR per sample
r = correlate(x, barker13, mode="full")
lags = correlation_lags(len(x), len(barker13), mode="full")
k = lags[np.argmax(r)]
noise_part = np.delete(r, np.arange(np.argmax(r) - 12, np.argmax(r) + 13))
print(f"detected start = {k} (true {start}); peak = {r.max():.2f}")
print(f"correlation noise std = {noise_part.std():.2f} (theory sqrt(13) = {np.sqrt(13):.2f})")
print(f"processing gain = 10 log10(13) = {10 * np.log10(13):.1f} dB")Barker-13 autocorrelation: 1 0 1 0 1 0 1 0 1 0 1 0 13 0 1 0 1 0 1 0 1 0 1 0 1
peak 13, max sidelobe 1 -> -22.3 dB
detected start = 137 (true 137); peak = 18.37
correlation noise std = 3.30 (theory sqrt(13) = 3.61)
processing gain = 10 log10(13) = 11.1 dB
The peak lands on the true start. Its height () is plus a noise sample of about standard deviations, which is why a detector threshold is set from the noise statistics, not from the ideal peak. The noise standard deviation estimated from one 400-sample record () is close to the theoretical .
Time-delay estimation
Two microphones apart along the line to a source hear broadband noise apart (). At that is 23 samples. Cross-correlating the two channels finds it, and a parabola through the peak and its neighbours refines it below one sample:
import numpy as np
from scipy.signal import correlate, correlation_lags
fs, c = 48000.0, 343.0
rng = np.random.default_rng(7)
src = rng.standard_normal(4800 + 100) # 0.1 s of broadband source noise
d = 23 # true delay in samples
mic1 = src[100:4900] + 0.5 * rng.standard_normal(4800)
mic2 = src[100 - d:4900 - d] + 0.5 * rng.standard_normal(4800) # hears it d samples later
r = correlate(mic2, mic1, mode="full")
lags = correlation_lags(len(mic2), len(mic1), mode="full")
i = np.argmax(r)
y0, y1, y2 = r[i - 1], r[i], r[i + 1]
frac = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2) # parabolic interpolation
delay = lags[i] + frac
rho = r[i] / np.sqrt(np.sum(mic1**2) * np.sum(mic2**2))
print(f"delay = {lags[i]} samples ({frac:+.3f}) = {1e3 * delay / fs:.4f} ms -> path difference {100 * c * delay / fs:.2f} cm")
print(f"correlation coefficient at the peak: {rho:.3f}")delay = 23 samples (-0.005) = 0.4791 ms -> path difference 16.43 cm
correlation coefficient at the peak: 0.797
The interpolation correction is tiny because the true delay is a whole number of samples. The coefficient is below 1 because each microphone adds its own noise ( against a source of : expected , measured ). Real rooms add reflections, which show up as extra peaks; a band-pass filter or the "PHAT" weighting (whitening the cross-spectrum) sharpens the main one.
Guided lab: measure a path difference with two microphones
Hand calculation. Two microphones apart, the source on the line through both: delay , samples at . One sample is of path.
Simulation. Set d = 70 in the program and add more microphone noise until the peak is wrong; note the correlation coefficient at which detection fails.
What you would measure. A USB audio interface with two inputs and two small microphones, a click or a burst of noise from a phone speaker at the end of the line. Record a few seconds and cross-correlate. Expect samples: the speed of sound changes by about per kelvin, and placing the microphones' acoustic centres to is hard. Move the source off-axis and the delay falls as , the principle of acoustic direction finding.
Hazards and safe setup. Keep sound levels comfortable (no loud sources close to the ears or microphones); USB-powered equipment only.
Pitfalls
- Misreading the lag sign: check with a known delay, and use
correlation_lagsinstead of guessing the index offset. - Correlating signals with large DC offsets: the offset's triangular correlation swamps the peak. Remove the mean first.
- Setting a detection threshold from the ideal peak instead of from the correlation noise.
- Using a periodic signal for delay estimation: correlation peaks repeat every period and the delay is ambiguous.
Practice
- What processing gain does a matched filter give for a 127-chip code?
- A pulse of energy is in white noise with . What is the matched-filter output SNR in dB?
- Why does a plain rectangular burst make a poor ranging pulse even with a matched filter?
Answer
- .
- , i.e. .
- Its autocorrelation is a broad triangle: the SNR at the peak is optimal, but the peak is wide, so the timing (range) resolution is poor and nearby echoes merge. Coded or chirped pulses keep the energy but sharpen the peak.
Test yourself
The matched filter for a known pulse of length has impulse response
- a moving average of length
In white noise, the matched filter's output SNR depends on the pulse's
- shape
- energy
- peak amplitude only
- bandwidth only
The largest autocorrelation sidelobe of the 13-chip Barker code, relative to its peak, is
- dB
- dB
- dB
- dB
Cross-correlation of two microphone signals peaks at lag 35 at 48 kSa/s. The arrival-time difference is
- 35 ms
- 0.729 ms
- 1.37 ms
- 48 ms