IIR structures: direct forms, biquads, notch, peak and comb filters
| Problem | Run a recursive filter sample by sample; design the small special-purpose filters that remove or isolate single frequencies and their harmonics |
| Devised by | The direct forms and their transposes date from the first digital filters (James Kaiser, 1960s); Leland Jackson (1970), roundoff analysis; Robert Bristow-Johnson (1990s), the “audio EQ cookbook” biquads; Sophocles Orfanidis (1996), the notch, peak and comb designs used by SciPy |
| Accuracy | Notch, peak and comb coefficients agree with SciPy exactly; filtering agrees with SciPy’s lfilter to |
| Cost | multiply-adds per sample for order |
| Read first | Digital IIR design by the bilinear transform |
| API | DiscreteLinearFilter (new(b, a), step, StreamOperator), BiquadFilter, BiquadCoefficients (lowpass), iirnotch, iirpeak, iircomb |
Overview
A transfer function says what a filter does, not how to compute it. The same can be realised by different arrangements of delays, multipliers and adders, called structures. In exact arithmetic they are equivalent; in floating point they differ in rounding error, in sensitivity to the coefficients, and in memory. This entry covers the direct forms, the second-order section (biquad) from which robust high-order filters are built, and three small designs that are widely used on their own: the notch that removes one frequency, the peak that isolates one, and the comb that acts on a frequency and all its harmonics.
Where it is used
How a filter is organised in arithmetic matters as much as its coefficients.
- Biquads in audio. Parametric equalisers, notch filters that remove 50/60 Hz mains hum, peaking filters and shelving filters are all single biquad sections.
- Comb filters. Used in reverberators, flangers and chorus effects, and to cancel periodic interference.
- Fixed-point hardware. DSP chips and FPGAs use cascaded second-order sections because high-order direct forms lose accuracy.
History
The first digital filters, in the 1960s at Bell Labs and MIT, were programmed directly from the difference equation. Analysis of
their finite-precision behaviour followed quickly: James Kaiser (1965) showed how sensitive high-order direct forms are to coefficient
quantisation, and Leland Jackson (1970) analysed roundoff noise and recommended cascades of second-order sections. Second-order
sections remain the standard, from SciPy’s sosfilt to audio equalisers built from Robert Bristow-Johnson’s “cookbook” formulas.
The notch, peak and comb designs in SciPy follow Sophocles Orfanidis’s Introduction to Signal Processing (1996).
The idea
Direct forms
The difference equation
can be computed literally, with delay lines for past inputs and past outputs (direct form I), or by sharing a single delay line of length
(direct form II). DiscreteLinearFilter uses the transposed direct form II, the structure of SciPy’s lfilter, which keeps state
variables and updates them as
The state is a running sum of partial products. Each new input and output enters every state variable in one step, which keeps
intermediate values small. new divides all coefficients by , as lfilter does. (Before this chapter was written it assumed silently.)
Coefficient sensitivity
The poles are the roots of , and the roots of a polynomial can be extremely sensitive to its coefficients. This is worst when poles cluster, as they do near in a narrow low-pass filter. Rounding the denominator of Butterworth designs to single precision:
Table 14.4. Pole movement of Butterworth filters when the coefficients are rounded to single precision.
| Butterworth order | cutoff (× Nyquist) | largest pole radius | after rounding a to f32 | |
|---|---|---|---|---|
| 4 | 0.2 | 0.795449 | 0.795449 | stable |
| 8 | 0.2 | 0.891208 | 0.891229 | stable |
| 8 | 0.05 | 0.969933 | 1.022031 | unstable |
| 12 | 0.05 | 0.979785 | 1.376727 | unstable |
| 16 | 0.05 | 0.984783 | 1.674771 | unstable |
A narrow eighth-order filter becomes unstable from rounding in the seventh significant digit. The same problem appears in double
precision for higher orders: NumPy’s roots puts a pole of the 16th-order design at radius 1.07, outside the unit circle, from the
exact double-precision coefficients. The remedy is to factor the filter into second-order sections , each with two poles, so that every
pole is set by a quadratic, whose roots are well conditioned. The library designs filters in zero-pole-gain form, and
zpk2sos and sosfilt
turn a design into such a cascade and apply it; Second-order sections and zero-phase filtering develops this.
BiquadFilter runs a single section in direct form I, sample by sample.
Notch and peak filters
A notch at places a pair of zeros on the unit circle at and a pair of poles just inside them, at radius . Away from the poles cancel the zeros’ effect and the gain is 1; near the zeros win. The closer is to 1, the narrower the notch. In Orfanidis’s design, the 3 dB bandwidth is set by the quality factor :
The peak filter is its complement, , a resonator with unit gain at .
Figure 14.9. Notch and peak filters.
Comb filters
Replacing by repeats a response times around the unit circle. A comb notch filter with removes and every harmonic of it, the shape of mains hum and of other periodic interference:
Figure 14.10. Comb filter.
iircomb requires to divide exactly, since must be an integer, and by default it also places a notch at DC (set pass_zero to pass DC instead).
Algorithm
Filtering in transposed direct form II. The state is numbers , where is the larger of the two orders, initially zero. Missing coefficients count as zero. For each input sample :
- compute the output ;
- update the state, for in increasing order: , with taken as zero.
Each sample costs about multiplications. The order of the updates matters: each is computed from the old , which has not yet been overwritten.
Notch filter at frequency with quality factor :
- convert to radians per sample, , and compute the bandwidth ;
- compute ;
- the numerator is and the denominator .
The peak filter has the same denominator and the numerator .
Comb filter removing and its harmonics:
- , which must be an integer;
- compute the bandwidth as above and ;
- form a numerator and a denominator that are nonzero only at the powers and , with constants that depend on and on whether a notch or a peak comb is wanted.
Implementation
pub fn step(&mut self, sample: &T) -> T {
let order = self.delay.len();
// d[0] is added directly to output
let d0 = if order > 0 { self.delay[0] } else { T::zero() };
// Output
let y = self.b[0] * *sample + d0;
// Update delay registers
// d[k] = d[k+1] + b[k+1]*x − a[k+1]*y
for k in 0..order {
let next_d = if k + 1 < order {
self.delay[k + 1]
} else {
T::zero()
};
// b[k+1] or 0
let bkp1 = if k + 1 < self.b.len() {
self.b[k + 1]
} else {
T::zero()
};
// a[k+1] or 0
let akp1 = if k + 1 < self.a.len() {
self.a[k + 1]
} else {
T::zero()
};
self.delay[k] = next_d + bkp1 * *sample - akp1 * y;
}
y
}
let normalized_w0 = 2.0 * w0 / fs;
let normalized_bw = normalized_w0 / q;
// The Orfanidis/SciPy implementation then works in radians per sample.
let bw = normalized_bw * PI;
let w0_rad = normalized_w0 * PI;
// For the notch case, the -3 dB bandwidth simplification gives a compact
// expression for `beta`. This is what SciPy uses internally.
let beta = (bw * 0.5).tan();
let gain = 1.0 / (1.0 + beta);
// Numerator zeros sit exactly on the unit circle at the notch frequency.
// The denominator poles pull slightly inward according to `Q`, which sets
// the notch sharpness.
let beta_coeffs = vec![
Complex::new(gain, 0.0),
Complex::new(-2.0 * gain * w0_rad.cos(), 0.0),
Complex::new(gain, 0.0),
];
let alpha_coeffs = vec![
Complex::new(1.0, 0.0),
Complex::new(-2.0 * gain * w0_rad.cos(), 0.0),
Complex::new(2.0 * gain - 1.0, 0.0),
];
DiscreteLinearFilterworks for real and complex samples, and as aStreamOperatorfor blocks.- The designs return
BilinearResultwith complex coefficients; take the real parts for real filtering. BiquadCoefficients::lowpassuses the cookbook formulas with the cutoff in cycles per sample, in .
In practice
//! Removing mains hum with a notch filter and its harmonics with a comb filter.
use lib_jsl_dsp::discrete::filters::discrete_linear_filter::DiscreteLinearFilter;
use lib_jsl_dsp::discrete::filters::iir_comb::{IirCombFilterType, iircomb};
use lib_jsl_dsp::discrete::filters::iir_notch::iirnotch;
use std::f64::consts::PI;
fn main() {
let fs = 1000.0;
// A 23 Hz "signal" plus 50 Hz hum and its third harmonic.
let x: Vec<f64> = (0..4000)
.map(|n| {
let t = n as f64 / fs;
(2.0 * PI * 23.0 * t).sin() + 0.5 * (2.0 * PI * 50.0 * t).sin() + 0.2 * (2.0 * PI * 150.0 * t).sin()
})
.collect();
let clean: Vec<f64> = (0..4000).map(|n| (2.0 * PI * 23.0 * n as f64 / fs).sin()).collect();
let error = |y: &[f64]| (y[2000..].iter().zip(&clean[2000..]).map(|(a, b)| (a - b).powi(2)).sum::<f64>() / 2000.0).sqrt();
let run = |b: Vec<f64>, a: Vec<f64>| {
let mut f = DiscreteLinearFilter::new(&b, &a);
x.iter().map(|v| f.step(v)).collect::<Vec<f64>>()
};
let notch = iirnotch(50.0, 30.0, Some(fs)).unwrap();
let y = run(notch.beta.iter().map(|c| c.re).collect(), notch.alpha.iter().map(|c| c.re).collect());
println!("RMS error: input {:.3}, after a 50 Hz notch {:.3}", error(&x), error(&y));
let comb = iircomb(50.0, 30.0, Some(IirCombFilterType::Notch), Some(fs), None).unwrap();
println!("comb filter: {} numerator taps", comb.beta.len());
let y = run(comb.beta.iter().map(|c| c.re).collect(), comb.alpha.iter().map(|c| c.re).collect());
println!("after a 50 Hz comb (all harmonics): {:.3}", error(&y));
}
RMS error: input 0.381, after a 50 Hz notch 0.142
comb filter: 21 numerator taps
after a 50 Hz comb (all harmonics): 0.005
The notch removes the 50 Hz hum but leaves its 150 Hz harmonic, whose RMS amplitude, 0.14, is all the remaining error. The comb, with a 20-sample delay at 1 kHz, removes both.
Strengths
- Cheap, sample-by-sample filtering with little memory; notch, peak and comb filters have a single intuitive parameter, .
Weaknesses
- Direct forms of high-order or narrow-band filters are numerically fragile; use second-order sections for them.
- Combs need an integer period; poles near the unit circle ring for a long time after transients.
Exercises
- Draw the signal-flow graphs of direct forms I and II and the transposed direct form II, and count delays and multipliers.
- Show that the notch filter’s gain is exactly 1 at DC and Nyquist and exactly 0 at .
- Show that the peak filter equals one minus the notch filter for the same and .
- Factor a sixth-order Butterworth design into three second-order sections by pairing conjugate poles, and compare its response under single-precision coefficients with the direct form.
- Estimate how long (in samples) the notch filter’s impulse response takes to decay by 60 dB for at .
Hints and answers
- Direct form I has two delay lines ( delays), direct form II shares them ( delays); both have multipliers, and the transposed form II has the same counts as form II.
- , and likewise . At the numerator is zero.
- The denominator minus times the notch numerator is , so has numerator over the same denominator: the peak filter.
- Group the six poles into conjugate pairs and form three biquads; with single-precision coefficients the direct form’s poles move much more than the biquads’ because sensitivity of the roots to the coefficients grows with the order.
- The denominator has poles of radius . For and : , , . The response decays like , so gives samples.
Further reading
- L. B. Jackson, “Roundoff-noise analysis for fixed-point digital filters realized in cascade or parallel form”, IEEE Transactions on Audio and Electroacoustics 18 (1970) 107–122.
- S. J. Orfanidis, Introduction to Signal Processing, Prentice Hall, 1996, chapters 6 and 8.
- R. Bristow-Johnson, “Cookbook formulae for audio EQ biquad filter coefficients”, W3C Audio Working Group note.
- A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010, chapter 6.