FIR Design by the Window Method
The Filter Specifications lesson ended with a mask: keep to within , remove everything above by , at . The simplest way to meet it with a finite impulse response (FIR) filter is the window method: take the impulse response of the ideal "brick-wall" filter, which is infinitely long, cut it to taps, and taper the cut with a window so that the truncation does not ruin the stopband. This lesson shows why the window decides the attenuation, why the length decides the transition width, how firwin and kaiserord turn a mask into taps, and how to get high-pass and band-pass filters from the same recipe. The mathematics of FIR filters and of windows is in FIR Filters and Windows.
From the ideal filter to taps
An ideal low-pass filter with cutoff passes with gain 1 and nothing else. Its impulse response (the inverse DTFT of a rectangle) is a sampled sinc, centred at so that the filter is causal:
with . Multiplying by a window in time convolves the ideal rectangle with the window's spectrum in frequency. Two things follow:
- the window's main-lobe width smears the brick-wall edge into a transition band whose width is about times , with depending on the window;
- the window's side lobes leak into the stopband and set the minimum attenuation, which depends on the window shape and not on .
Plain truncation is the rectangular ("boxcar") window: the sharpest transition but only about of attenuation, and a Gibbs overshoot near the edge that no length removes (Convergence and Gibbs). Smoother windows trade transition width for attenuation:
import numpy as np
from scipy import signal
# The same 31-tap low-pass (cutoff 1.25 kHz at fs = 8 kHz) truncated by different windows
fs, fc, N = 8000, 1250, 31
f = np.linspace(0, fs / 2, 8001)
print("window gain at 1 kHz -6 dB point first null peak sidelobe")
for win in ("boxcar", "hann", "hamming", "blackman", ("kaiser", 6.0)):
h = signal.firwin(N, fc, window=win, fs=fs)
_, H = signal.freqz(h, worN=f, fs=fs)
g = 20 * np.log10(np.maximum(np.abs(H), 1e-12))
i = np.argmax(f >= fc)
while g[i + 1] < g[i]: # walk down the main lobe to its first null
i += 1
name = win if isinstance(win, str) else f"kaiser {win[1]:.0f}"
f6 = f[np.argmax(g < -6.0206)]
print(f"{name:10s} {g[f == 1000][0]:7.3f} dB {f6:6.0f} Hz {f[i]:6.0f} Hz {g[i:].max():6.1f} dB")window gain at 1 kHz -6 dB point first null peak sidelobe
boxcar 0.492 dB 1244 Hz 1404 Hz -21.8 dB
hann -0.997 dB 1250 Hz 1696 Hz -43.9 dB
hamming -0.863 dB 1250 Hz 1722 Hz -50.6 dB
blackman -1.492 dB 1250 Hz 2181 Hz -75.2 dB
kaiser 6 -1.034 dB 1250 Hz 1777 Hz -61.7 dB
Read the table by columns. All windows place the point at the design cutoff (): firwin's cutoff is where the gain is , not the point of analog filters. The first null moves out as the side lobes go down: the Blackman window has the deepest stopband but the widest transition. The Kaiser window has a parameter that slides continuously along this trade-off, which is why it is the default for designing to a specification.
| Window | Filter's peak stopband lobe (typical) | Transition width, about | Use |
|---|---|---|---|
| rectangular | almost never for filters | ||
| Hann | modest attenuation | ||
| Hamming | classic default | ||
| Blackman | high attenuation, longer filter | ||
| Kaiser () | chosen | from | design to a mask |
(The transition widths are the usual textbook rules of thumb; the side-lobe levels measured above for differ by a few dB.)
Kaiser's design formulas
For an attenuation in dB, Kaiser found that
signal.kaiserord(As, width) returns both, with the width as a fraction of the Nyquist frequency . Put the cutoff in the middle of the transition band, , because the window spreads the edge symmetrically around it.
Worked example: the vibration-channel low-pass
Given: , , , (passband ripple allowed).
Find: , the number of taps, the gains at the band edges and the delay; then check the filter on a signal with a interferer.
Solve: . , so , rounded up by kaiserord to 60 taps. Cutoff . Delay samples .
import numpy as np
from scipy import signal
fs, fp, fst, As = 8000, 1000, 1500, 60.0
numtaps, beta = signal.kaiserord(As, (fst - fp) / (fs / 2))
h = signal.firwin(numtaps, (fp + fst) / 2, window=("kaiser", beta), fs=fs)
print(f"{numtaps} taps, beta = {beta:.3f}, symmetric: {np.allclose(h, h[::-1])}, sum of taps (DC gain) = {h.sum():.5f}")
print("centre taps:", np.round(h[27:33], 5))
_, H = signal.freqz(h, worN=[0, 500, 1000, 1250, 1500, 2000, 3000], fs=fs)
for fk, Hk in zip([0, 500, 1000, 1250, 1500, 2000, 3000], H):
print(f" {fk:5d} Hz: {20 * np.log10(abs(Hk)):8.2f} dB")
print(f"delay = {(numtaps - 1) / 2} samples = {1e3 * (numtaps - 1) / 2 / fs:.3f} ms")
# Filter a 300 Hz signal with a 2 kHz interferer and compare after removing the delay
t = np.arange(800) / fs
x = np.sin(2 * np.pi * 300 * t) + 0.5 * np.sin(2 * np.pi * 2000 * t)
y = signal.lfilter(h, 1, x)
D = (numtaps - 1) / 2 # 29.5 samples: compare with the input delayed by that much
ideal = np.sin(2 * np.pi * 300 * (t - D / fs))
err = y[100:] - ideal[100:]
print(f"rms error after the transient: {np.sqrt(np.mean(err**2)):.5f} (interferer was 0.35355 rms)")60 taps, beta = 5.653, symmetric: True, sum of taps (DC gain) = 1.00000
centre taps: [0.07927 0.20973 0.29979 0.29979 0.20973 0.07927]
0 Hz: 0.00 dB
500 Hz: 0.00 dB
1000 Hz: -0.01 dB
1250 Hz: -6.02 dB
1500 Hz: -66.60 dB
2000 Hz: -72.66 dB
3000 Hz: -74.05 dB
delay = 29.5 samples = 3.688 ms
rms error after the transient: 0.00010 (interferer was 0.35355 rms)
Check: the taps are symmetric (linear phase) and sum to 1 (unit DC gain). The passband edge loses only and the stopband edge is down, inside the mask with a margin. After removing the -sample delay, the output differs from the clean sine by rms: the interferer ( rms) is suppressed by about . An even number of taps gives a half-sample delay, harmless here; choose an odd when the output must line up with other signals on whole samples.
High-pass, band-pass and band-stop
The same recipe gives the other types. A high-pass is an all-pass delay minus a low-pass ("spectral inversion"), a band-pass is the difference of two low-passes, and a band-stop is a delay minus a band-pass. firwin does this when you pass pass_zero=False or a list of edges. A high-pass or band-stop needs an odd number of taps: an even-length symmetric FIR always has a zero at (type II, see Equiripple FIR).
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
fs = 16000
hp = signal.firwin(81, 1000, pass_zero=False, window="hamming", fs=fs) # high-pass: odd length needed
bp = signal.firwin(81, [300, 3400], pass_zero=False, window="hamming", fs=fs) # telephone band-pass
lp = signal.firwin(81, 1000, window="hamming", fs=fs)
inv = -lp
inv[40] += 1 # spectral inversion: delta - lowpass
print(f"high-pass vs delta minus low-pass: max tap difference {np.abs(hp - inv).max():.1e}")
fk = [100, 300, 1000, 2000, 3400, 6000]
for name, h in (("high-pass 1 kHz", hp), ("band-pass 300-3400", bp)):
_, H = signal.freqz(h, worN=fk, fs=fs)
print(f"{name:18s}", " ".join(f"{f}: {round(20 * np.log10(abs(v)), 1) + 0.0:6.1f}" for f, v in zip(fk, H)), "dB")
f, H1 = signal.freqz(hp, worN=2048, fs=fs)
_, H2 = signal.freqz(bp, worN=2048, fs=fs)
plt.figure(figsize=(7, 3.2))
plt.plot(f, 20 * np.log10(np.abs(H1) + 1e-9), label="high-pass 1 kHz")
plt.plot(f, 20 * np.log10(np.abs(H2) + 1e-9), label="band-pass 300-3400 Hz")
plt.ylim(-90, 5); plt.xlabel("frequency (Hz)"); plt.ylabel("gain (dB)")
plt.grid(alpha=0.3); plt.legend(); plt.title("81-tap Hamming-window FIR filters, fs = 16 kHz")
plt.tight_layout(); plt.show()high-pass vs delta minus low-pass: max tap difference 4.1e-04
high-pass 1 kHz 100: -94.4 300: -77.9 1000: -6.0 2000: 0.0 3400: 0.0 6000: 0.0 dB
band-pass 300-3400 100: -22.4 300: -6.0 1000: 0.0 2000: 0.0 3400: -6.0 6000: -101.8 dB
The high-pass is minus the low-pass, except for a tiny rescaling (firwin scales a high-pass to exactly unit gain at ). The band-pass edges sit at , again by construction; widen the design edges if the band edges must be within . With 81 taps at , the transition from down to achieves only : low-frequency edges need many taps at a high sampling rate, a problem that decimation solves.
Guided lab: hearing the window
Hand calculation. For a 31-tap filter at with , the rectangular window leaves side lobes near ; a tone happens to fall where the gain is (about ). The Hamming window gives at the same frequency (about ). Add 2000 to a freqz call to confirm both.
Simulation. Change N and the window list in the first program. Doubling halves the transition width (first null moves toward ) but leaves the side-lobe levels where they are.
What you would measure. Load both filters into a USB audio interface or a microcontroller board running at , feed a sine of amplitude, and read the output on a scope. Expect about with the rectangular window and about with Hamming; the second is near or below the noise of a typical 12-bit or audio-codec output, so average the scope's FFT. Uncertainty: about in the passband (generator and converter gains), a few dB at because of noise.
Hazards and safe setup. Low-voltage signals only: a function generator and a USB-powered board or interface. Keep the generator below the input's full scale, set the level with the output disabled, and use headphones at low volume if you listen.
Pitfalls
- Expecting a longer rectangular-window filter to reach more attenuation: the side lobes stay at about for any .
- Reading
firwin's cutoff as a frequency: it is the (half-amplitude) point. - Designing a high-pass with an even number of taps (SciPy refuses; the response would be zero at ).
- Forgetting the delay when comparing input and output, or when the filter sits in a control loop.
- Writing the cutoff in hertz without
fs=: SciPy then reads it as a fraction of Nyquist.
Practice
- Find and the Kaiser length for and .
- A Hamming-window low-pass needs a transition of at . Estimate .
- Why must a linear-phase FIR high-pass have an odd number of taps?
Answer
- ; , so 102 taps.
- taps.
- An even-length symmetric impulse response has (the terms cancel in pairs at ), so its gain at is forced to zero.
Test yourself
In the window method, the minimum stopband attenuation is set mainly by
- the number of taps
- the window shape
- the sampling rate
- the cutoff frequency
firwin(N, fc, fs=fs) places at the frequency where the gain is
- dB
- dB
- dB
- dB
For dB, Kaiser's is about
- 0
- 3.4
- 5.65
- 8.7
A 60-tap linear-phase FIR at 8 kHz delays every frequency by
- 7.5 ms
- 3.69 ms
- 60 samples
- depends on frequency