05. Convolution and FIR filters

A finite impulse response (FIR) filter replaces each sample by a weighted sum of the most recent input samples. This operation, convolution, is used to smooth noisy envelopes, remove hum, band-limit a signal before downsampling, simulate a room from its impulse response, and implement the pre-emphasis step of speech front ends. This notebook defines convolution precisely, describes the two output lengths (“full” and “valid”), and connects a filter’s taps to its frequency response and delay, ending with a low-pass filter designed from scratch.

Learning outcomes. After working through this notebook you can

  • compute a convolution by hand and predict the length of its full and valid parts;

  • read a filter’s frequency response from its taps, and measure it by filtering sines;

  • explain linear phase and group delay, and predict the delay of a symmetric FIR filter;

  • design a windowed-sinc low-pass filter and check it against SciPy.

import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as ss

import audio_samples as aus

rng = np.random.default_rng(seed=2026)
F64 = np.dtype("float64")
WT = aus.WindowType
FS = 16_000

def mono(v, fs=FS):
    return aus.AudioSamples.new_mono(np.asarray(v, dtype=float), sample_rate=fs)

Concept

Convolution. For an input \(x[n]\) of \(N\) samples and taps \(h[k]\), \(k = 0 \dots M-1\) (the tap index; \(j = \sqrt{-1}\) throughout):

\[y[n] = \sum_{k=0}^{M-1} h[k] \, x[n - k]\]

where \(n\) is the output sample index, \(M\) the number of taps and \(x[\cdot] = 0\) outside the signal. The full convolution has \(N + M - 1\) samples (\(n = 0 \dots N + M - 2\)). The valid part, where every term of the sum uses a real input sample, has \(N - M + 1\) samples (\(n = M-1 \dots N-1\)).

Impulse response. Filtering the unit impulse \(\delta[n]\) (1 at \(n = 0\), 0 elsewhere) returns \(y[n] = h[n]\): the taps are the impulse response.

Frequency response. A complex exponential at angular frequency \(\omega = 2\pi f / f_s\) (radians per sample, \(f\) in Hz, \(f_s\) the sample rate in Hz) comes out multiplied by

\[H(e^{j\omega}) = \sum_{k=0}^{M-1} h[k] \, e^{-j\omega k}\]

so a sine of amplitude \(A\) is output with amplitude \(A\,|H|\), shifted by the phase \(\arg H\). For the \(M\)-tap moving average \(h[k] = 1/M\) this sums to the Dirichlet kernel

\[|H(f)| = \left| \frac{\sin(\pi f M / f_s)}{M \sin(\pi f / f_s)} \right|\]

with nulls at every multiple of \(f_s / M\) Hz (except 0).

Linear phase and group delay. The group delay

\[\tau_g(\omega) = -\frac{d \arg H(e^{j\omega})}{d\omega} = \mathrm{Re}\left\{ \frac{\sum_k k\,h[k]\,e^{-j\omega k}}{H(e^{j\omega})} \right\}\]

is the delay in samples of a narrow-band signal at \(\omega\). If the taps are symmetric, \(h[k] = h[M-1-k]\), the phase is exactly \(-\omega (M-1)/2\) (plus jumps of \(\pi\) where \(H\) changes sign), so every frequency is delayed by the same \((M-1)/2\) samples and waveform shapes are preserved. Asymmetric taps delay different frequencies by different amounts.

The four linear-phase types. Linear phase needs symmetric taps, \(h[k] = h[M-1-k]\), or antisymmetric ones, \(h[k] = -h[M-1-k]\) (which add a constant \(90°\) phase shift; same group delay). Together with odd or even \(M\) that gives four types, each with zeros it cannot avoid:

Type

Taps

\(M\)

Forced zeros

So it cannot be

I

symmetric

odd

none

(any response)

II

symmetric

even

at Nyquist (\(z = -1\))

high-pass

III

antisymmetric

odd

at DC and Nyquist (\(z = \pm 1\))

low-pass or high-pass

IV

antisymmetric

even

at DC (\(z = 1\))

low-pass

Windowed-sinc design. The ideal low-pass with cutoff \(f_c\) Hz has the infinitely long impulse response \(h_{\mathrm{ideal}}[n] = 2 (f_c/f_s)\, \mathrm{sinc}\big(2 (f_c / f_s)\, n\big)\), with \(\mathrm{sinc}(u) = \sin(\pi u)/(\pi u)\). Truncate it to \(M\) taps centred on \((M-1)/2\), multiply by a window \(w[n]\) (Hamming here) to reduce the ripples, and scale so that \(\sum_k h[k] = 1\) (unit gain at DC):

\[h[n] = c \; 2\frac{f_c}{f_s}\, \mathrm{sinc}\!\left(2 \frac{f_c}{f_s}\left(n - \frac{M-1}{2}\right)\right) w[n]\]

where \(c\) is the normalising constant. The response passes through about 0.5 (\(-6\) dB) at \(f_c\), and the transition band narrows as \(M\) grows.

With the library

AudioSamples.convolve(other) returns the full convolution (both signals mono and of the same sample type). AudioSamples.apply_filter(taps) returns the valid part (what numpy.convolve(x, h, 'valid') gives), which is the slice full[M-1:N] of the full result.

x = np.sin(0.05 * np.arange(1000))
h = np.full(31, 1 / 31)                              # 31-tap moving average
N, M = len(x), len(h)

full = mono(x).convolve(mono(h)).to_numpy()
valid = mono(x).apply_filter(h).to_numpy()
assert np.array_equal(valid, full[M - 1: N]) or np.allclose(valid, full[M - 1: N], atol=1e-12)
assert len(full) == 1030                             # N + M - 1
assert len(valid) == 970                             # N - M + 1
# NumPy and SciPy agree (rounding of 31-term sums: ~1e-15).
assert np.allclose(full, np.convolve(x, h), atol=1e-12)
assert np.allclose(valid, np.convolve(x, h, mode="valid"), atol=1e-12)
assert np.allclose(valid, ss.lfilter(h, 1.0, x)[M - 1:], atol=1e-12)
assert np.allclose(ss.lfilter(h, 1.0, x), full[:N], atol=1e-12)    # lfilter = first N samples

# Filtering an impulse returns the taps.
delta = np.zeros(64)
delta[0] = 1.0
ir = mono(delta).convolve(mono(h)).to_numpy()
assert np.allclose(ir[:31], h, atol=1e-12) and np.allclose(ir[31:], 0.0, atol=1e-12)

# The explainer classifies the taps and reports their delay.
doc = aus.explain.fir(h, 16_000.0)
assert doc.quantity("Group delay") == 15.0          # (31 - 1) / 2
assert abs(doc.quantity("DC gain") - 1.0) < 1e-12

The moving-average response, measured by filtering sines. One second of valid output (\(f_s\) samples) holds a whole number of cycles of each test tone, so projecting the output on \(\sin\) and \(\cos\) recovers its amplitude exactly.

def filter_valid(x, h, fs=FS):
    # The valid part of the convolution computed by the library.
    return mono(x, fs).apply_filter(np.asarray(h, dtype=float)).to_numpy()

def measured_gain(h, f, fs):
    n = np.arange(int(fs) + len(h) - 1)               # so the valid output is exactly fs samples
    y = filter_valid(np.sin(2 * np.pi * f * n / fs), h, int(fs))
    phi = 2 * np.pi * f * np.arange(len(y)) / fs
    return 2 / fs * np.hypot(np.sum(y * np.sin(phi)), np.sum(y * np.cos(phi)))

ma = np.full(8, 1 / 8)
fs8 = 8_000.0
for f, expected in [(250.0, 0.901764), (500.0, 0.640729), (750.0, 0.304489), (1500.0, 0.224994)]:
    u = np.pi * f / fs8
    dirichlet = abs(np.sin(8 * u) / (8 * np.sin(u)))
    g = measured_gain(ma, f, fs8)
    print(f"{f:6.0f} Hz: measured {g:.6f}, Dirichlet {dirichlet:.6f}")
    assert abs(g - dirichlet) < 1e-9                  # exact up to rounding
    assert abs(g - expected) < 1e-6
# Nulls at multiples of fs / M = 1000 Hz.
for f in [1000.0, 2000.0, 3000.0]:
    assert measured_gain(ma, f, fs8) < 1e-9
   250 Hz: measured 0.901764, Dirichlet 0.901764
   500 Hz: measured 0.640729, Dirichlet 0.640729
   750 Hz: measured 0.304489, Dirichlet 0.304489
  1500 Hz: measured 0.224994, Dirichlet 0.224994
w_, H_ = ss.freqz(ma, worN=2048, fs=fs8)
f_test = np.array([250.0, 500.0, 750.0, 1000.0, 1500.0, 2000.0, 3000.0])
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(w_, np.abs(H_), label="|H(f)| from the taps (freqz)")
ax.plot(f_test, [measured_gain(ma, f, fs8) for f in f_test], "o", label="measured with sines")
ax.set(xlabel="Frequency (Hz)", ylabel="Gain", title="8-tap moving average at 8 kHz")
ax.legend()
plt.show()
../_images/8f5db47cbc9f64825c50252887644854669f3ea4466ef7436b3255fe1d6340c4.png

How it works

The convolution sum, a group-delay calculation, and the delay seen in the time domain, all for a 63-tap windowed-sinc low-pass (\(f_c = 2\) kHz, \(f_s = 16\) kHz) designed here, since the library has no FIR designer. SciPy’s firwin is the independent reference: it builds exactly this design (symmetric Hamming window, unit DC gain).

def windowed_sinc(m, fc, fs):
    n = np.arange(m) - (m - 1) / 2
    wc = 2 * fc / fs
    h = wc * np.sinc(wc * n) * WT.make_hamming(m)
    return h / h.sum()

def convolve_full(x, h):
    # The convolution sum, written out.
    y = np.zeros(len(x) + len(h) - 1)
    for k, hk in enumerate(h):
        y[k: k + len(x)] += hk * x
    return y

def group_delay(h, omega):
    k = np.arange(len(h))
    e = np.exp(-1j * omega * k)
    return (np.sum(k * h * e) / np.sum(h * e)).real

lp = windowed_sinc(63, 2000.0, 16_000.0)
assert np.allclose(lp, lp[::-1], rtol=0, atol=1e-15)            # symmetric (to rounding)
assert np.allclose(lp, ss.firwin(63, 2000.0, window="hamming", fs=16_000), atol=1e-15)

# Direct sum versus the library: the same numbers up to the last bits of rounding.
xx = np.sin(0.05 * np.arange(1000)) + 0.3 * np.cos(0.71 * np.arange(1000))
assert np.allclose(convolve_full(xx, lp), mono(xx).convolve(mono(lp)).to_numpy(), atol=1e-12)

# Linear phase: 31 samples of delay at every passband frequency ...
for f in [100.0, 500.0, 1000.0, 1500.0]:
    assert abs(group_delay(lp, 2 * np.pi * f / 16_000) - 31.0) < 1e-9
# ... SciPy agrees ...
_, gd = ss.group_delay((lp, [1.0]), w=[100.0, 1000.0], fs=16_000)
assert np.allclose(gd, 31.0, atol=1e-6)
# ... but not for asymmetric taps: 0.7 samples at DC, 0.25 at Nyquist.
skew = np.array([0.5, 0.3, 0.2])
assert abs(group_delay(skew, 0.0) - 0.7) < 1e-12
assert abs(group_delay(skew, np.pi) - 0.25) < 1e-12
# Measured with a delayed impulse: impulse at n = 100 -> peak at 100 + 31 in the full output ...
d = np.zeros(400)
d[100] = 1.0
assert np.argmax(mono(d).convolve(mono(lp)).to_numpy()) == 131
# ... and at 131 - 62 = 69 in the valid part (its index i is time i + M - 1).
assert np.argmax(filter_valid(d, lp)) == 69

# And with a smooth pulse: its centroid moves by exactly (M - 1)/2 = 31.
pulse = np.exp(-((np.arange(400) - 150) / 12) ** 2 / 2)
centroid = lambda v: np.sum(np.arange(len(v)) * v) / np.sum(v)
assert abs(centroid(convolve_full(pulse, lp)) - centroid(pulse) - 31.0) < 1e-9

# The magnitude response, evaluated from the taps (the DTFT), and SciPy's freqz.
def gain(h, f, fs=16_000.0):
    return abs(np.sum(h * np.exp(-2j * np.pi * f / fs * np.arange(len(h)))))

db = lambda g: 20 * np.log10(g)
for f in [500.0, 1000.0, 1500.0]:
    assert abs(db(gain(lp, f))) < 0.05                  # pass band flat to 0.05 dB (max 0.03 dB)
assert abs(gain(lp, 2000.0) - 0.5005) < 1e-4            # -6.01 dB at the cutoff
assert abs(db(gain(lp, 2000.0)) - (-6.01)) < 0.005
for f in [3000.0, 4000.0, 6000.0]:
    assert db(gain(lp, f)) < -59.0                      # stop band below -59 dB from 3 kHz
_, Hz = ss.freqz(lp, worN=[2000.0, 4000.0], fs=16_000)
assert np.allclose(np.abs(Hz), [gain(lp, 2000.0), gain(lp, 4000.0)], atol=1e-12)
f_ax, H_lp = ss.freqz(lp, worN=4096, fs=16_000)
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
axes[0].stem(np.arange(63), lp)
axes[0].set(xlabel="Tap index k", ylabel="h[k]", title="63-tap windowed sinc")
axes[1].plot(f_ax, 20 * np.log10(np.abs(H_lp) + 1e-12))
axes[1].axvline(2000, ls=":", c="k")
axes[1].set(xlabel="Frequency (Hz)", ylabel="Gain (dB)", ylim=(-100, 5), title="Response (fc = 2 kHz)")
fig.tight_layout()
plt.show()
../_images/59ab212a190b94f24c00c477d8039cb146b5a52260536e876dc5f271fc4edc2f.png

The same holds for long filters: a 201-tap design convolved by the library agrees with the direct sum to better than \(10^{-12}\).

lp201 = windowed_sinc(201, 2000.0, 16_000.0)
noise = rng.standard_normal(4000)
assert np.allclose(mono(noise).convolve(mono(lp201)).to_numpy(), convolve_full(noise, lp201), atol=1e-12)

Ask the library to explain

aus.explain.fir(taps, sample_rate) classifies the taps (linear-phase types I-IV), reports the group delay, DC and Nyquist gains and a small response table, and notes when apply_filter switches to FFT convolution (from 160 taps):

ma5 = aus.explain.fir([0.2] * 5, 16_000.0)
assert ma5.quantity("Taps") == 5
assert ma5.quantity("Group delay") == 2.0                          # samples
assert abs(ma5.quantity("Group delay (time)") - 0.125) < 1e-12     # ms
assert ma5.has_warning_containing("type I")

# Even length and symmetric: type II, forced zero at Nyquist.
t2 = aus.explain.fir([0.25] * 4, 16_000.0)
assert t2.has_warning_containing("type II") and abs(t2.quantity("Nyquist gain")) < 1e-12

# Antisymmetric taps: type III (odd length) and type IV (even length), with their forced zeros.
H_abs = lambda taps, w: abs(np.sum(np.asarray(taps) * np.exp(-1j * w * np.arange(len(taps)))))
t3, t4 = [0.5, 0.0, -0.5], [0.5, -0.5]
assert aus.explain.fir(t3, 16_000.0).has_warning_containing("type III")
assert aus.explain.fir(t4, 16_000.0).has_warning_containing("type IV")
assert H_abs(t3, 0.0) < 1e-12 and H_abs(t3, np.pi) < 1e-12        # zeros at DC and Nyquist
assert H_abs(t4, 0.0) < 1e-12 and abs(H_abs(t4, np.pi) - 1.0) < 1e-12  # zero at DC only
assert H_abs([0.25] * 4, np.pi) < 1e-12                            # type II: zero at Nyquist

# Asymmetric taps: no constant group delay, only its value at DC.
sk = aus.explain.fir(skew, 16_000.0)
assert sk.quantity("Group delay") is None
assert abs(sk.quantity("Group delay at DC") - group_delay(skew, 0.0)) < 1e-12

long = aus.explain.fir(np.full(200, 1 / 200), 16_000.0)
assert long.has_warning_containing("FFT convolution")
assert aus.explain.fir(np.full(160, 1 / 160), 16_000.0).has_warning_containing("FFT convolution")
assert not aus.explain.fir(np.full(159, 1 / 159), 16_000.0).has_warning_containing("FFT convolution")
ma5

FIR filter

5 taps at 16000 Hz. The taps are symmetric (type I), so the phase is linear and every frequency is delayed by 2 samples (0.125 ms). apply_filter (Rust AudioProcessing::apply_filter, Python AudioSamples.apply_filter) returns the fully overlapping part of the convolution, 4 samples shorter than the input.

Formulas

Convolution of the input with the M taps:

$$ y[n] = \sum_{j=0}^{M-1} h[j] , x[n-j] $$

Frequency response:

$$ H(e^{j\omega}) = \sum_{j=0}^{M-1} h[j] , e^{-j \omega j}, \quad \omega = \frac{2\pi f}{f_s} $$

Symmetric or antisymmetric taps give linear phase with constant group delay:

$$ h[j] = \pm h[M-1-j] \Rightarrow \tau_g = \frac{M-1}{2} $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $M$ | number of taps | 5 | | $h[j]$ | filter taps | | | $f_s$ | sample rate | 16000 Hz |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Taps | $M$ = 5 | $M$ | | DC gain | $H(1)$ = 1 | $\sum_j h[j]$ | | Nyquist gain | $H(-1)$ = 0.2 | $\sum_j (-1)^j h[j]$ | | DC gain (dB) | $20\log_{10}\vert H(1)\vert $ = 0 dB | $20 \log_{10} \vert \sum_j h[j]\vert $ | | Group delay | $\tau_g$ = 2 samples | $(M-1)/2$ | | Group delay (time) | $\tau_g / f_s$ = 0.125 ms | $1000 (M-1) / (2 f_s)$ |

Measured magnitude response

| f (Hz) | |H| | |H| (dB) | |—|—|—| | 0 | 1 | 0 | | 2000 | 0.482843 | -6.32389 | | 4000 | 0.2 | -13.9794 | | 6000 | 0.0828427 | -21.6349 | | 8000 | 0.2 | -13.9794 |

Trade-offs

  • Linear phase preserves waveform shape (all frequencies delayed equally) at the cost of (M-1)/2 samples of latency.

  • A sharper transition band needs more taps, which lengthens the delay and the computation.

Warnings

  • Info: Linear-phase type I: symmetric, odd length.

See also

  • Apply: audio_samples::AudioProcessing::apply_filter

  • Apply (Python): audio_samples.AudioSamples.apply_filter

  • Python: audio_samples.explain.fir

Exercises

  1. Where are the nulls (Hz, below Nyquist) of a 5-tap moving average at \(f_s = 10\) kHz? Check them by filtering sines.

answer = None  # TODO
# Solution
answer = [k * 10_000 / 5 for k in (1, 2)]        # multiples of fs / M below 5 kHz
assert answer == [2000.0, 4000.0]
ma_5 = np.full(5, 0.2)
for f in answer:
    y = filter_valid(np.sin(2 * np.pi * f * np.arange(10_004) / 10_000), ma_5, 10_000)  # 10 000 outputs
    assert np.max(np.abs(y)) < 1e-12
assert gain(ma_5, 1000.0, 10_000.0) > 0.5         # but not in between
  1. You low-pass 1 s of 16 kHz audio with the 63-tap filter above and keep the valid part. How many samples come out, and which input sample \(x[i + d]\) is output sample \(i\) aligned with? (answer = (length, d).) Check with a 100 Hz sine.

answer = None  # TODO
# Solution
answer = (16_000 - 62, 31)   # output i is the causal output at time i + 62, which lags by 31
xs = np.sin(2 * np.pi * 100 * np.arange(16_000) / 16_000)
y = filter_valid(xs, lp)
assert len(y) == answer[0]
# At 100 Hz the gain is 1.0012 (pass-band ripple), so the aligned samples agree to ~1.2e-3.
assert abs(gain(lp, 100.0) - 1.0012) < 1e-4
assert np.max(np.abs(y - xs[answer[1]: answer[1] + len(y)])) < 2e-3
  1. Spectral inversion: \(h_{hp}[n] = \delta[n - (M-1)/2] - h_{lp}[n]\) turns the low-pass into a high-pass. Predict its gain at DC, at the 2 kHz cutoff and at 6 kHz, then measure.

answer = None  # TODO
# Solution
answer = (0.0, 0.5, 1.0)     # 1 - 1; |1 - 0.5| (same linear phase); 1 - (almost 0)
hp = -lp.copy()
hp[31] += 1.0
assert gain(hp, 0.0) < 1e-12
assert abs(gain(hp, 2000.0) - answer[1]) < 0.01
assert abs(gain(hp, 6000.0) - answer[2]) < 1e-3
hp_doc = aus.explain.fir(hp, 16_000.0)
assert hp_doc.has_warning_containing("type I") and hp_doc.quantity("Group delay") == 31.0

Common pitfalls

  • AudioSamples.convolve returns the full convolution (\(N + M - 1\) samples); AudioSamples.apply_filter returns the valid part (\(M - 1\) samples shorter, output \(i\) belongs to input time \(i + M - 1\)). Neither is delay-compensated: a linear-phase filter still lags by \((M-1)/2\).

  • convolve needs both signals mono and of the same sample type (generators default to float32; build taps with new_mono from a float64 array, or pass dtype).

  • Even-length symmetric filters (type II) always have a zero at Nyquist and cannot be high-pass; spectral inversion needs an odd length.

  • A windowed sinc is \(-6\) dB (not \(-3\) dB) at its design cutoff.

  • SciPy’s lfilter(h, 1, x) returns the full-length causal output (the first \(N\) samples of convolve); the valid part is lfilter(h, 1, x)[M-1:]. Compare like with like.

  • low_pass_filter / high_pass_filter / band_pass_filter are first-order IIR (Butterworth) filters, not FIR (notebook 06).

See also

  • Rust guide chapter: 05. Convolution and FIR filters (available from the next release; until then build the docs locally with cargo doc --features educational,full_no_plotting --open) and the lab examples/tutorial_05_convolution_fir.rs.

  • Python API: AudioSamples.convolve, AudioSamples.apply_filter, AudioSamples.deconvolve, aus.impulse, aus.explain.fir (API reference); SciPy: scipy.signal.firwin, freqz, group_delay.

  • Previous: 04. STFT and spectrograms. Next: 06. IIR filters.

References

  • Oppenheim, A. V. and Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson. Chapters 5 and 7 (linear-phase systems and the four generalised linear-phase FIR types; FIR design by windowing).