FIR design: windows, frequency sampling and Parks-McClellan
| Problem | Find the taps of a linear-phase finite impulse response filter whose frequency response approximates a desired one |
| Devised by | Window method: James Kaiser (1966, 1974), the Kaiser window and design formulas; frequency sampling: Lawrence Rabiner, Bernard Gold and C. A. McGonegal (1970); equiripple design: Thomas Parks and James McClellan (1972), with Lawrence Rabiner (1973), after Evgeny Remez (1934) |
| Accuracy | firwin, firwin2 and remez agree with SciPy to , and (remez stops on a grid, as SciPy’s does) |
| Cost | Window and frequency sampling: and . Parks-McClellan: per exchange for a grid of points, typically under ten exchanges |
| Read first | Background: frequency responses, Window functions |
| API | firwin, firwin2, remez (RemezFilterType), kaiser_beta, kaiser_atten, kaiser_estimate_numtaps, generate_derivative_taps, BoxcarIntegrator |
Overview
A finite impulse response filter is a set of taps , applied by convolution. FIR filters are always stable, and when the taps are symmetric or antisymmetric about their centre they have exactly linear phase, a pure delay of samples at every frequency, which no causal IIR filter can achieve. Their cost is length: matching a sharp IIR filter takes many more taps. Three design methods cover most needs:
- windowing truncates the ideal (infinite) impulse response and tapers it with a window;
- frequency sampling specifies the response on a dense grid and inverts the DFT;
- Parks-McClellan finds the taps that minimise the largest weighted error, an equiripple design that is optimal in that sense.
Where it is used
FIR filters are always stable and can have exactly linear phase, so they are the default when the shape of a waveform must be preserved.
- Audio. Crossovers, equalisers and sample-rate converters are FIR filters, often designed by windows or Parks-McClellan.
- Communications. Pulse-shaping filters (root-raised-cosine) and channel-selection filters in digital radios.
- Biomedical signals. ECG and EEG processing uses linear-phase filters so that the timing of features such as the QRS complex is not distorted.
- Image processing. Many 2-D filters are separable FIR kernels.
History
The window method is as old as digital filtering. James Kaiser (1966) introduced the Bessel-function window that bears his name,
whose single parameter trades main-lobe width against side-lobe level, and (1974) empirical formulas for its parameter and the
filter length. Lawrence Rabiner, Bernard Gold and C. A. McGonegal (1970) developed frequency-sampling design. Thomas Parks and
James McClellan (1972), at Rice University, recognised that the optimal linear-phase design is a Chebyshev approximation problem
and solved it with Evgeny Remez’s exchange algorithm (1934). Their FORTRAN program, with Lawrence Rabiner (1973), became the
standard design tool, and SciPy’s remez is a direct descendant.
The idea
Linear phase and the four types
Why symmetry matters. A filter delays the signals passing through it, and in general it delays different frequencies by different amounts, which distorts the shape of a pulse. A filter that delays every frequency by the same amount only shifts the signal in time. Such a filter has a phase that is a linear function of frequency, and is said to have linear phase. FIR filters can achieve this exactly, simply by making their taps symmetric.
To see why, take five symmetric taps, . In the frequency response , factor out the delay to the centre tap, , and pair each tap with its mirror image:
The bracket is real. So the response is a real amplitude times a pure delay of two samples, half the filter’s span. In general a symmetric filter of length has
a delay of samples at every frequency. Designing the filter reduces to designing the real function .
The four types. The same pairing works when the taps are antisymmetric (), giving sines instead of cosines (and an extra factor ). The length may be odd or even. These choices give four types, and the symmetry of each forces its amplitude to vanish at certain frequencies, which limits what it can be used for:
| Type | Taps | Length | is forced to zero at | Suits |
|---|---|---|---|---|
| I | symmetric | odd | nowhere | any response |
| II | symmetric | even | low-pass, band-pass | |
| III | antisymmetric | odd | and | Hilbert transformers, band-pass |
| IV | antisymmetric | even | differentiators, Hilbert transformers, high-pass |
A type II filter, for example, cannot be a high-pass filter, because its gain at the Nyquist frequency is always zero.
Every type can be written , where is a polynomial in and is a fixed factor, equal to , , or for types I to IV, that accounts for the forced zeros. This is how one optimisation algorithm serves all four: it always designs the polynomial .
The window method
The simplest design method starts from the ideal answer and makes it realisable.
The ideal filter. An ideal low-pass filter has gain 1 up to the cutoff and 0 beyond. Its impulse response is the inverse Fourier transform of that rectangular shape,
which extends for ever in both directions and decays only like . It cannot be used as it stands.
Truncation and its cost. The obvious fix is to keep only the central taps. Keeping some taps and discarding the rest is the same as multiplying by a rectangular window that is 1 on those taps and 0 elsewhere. Multiplication in time corresponds to convolution in frequency: the response of the truncated filter is the ideal rectangle smeared by the Fourier transform of the window. The transform of a rectangular window is a narrow main lobe flanked by side lobes that decay slowly. Smearing with it has two effects. The sharp edge of the ideal response becomes a transition band about as wide as the main lobe. And the side lobes produce ripple on both sides of the edge: an overshoot of 9% however large is (the Gibbs phenomenon), and a stopband whose first side lobe is only 21 dB down.
Better windows. The side lobes come from the abrupt ends of the rectangular window. A window that tapers smoothly to zero at its ends has much lower side lobes, at the price of a wider main lobe. Multiplying by such a window instead trades a wider transition band for a cleaner stopband:
Figure 14.13. Window-method filters.
firwin builds the ideal response from sinc functions, one difference of two per band, applies the window, and scales the result to unit gain at the
centre of the first passband. Its window can be any of the library’s
window functions, which a later chapter treats in detail.
Kaiser’s formulas
The Kaiser window has a parameter that sets the stopband attenuation (in dB) independently of the length, and the length then sets the transition width . Kaiser fitted
These make window design a recipe: choose and , read off and . They are accurate to about a decibel:
Table 14.7. Kaiser-window designs: estimated taps and β against measured attenuation.
| target attenuation (dB) | transition width (× Nyquist) | taps (kaiser_estimate_numtaps) | β (kaiser_beta) | stopband attenuation achieved (dB) | passband ripple achieved (dB below 1) |
|---|---|---|---|---|---|
| 40 | 0.1 | 47 | 3.395 | 40.8 | 39.7 |
| 60 | 0.1 | 75 | 5.653 | 59.9 | 59.7 |
| 80 | 0.05 | 203 | 7.857 | 79.6 | 79.3 |
| 100 | 0.05 | 259 | 10.061 | 100.5 | 99.6 |
The passband ripple of a window design equals its stopband ripple, so a 60 dB filter also has 60 dB passband accuracy, whether that is needed or not.
Frequency sampling
firwin2 takes a piecewise-linear desired gain, given at a list of frequencies (with repeated frequencies for jumps). It interpolates it onto a dense grid,
attaches the linear-phase factor, inverse-transforms by FFT, and windows the result. Any shape can be specified:
Figure 14.14. Frequency sampling.
More taps follow the specification more closely, but discontinuities still ring.
Parks-McClellan: equiripple design
Window designs are simple but not optimal. Their error is spread unevenly: largest near the band edges, and far smaller than necessary elsewhere. A filter that meets a specification with the fewest taps should not waste accuracy in this way. The minimax design chooses the taps to minimise the largest weighted error over the bands of interest,
where is the desired amplitude (1 in a passband, 0 in a stopband), the actual amplitude, and a weight that sets the relative importance of the bands. The transition bands are left out: no error is counted there.
What the optimum looks like. A classical theorem of approximation theory describes the solution. By Chebyshev’s alternation theorem, a polynomial of degree (in ) is the minimax approximation if and only if its weighted error reaches its maximum magnitude at least times, with alternating signs. Intuitively, if the error peaks were not all equal, the polynomial could be adjusted to lower the highest peak at the expense of the others. At the optimum no such improvement is possible: all the peaks are level. The error is equiripple.
Finding it. The theorem turns an optimisation problem into a search for the right frequencies. Remez’s exchange algorithm does the search:
- Guess reference frequencies.
- Solve for the polynomial whose weighted error is exactly , with alternating signs, at those frequencies. This is a linear problem in the coefficients and ; a closed formula gives , and barycentric Lagrange interpolation gives the polynomial.
- Evaluate the error on a dense grid of frequencies. Between the reference points it generally exceeds somewhere. Move the reference frequencies to the local extrema of the error.
- Repeat until the reference stops changing. The error then alternates between equal extremes, and by the theorem the filter is optimal.
Figure 14.15. Equiripple against window.
At the same length, the equiripple filter has a sharper transition and an even stopband; the window design’s side lobes fall away where no attenuation was needed. For a fixed transition, Parks-McClellan reaches more attenuation from the same number of taps:
Table 14.8. Stopband attenuation of Parks-McClellan and Kaiser-window designs of equal length.
| taps (transition 0.2–0.3 × Nyquist) | Parks-McClellan stopband (dB) | Kaiser window stopband (dB) |
|---|---|---|
| 21 | 24.9 | 21.2 |
| 31 | 32.3 | 25.7 |
| 41 | 39.3 | 31.5 |
| 61 | 56.1 | 40.5 |
| 81 | 69.6 | 54.2 |
The implementation follows Parks, McClellan and Rabiner for all four types and matches SciPy on six reference designs. A simplified exchange stops well short of the optimum: on a 51-tap low-pass filter such a version was 12 times worse than SciPy’s (−65 dB against −87 dB).
Differentiators and integrators
An ideal differentiator has . remez with RemezFilterType::Differentiator designs one up to a chosen band edge, weighting the error by so that it is relative;
its desired value is a slope per cycle per sample, as in SciPy. generate_derivative_taps instead smooths a central difference, for derivatives of noisy
data. It is accurate at low frequencies only, and suppresses the rest:
Figure 14.16. Differentiators.
The BoxcarIntegrator is the opposite case, a moving sum of the last samples computed with one addition and
one subtraction per sample, whatever .
Algorithm
firwin (window method), for taps and a list of passbands, with frequencies as
fractions of the Nyquist frequency.
- For each tap , compute its offset from the centre, .
- For each passband , add to the tap: the ideal response of a band is the difference of two ideal low-pass responses.
- Multiply the taps by the window.
- Scale all the taps so that the gain at the centre of the first passband is exactly 1.
firwin2 (frequency sampling), for a desired gain given at a list of frequencies.
- Interpolate the gain linearly onto a grid of equally spaced frequencies from zero to Nyquist.
- Multiply by the linear-phase factor (and by for an antisymmetric filter), which centres the impulse response on the middle of the taps.
- Apply an inverse real FFT and keep the first values.
- Multiply by the window.
remez (Parks-McClellan), for taps and a desired gain and weight on each band.
- Grid. Lay a dense grid over the bands, about 16 points for each extremal frequency.
- Reduce to a polynomial problem. On the grid, divide the desired response by the type’s fixed factor and multiply the weight by it. The remaining problem is to fit a polynomial in .
- Exchange. Starting from equally spaced reference points, repeat: compute and the interpolating polynomial for the current reference; evaluate the weighted error on the whole grid; replace the reference by the local extrema of the error. Stop when the reference does not change.
- Recover the taps. Sample the optimal amplitude at equally spaced frequencies and apply an inverse DFT.
Implementation
let mut h = vec![0.0; numtaps];
let alpha = 0.5 * (numtaps as f64 - 1.0);
for band in c.as_chunks::<2>().0 {
let left = band[0];
let right = band[1];
for (n, hn) in h.iter_mut().enumerate() {
let m = n as f64 - alpha;
*hn += right * sinc(right * m) - left * sinc(left * m);
}
}
let win = if let Some(w) = width {
let atten = kaiser_atten(numtaps, w / nyq);
windows::kaiser(numtaps, windows::kaiser_beta(atten), true)
} else {
windows::generate_window(window, numtaps, true)
};
for (hn, wn) in h.iter_mut().zip(win.iter()) {
*hn *= *wn;
}
// Start from reference points spread evenly over the grid.
let mut ext: Vec<usize> = (0..needed).map(|i| i * (grid.f.len() - 1) / (needed - 1)).collect();
let mut interpolant: (Vec<f64>, Vec<f64>, Vec<f64>);
let mut iterations = 0;
loop {
iterations += 1;
// Levelled error δ on the reference: P(x_k) = D_k − (−1)^k δ / W_k for all k.
let xs: Vec<f64> = ext.iter().map(|&i| x[i]).collect();
let b = barycentric_weights(&xs);
let (mut num, mut den) = (0.0, 0.0);
for (k, &i) in ext.iter().enumerate() {
let s = if k % 2 == 0 { 1.0 } else { -1.0 };
num += b[k] * grid.desired[i];
den += b[k] * s / grid.weight[i];
}
let delta = num / den;
// Interpolate P through all but the last reference point.
let nodes = xs[..functions].to_vec();
let values: Vec<f64> = ext[..functions]
.iter()
.enumerate()
.map(|(k, &i)| grid.desired[i] - if k % 2 == 0 { 1.0 } else { -1.0 } * delta / grid.weight[i])
.collect();
let weights = barycentric_weights(&nodes);
let err: Vec<f64> = (0..grid.f.len()).map(|i| grid.weight[i] * (grid.desired[i] - barycentric(x[i], &nodes, &weights, &values))).collect();
interpolant = (nodes, weights, values);
match new_extremals(&err, &grid.band, delta, needed) {
Some(next) if next != ext && iterations < maxiter.max(1) => ext = next,
_ => break,
}
}
- The weighted error’s local extrema are found with signed comparisons, so an extremum at a band edge next to a sign change is not missed.
- A reference point whose error rounding puts a hair below (possible when is tiny, as for differentiators) is still accepted.
remezfrequencies are in the units offs;firwinandfirwin2likewise, withfs = 2meaning fractions of Nyquist.
In practice
//! FIR design three ways: Kaiser window, Parks-McClellan and frequency sampling.
use lib_jsl_dsp::discrete::filters::firwin::{FirwinPassZero, firwin};
use lib_jsl_dsp::discrete::filters::firwin2::firwin2;
use lib_jsl_dsp::discrete::filters::remez::{RemezFilterType, remez};
use lib_jsl_dsp::discrete::spectral::freqz::{FreqzWorN, freqz};
use lib_jsl_dsp::discrete::windows::{WindowType, kaiser_beta, kaiser_estimate_numtaps};
/// The smallest stopband attenuation (dB) from `from` to Nyquist (frequencies × Nyquist).
fn stopband(h: &[f64], from: f64) -> f64 {
let w: Vec<f64> = (0..2000).map(|i| std::f64::consts::PI * (from + (1.0 - from) * i as f64 / 1999.0)).collect();
let r = freqz(h, None, Some(FreqzWorN::Frequencies(w)), None, None, None).unwrap();
r.h.iter().map(|v| -20.0 * v.norm().log10()).fold(f64::INFINITY, f64::min)
}
fn main() {
// Lowpass: pass below 0.2, stop above 0.3 (× Nyquist), 60 dB.
let n = kaiser_estimate_numtaps(60.0, 0.1) | 1;
let kaiser = firwin(n, &[0.25], None, WindowType::Kaiser { beta: kaiser_beta(60.0) }, FirwinPassZero::True, true, 2.0).unwrap();
println!("Kaiser window: {n} taps, stopband {:.1} dB", stopband(&kaiser, 0.3));
for taps in [41, 51, 61] {
let pm = remez(taps, &[0.0, 0.2, 0.3, 1.0], &[1.0, 0.0], Some(&[1.0, 10.0]), RemezFilterType::Bandpass, 25, 16, 2.0).unwrap();
println!("Parks-McClellan: {taps} taps, stopband {:.1} dB", stopband(&pm, 0.3));
}
// An arbitrary response: a gentle high-frequency boost.
let boost = firwin2(41, &[0.0, 0.5, 1.0], &[1.0, 1.0, 2.0], None, Some(WindowType::Hamming), false, 2.0).unwrap();
let r = freqz(&boost, None, Some(FreqzWorN::Frequencies(vec![0.0, 0.5 * std::f64::consts::PI, 0.9 * std::f64::consts::PI])), None, None, None).unwrap();
println!("firwin2 boost: gains {:.3} at 0, 0.5 and 0.9 × Nyquist", r.h.mapv(|v| v.norm()));
}
Kaiser window: 75 taps, stopband 60.4 dB
Parks-McClellan: 41 taps, stopband 50.2 dB
Parks-McClellan: 51 taps, stopband 58.6 dB
Parks-McClellan: 61 taps, stopband 64.9 dB
firwin2 boost: gains [1.000, 1.027, 1.800] at 0, 0.5 and 0.9 × Nyquist
With the stopband weighted ten times the passband, Parks-McClellan meets 60 dB with about 55 taps, where the Kaiser window needs 75.
Strengths
- Always stable, exactly linear phase, and simple to apply with FFT methods.
- Arbitrary responses (
firwin2) and optimal equiripple designs (remez), including differentiators and Hilbert transformers.
Weaknesses
- Many more taps than an IIR filter of similar sharpness, and a delay of half the length.
remezcan fail to converge for very long filters or awkward band specifications; very wide transition bands give poorly controlled responses there.
Exercises
- Show that a symmetric filter of even length has .
- Derive the window-method taps for an ideal band-pass filter from two low-pass filters.
- Explain why the passband and stopband ripples of a window design are equal.
- State the alternation theorem, and check it numerically on a
remezdesign by counting the extrema of its weighted error. - Design a 31-tap Hilbert transformer with
remezand compare its magnitude with that of a windowed ideal Hilbert impulse response .
Hints and answers
- For even length and symmetry , and each cosine argument at is an odd multiple of , so .
- A band-pass between and is the difference of two ideal low-passes: with , then multiply by the window.
- The window method multiplies the ideal response by , which convolves its frequency response with ; the result is a symmetric convolution, so the ripple on either side of the transition is mirrored.
- The alternation theorem says the optimal weighted-Chebyshev approximation has at least alternating extrema of equal height, where is the number of free coefficients; count the extrema of the weighted error in each band including the band edges.
- Compare the equiripple design’s passband and stopband errors with the windowed one; the Remez design has a flat ripple and typically a narrower transition for the same length.
Further reading
- T. W. Parks and J. H. McClellan, “Chebyshev approximation for nonrecursive digital filters with linear phase”, IEEE Transactions on Circuit Theory 19 (1972) 189–194.
- J. H. McClellan, T. W. Parks and L. R. Rabiner, “A computer program for designing optimum FIR linear phase digital filters”, IEEE Transactions on Audio and Electroacoustics 21 (1973) 506–526.
- J. F. Kaiser, “Nonrecursive digital filter design using the I₀-sinh window function”, Proceedings of the IEEE International Symposium on Circuits and Systems (1974) 20–23.
- A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010, sections 7.5–7.8.