Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Convolution and correlation

ProblemApply a finite impulse response to a signal, in one piece or as a stream; measure the similarity of two signals as a function of their relative shift
Devised byThe convolution sum is classical (Euler, Laplace, Cauchy); James Cooley and John Tukey (1965), the FFT that makes fast convolution practical; Thomas Stockham (1966), sectioned high-speed convolution (overlap-add and overlap-save); Charles Knapp and G. Clifford Carter (1976), time-delay estimation by correlation
AccuracyDirect sums are exact up to rounding; FFT methods agree with them to about relative (tables below)
CostDirect: for samples and taps. FFT: for whole signals, per sample for streams
Read firstBackground: frequency responses, The fast Fourier transform
APIconvolve (ConvolveMode::{Full, Same, Valid}, ConvolveMethod::{Direct, Fft, Auto}), fft_convolve, cross_correlate, fft_cross_correlate, fft_correlation_peak, OverlapAddFir, FftFir, StreamOperator

Overview

A linear time-invariant system is completely described by its impulse response : the output for any input is the convolution

When has finitely many taps, the system is a finite impulse response (FIR) filter, and computing is the most common operation in digital signal processing. Done directly it costs one multiply-add per tap per sample. By the convolution theorem, the discrete Fourier transform turns convolution into multiplication, so with the FFT, long filters cost a few operations per sample whatever their length. Cross-correlation is convolution with one signal reversed (and conjugated). Its peak shows the shift at which two signals best match, which is how echoes, delays and known waveforms are found.

Where it is used

Convolution is how a linear system’s output is computed from its input, and correlation is how a known pattern is found.

  • Audio effects and reverberation. Convolving a recording with a room’s impulse response makes it sound as though it were played in that room.
  • Filtering and smoothing. Moving averages, FIR filters and derivative filters are all convolutions.
  • Detection. Correlating a received signal with a known waveform (radar echo, GPS code, a preamble in a packet) gives the matched filter.
  • Image processing. Blur, sharpen and edge filters are two-dimensional convolutions.

History

Convolution sums and integrals go back to Euler and Laplace, and the name to the twentieth century. Before the FFT, digital filtering meant direct sums. James Cooley and John Tukey’s FFT (1965) changed that almost at once: Thomas Stockham (1966) showed that sectioning a long signal into blocks, transforming each, and joining the results by overlap-add or overlap-save made “high-speed convolution” faster than direct filtering for filters beyond a few dozen taps. Cross-correlation for delay estimation is older still, in radar and sonar; Charles Knapp and G. Clifford Carter’s generalised cross-correlation (1976) is the standard analysis of it.

The idea

Output lengths and modes

Convolving samples with taps gives outputs, the full convolution, including the partial overlaps at both ends. Same keeps the central samples, aligned with the input. Valid keeps only the samples where the filter lies entirely inside the signal. The modes follow NumPy and SciPy, and the library’s results agree with them to rounding error (see the chapter’s reference table).

Fast convolution

The DFT of a circular convolution is the product of the DFTs. To see why, take the -point DFT of the circular convolution and exchange the order of summation:

where . The step uses that is periodic in with period , so replacing by only multiplies by whatever the wrap-around. This is also where the circular nature enters: indices wrap modulo , so products of samples near the end of a block land at the start. Padding both sequences with zeros to a length makes the circular convolution equal the linear one, so

at a cost of three FFTs, , instead of multiply-adds. For a whole signal, fft_convolve does exactly this. convolve with ConvolveMethod::Auto chooses direct summation when .

Streams: overlap-add and overlap-save

A stream cannot be transformed whole. Both sectioned methods cut it into blocks of samples and use FFTs of length (a power of two):

  • Overlap-add convolves each block separately, each result being long, and adds the samples that spill past each block into the start of the next one.
  • Overlap-save prefixes each block with the last input samples, convolves circularly, and discards the first outputs, which are corrupted by wrap-around. The remaining outputs are exact.

Both cost two FFTs per block (the filter’s transform is computed once), about operations per sample. Their outputs are identical to the direct sum:

Table 14.2. Time to filter 20 000 samples by direct and FFT convolution.

filter taps (20 000 samples)direct (ms)whole-signal FFT (ms)overlap-add stream (ms)overlap-save stream (ms)
80.100.570.190.16
320.130.660.210.18
1280.390.570.210.15
5121.540.570.340.24
20486.210.570.560.42

Direct filtering wins for short filters. The crossover lies near a hundred taps, beyond which the streaming FFT filters cost almost nothing more per tap. Transforming the whole 20 000-sample signal at once needs three FFTs of 32 768 points, and is slower than sectioning until the filter is thousands of taps long.

Cross-correlation and delay estimation

The cross-correlation is large where , shifted by , resembles . If is a delayed copy of plus independent noise, peaks at the delay. The noise adds a random background whose standard deviation grows only as , while the peak grows as :

Figure 14.1. Cross-correlation of a noisy delayed copy.

Here the copy is buried in noise with 1.5 times its amplitude, yet the peak at lag 37 stands far above the background. This is the principle of the matched filter used in radar (pulse compression) and communications (synchronisation).

Algorithm

For an input of samples and a filter of taps.

Direct convolution.

  1. For each output index , sum over the values of for which both indices are in range.
  2. Trim the result to the requested mode: all of it (full), the central samples (same), or the samples computed from complete overlaps (valid).

Cost: about multiply-adds.

FFT convolution.

  1. Choose , the next power of two at or above .
  2. Pad both sequences with zeros to length and transform them.
  3. Multiply the two transforms element by element.
  4. Inverse-transform, keep the first values, and trim to the mode.

Cost: three FFTs of length .

Overlap-save, for a stream processed in blocks of samples, with an FFT length . The transform of the zero-padded filter is computed once. The state is the last input samples, initially zeros.

  1. Wait until new samples have arrived.
  2. Form the buffer of the remembered samples followed by the new ones (padded to if necessary) and transform it.
  3. Multiply by the filter’s transform and inverse-transform.
  4. Discard the first outputs, which are corrupted by wrap-around, and emit the next .
  5. Remember the last input samples for the next block.

At the end of the stream, flush pads the remaining input with zeros, so as to emit the last partial block and the samples of the filter’s tail. The total output is then the full convolution.

Overlap-add uses the same blocks: transform each block of new samples (zero-padded to ), multiply, inverse-transform to get outputs, add the saved tail of the previous block to the first of them, emit , and save the new tail.

Implementation

    fn run_block(&mut self, new: &[Complex<f64>], valid: usize) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
        let mut x = vec![Complex::new(0.0, 0.0); self.fft_len];
        x[..self.taps_len - 1].copy_from_slice(&self.history);
        x[self.taps_len - 1..self.taps_len - 1 + new.len()].copy_from_slice(new);
        let mut y = self.fwd.execute(&x)?;
        for (v, h) in y.iter_mut().zip(&self.taps_fft) {
            *v *= *h;
        }
        let y = self.inv.execute(&y)?;
        // The last `taps - 1` samples of [history, block] become the next history.
        if self.taps_len > 1 {
            self.history.copy_from_slice(&x[self.block_len..self.block_len + self.taps_len - 1]);
        }
        Ok(y[self.taps_len - 1..self.taps_len - 1 + valid].to_vec())
    }
  • Both streaming filters implement StreamOperator: process accepts chunks of any size and returns whole blocks as they complete, flush ends the stream, and reset starts a new one.
  • The FFT length is rounded up to a power of two. The block length is the rest of it, after the samples of history.
  • fft_correlation_peak returns the lag of the largest-magnitude correlation; a positive lag means the first signal lags the second.

In practice

//! Convolution, streaming FFT filtering and time-delay estimation by cross-correlation.

use lib_jsl_dsp::discrete::convolve::{ConvolveMethod, ConvolveMode, convolve};
use lib_jsl_dsp::discrete::fft_cross_correlation::fft_correlation_peak;
use lib_jsl_dsp::discrete::filters::fft_fir::FftFir;
use lib_jsl_dsp::discrete::stream_operator::StreamOperator;

fn main() {
    let x = [1.0, 2.0, 3.0, 4.0, 5.0];
    let h = [1.0, -1.0];
    for mode in [ConvolveMode::Full, ConvolveMode::Same, ConvolveMode::Valid] {
        println!("{mode:?}: {:?}", convolve(&x, &h, mode, ConvolveMethod::Direct).unwrap());
    }

    // Streaming: feed a long signal in uneven chunks; the output equals one big convolution.
    let signal: Vec<f64> = (0..1000).map(|n| (0.05 * n as f64).sin()).collect();
    let taps: Vec<f64> = (0..63).map(|k| 1.0 / (1.0 + (k as f64 - 31.0).powi(2))).collect();
    let mut fir = FftFir::new(&taps, 200).unwrap();
    let mut streamed = Vec::new();
    for chunk in signal.chunks(137) {
        if let Some(y) = fir.process(chunk).unwrap() {
            streamed.extend(y);
        }
    }
    streamed.extend(fir.flush().unwrap().unwrap_or_default());
    let reference = convolve(&signal, &taps, ConvolveMode::Full, ConvolveMethod::Direct).unwrap();
    let err = streamed.iter().zip(&reference).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
    println!("overlap-save: {} outputs (block {}, FFT {}), largest difference {err:.1e}", streamed.len(), fir.block_len(), fir.fft_len());

    // A pulse and its echo 23 samples later.
    let pulse: Vec<f64> = (0..64).map(|n| if n < 8 { 1.0 } else { 0.0 }).collect();
    let mut echo = vec![0.0; 64];
    for n in 0..64 - 23 {
        echo[n + 23] = 0.5 * pulse[n];
    }
    let (lag, value) = fft_correlation_peak(&echo, &pulse).unwrap();
    println!("echo delay: {lag} samples (correlation {value:.2})");
}
Full: [1.0, 1.0, 1.0, 1.0, 1.0, -5.0]
Same: [1.0, 1.0, 1.0, 1.0, 1.0]
Valid: [1.0, 1.0, 1.0, 1.0]
overlap-save: 1062 outputs (block 450, FFT 512), largest difference 2.7e-15
echo delay: 23 samples (correlation 4.00)

Convolving with takes first differences. Feeding the stream in chunks of 137 samples, unrelated to its block size of 450, changes nothing in the output.

Strengths

  • Exact linear filtering at a cost per sample that, with FFTs, barely depends on the filter length.
  • Correlation finds delays and known waveforms in noise far below the signal level.

Weaknesses

  • FFT methods add a block of latency and give up a few digits to rounding for very long transforms.
  • Sectioned filtering assumes a fixed filter; adaptive or time-varying filters need the direct form.

Exercises

  1. Show that zero-padding to makes circular convolution equal linear convolution, and that does not.
  2. Count the real multiplications per output sample of overlap-save with block and FFT length , and find the that minimises it for .
  3. Show that cross-correlating with a signal is the same as convolving with its time-reversed conjugate.
  4. With white noise of variance added to a delayed copy of a unit-power signal of length , compute the ratio of the correlation peak to the background’s standard deviation.
  5. Implement overlap-add with FFTs of length for a block length , and check it against convolve.
Hints and answers
  1. Linear convolution has non-zero outputs, which fit into without wrapping. With the last output wraps onto the first and the two are summed.
  2. Each block costs about complex multiplications for the two FFTs plus for the pointwise product, and produces outputs. Minimise the cost per output over ; for the best is a power of two near to times (for example 2048).
  3. is the convolution of with .
  4. The peak is (unit power) while the background has variance , so the ratio of peak to background standard deviation is .
  5. Split the input into blocks of , convolve each with the filter via FFT length (taps up to ), and add the overlapping tails of consecutive blocks.

Further reading

  • T. G. Stockham, “High-speed convolution and correlation”, Proceedings of the AFIPS Spring Joint Computer Conference 28 (1966) 229–233.
  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010, chapters 2 and 8.
  • C. H. Knapp and G. C. Carter, “The generalized correlation method for estimation of time delay”, IEEE Transactions on Acoustics, Speech, and Signal Processing 24 (1976) 320–327.