06. IIR filters: design, poles, zeros and stability
A telephone channel band-limits speech, a notch removes 50 Hz mains hum, a de-emphasis filter undoes pre-emphasis after speech synthesis: all are usually recursive (infinite impulse response, IIR) filters. (Pre-emphasis itself, \(1 - \alpha z^{-1}\), has no feedback: it is an FIR filter, notebook 05.) They achieve a steep roll-off with few coefficients, but they feed their output back to the input, so they can ring, distort phase and become unstable. This notebook designs a Butterworth filter the way the library does, compares it with SciPy, finds its poles and checks stability and the frequency response numerically.
Learning outcomes. After this notebook you can
design a Butterworth filter with
IirFilterDesignand read its second-order sections (SOS);predict its magnitude response from the bilinear-transform closed form and check it against
scipy.signal.butter/sosfreqz;find the poles and zeros of each section with
numpy.rootsand judge stability;explain the difference between causal filtering and zero-phase
filtfilt;design a 50 Hz hum notch (an RBJ-cookbook biquad) and measure its bandwidth.
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as ss
import audio_samples as aus
rng = np.random.default_rng(0)
F64 = np.dtype("float64") # generators default to float32; ask for float64
# The function is freqz_sos from SciPy 1.15 and sosfreqz below that.
freqz_sos = getattr(ss, "freqz_sos", None) or ss.sosfreqz
Concept
Difference equation. An IIR filter computes each output sample from the current and past inputs and past outputs:
where \(x[n]\) and \(y[n]\) are the input and output samples (dimensionless), \(b_k\) the feed-forward coefficients, \(a_k\) the feedback coefficients (with \(a_0 = 1\)), and \(M\), \(N\) the numerator and denominator orders.
Transfer function. The z-transform turns delays into powers of \(z^{-1}\):
where \(z\) is a complex variable. The roots of \(B\) are the zeros, the roots of \(A\) the poles. The frequency response is \(H\) on the unit circle, \(H(e^{j\omega})\) with \(\omega = 2\pi f / f_s\), where \(f\) is the frequency in Hz and \(f_s\) the sample rate in Hz.
Stability. A causal filter whose \(H(z)\) is in lowest terms (no pole cancelled by a zero) is bounded-input bounded-output stable if and only if every pole satisfies \(|p_i| < 1\). A pole of radius \(r\) contributes a term \(r^n\) to the impulse response, so the closer \(r\) is to 1, the longer the filter rings.
Butterworth prototype. The analogue Butterworth low-pass of order \(N\) is maximally flat:
where \(\Omega\) is the analogue angular frequency in rad/s and \(\Omega_c\) the cutoff in rad/s. At \(\Omega = \Omega_c\) the power is halved: \(10 \log_{10}(1/2) = -3.01\) dB. Its \(N\) poles lie on a circle of radius \(\Omega_c\) in the left half of the s-plane:
Bilinear transform with pre-warping. The digital filter comes from substituting
where \(K\) is a positive constant in rad/s (usually \(K = 2 f_s\); the library uses SciPy’s internal normalisation, and every \(K\) gives the same \(H(z)\) once the cutoff is pre-warped). The whole \(j\Omega\) axis maps onto the unit circle with \(\Omega = K \tan(\omega/2)\), so the frequency axis is compressed near Nyquist. To land the digital cutoff exactly on \(f_c\) (Hz) the analogue cutoff is pre-warped, \(\Omega_c = K \tan(\pi f_c / f_s)\). Each analogue pole maps to \(p = (K + s)/(K - s)\), and the \(N\) zeros at \(s = \infty\) map to \(z = -1\) (Nyquist). Together this gives a closed form for the digital Butterworth magnitude:
Second-order sections (SOS). A high-order \(A(z)\) is numerically fragile: tiny coefficient errors move the poles a lot. The library therefore factors \(H(z)\) into a cascade of biquads,
where \(S = \lceil N/2 \rceil\) is the number of sections. Each row is stored in SciPy’s layout
[b0, b1, b2, a0, a1, a2] with a0 = 1.
Zero-phase filtering. Running the filter forwards and then backwards (filtfilt) gives
the overall response \(|H|^2\) with zero phase: no delay, twice the attenuation in dB
(\(-6.02\) dB at a Butterworth cutoff), and a non-causal filter (it needs the whole signal).
The design pipeline follows the steps of SciPy’s iirfilter (prototype, lp2lp_zpk,
bilinear_zpk, zpk2sos) and is checked against SciPy golden fixtures in the Rust test
suite, so we can use SciPy as an independent reference here.
With the library
Design a 4th-order Butterworth low-pass at 1 kHz for 16 kHz audio and look at its sections.
IirFilterDesign is only a specification; sos(sample_rate) designs the filter.
fs, fc = 16_000.0, 1_000.0
design = aus.IirFilterDesign.butterworth_lowpass(4, fc)
sos = design.sos(fs)
print(sos)
assert sos.shape == (2, 6) # N = 4 -> two biquads
# SciPy's design of the same filter. The library takes the same design steps, so the
# coefficients agree to a few ULPs; 1e-12 is far above that and far below anything audible.
sos_scipy = ss.butter(4, fc, btype="low", fs=fs, output="sos")
assert np.allclose(sos, sos_scipy, rtol=0, atol=1e-12)
[[ 9.33498613e-04 1.86699723e-03 9.33498613e-04 1.00000000e+00
-1.36511724e+00 4.77592250e-01]
[ 1.00000000e+00 2.00000000e+00 1.00000000e+00 1.00000000e+00
-1.61172710e+00 7.44520838e-01]]
frequency_response(frequencies, sample_rate) returns the linear magnitude and the phase in
radians, like sosfreqz(sos, worN=frequencies, fs=fs). At the probes \(0\), \(f_c\), \(2f_c\) and
\(4f_c\) the filter is at 0 dB, \(-3.01\) dB, \(-25.5\) dB and \(-56.1\) dB.
probes = np.array([0.0, fc, 2 * fc, 4 * fc])
mag, phase = design.frequency_response(probes, fs)
db = 20 * np.log10(mag)
print(np.round(db, 4))
assert abs(db[0]) < 1e-9
assert abs(db[1] + 3.0103) < 1e-4 # 10 log10(1/2), to 4 decimals
assert abs(db[2] + 25.5) < 0.05 # one octave up
assert abs(db[3] + 56.1) < 0.05 # two octaves up
# The closed-form digital Butterworth magnitude matches to rounding (1e-12).
r = np.tan(np.pi * probes / fs) / np.tan(np.pi * fc / fs)
assert np.allclose(mag, 1 / np.sqrt(1 + r**8), rtol=0, atol=1e-12)
[ 0. -3.0103 -25.4973 -56.1071]
One octave above the cutoff the digital filter attenuates more (25.5 dB) than the analogue prototype would (\(10\log_{10}(1 + 2^8) = 24.1\) dB): the bilinear transform compresses the frequency axis towards Nyquist.
analogue_db = 10 * np.log10(1 + 2.0**8)
assert abs(analogue_db - 24.1) < 0.05
assert -db[2] > analogue_db # the digital filter is steeper
The next cell compares the whole response with SciPy’s sosfreqz on a dense grid, and plot orders 2, 4
and 8: higher order means a steeper transition band, but every order is \(-3.01\) dB at \(f_c\).
f = np.linspace(0, fs / 2, 801)
_, h_scipy = freqz_sos(sos_scipy, worN=f, fs=fs)
m_lib, p_lib = design.frequency_response(f, fs)
# Same coefficients, same formula: agreement to rounding.
assert np.allclose(m_lib, np.abs(h_scipy), rtol=0, atol=1e-12)
# Phases agree modulo 2 pi (both are wrapped).
assert np.allclose(np.exp(1j * p_lib), np.exp(1j * np.angle(h_scipy)), atol=1e-9)
fig, ax = plt.subplots(figsize=(8, 3))
for order in (2, 4, 8):
m, _ = aus.IirFilterDesign.butterworth_lowpass(order, fc).frequency_response(f[1:-1], fs)
ax.plot(f[1:-1], 20 * np.log10(m), label=f"N = {order}")
ax.axhline(-3.01, color="grey", lw=0.8, ls="--")
ax.axvline(fc, color="grey", lw=0.8, ls=":")
ax.set(xlim=(0, fs / 2), ylim=(-100, 5), xlabel="Frequency (Hz)", ylabel="Gain (dB)",
title="Butterworth low-pass, $f_c$ = 1 kHz, $f_s$ = 16 kHz")
ax.legend()
plt.show()
Applying the filter. AudioSamples.apply_iir_filter(design) filters causally in place
(like scipy.signal.sosfilt) and AudioSamples.filtfilt(design) filters with zero phase
(like sosfiltfilt). For a 1 kHz tone the causal filter attenuates by 3.01 dB and delays by
half a period (a 4th-order Butterworth has \(-180°\) of phase at its cutoff, 8 samples here);
filtfilt attenuates by 6.02 dB and does not delay.
tone = aus.sine_wave(1_000.0, 0.5, sample_rate=16_000, amplitude=1.0, dtype=F64)
t = tone.to_numpy()
once = tone.copy()
once.apply_iir_filter(design) # in place
twice = tone.copy()
twice.filtfilt(design) # in place
o, w = once.to_numpy(), twice.to_numpy()
# The causal output is exactly scipy.signal.sosfilt (same coefficients; 1e-12 for rounding).
assert np.allclose(o, ss.sosfilt(sos_scipy, t), rtol=0, atol=1e-12)
mid = slice(2_000, 6_000) # away from the start-up and end transients
amp_db = lambda v: 20 * np.log10(np.max(np.abs(v[mid])))
def lag(v):
corr = [np.dot(v[2_000:6_000], t[2_000 - k:6_000 - k]) for k in range(16)]
return int(np.argmax(corr))
# Peak-picking a sampled sine can miss the true peak by 1 - cos(pi fc/fs) = 1.9 % (0.17 dB),
# so 0.2 dB is the tolerance.
assert abs(amp_db(o) + 3.01) < 0.2 and abs(amp_db(w) + 6.02) < 0.2
assert lag(o) == 8 # half of the 16-sample period: -180 degrees
assert lag(w) == 0 # zero phase
fig, ax = plt.subplots(figsize=(8, 3))
n = np.arange(3_000, 3_048)
ax.plot(n / fs * 1e3, t[n], label="input")
ax.plot(n / fs * 1e3, o[n], label="apply_iir_filter (causal)")
ax.plot(n / fs * 1e3, w[n], label="filtfilt (zero phase)")
ax.set(xlabel="Time (ms)", ylabel="Amplitude", title="1 kHz tone through a 1 kHz Butterworth",
ylim=(-1.1, 1.6))
ax.legend(fontsize=8, ncol=3, loc="upper center")
plt.show()
For streaming, SosFilter.from_design(design, fs) builds the cascade once and keeps its delay
lines between calls, so processing a signal block by block gives the same output as one call.
filt = aus.SosFilter.from_design(design, fs)
assert np.allclose(filt.sos(), sos, rtol=0, atol=0)
blocks = [filt.process_samples(b) for b in np.array_split(t, 7)]
filt.reset()
whole = filt.process_samples(t)
# Same arithmetic in the same order: identical to the last bit.
assert np.array_equal(np.concatenate(blocks), whole)
assert np.allclose(whole, o, rtol=0, atol=1e-12)
How it works
This section builds the same filter from the Concept formulas alone: place the analogue poles on
a circle, pre-warp, apply the bilinear map, fix the gain so that \(H(1) = 1\), and compare with
the library’s poles. The library’s poles are the roots of each section’s denominator
\(a_0 z^2 + a_1 z + a_2\), found with numpy.roots.
order = 4
K = 2 * fs # any K works once the cutoff is pre-warped
omega_c = K * np.tan(np.pi * fc / fs)
k = np.arange(order)
s_poles = omega_c * np.exp(1j * np.pi * (2 * k + order + 1) / (2 * order))
assert np.all(s_poles.real < 0) # analogue stability: left half-plane
z_poles = (K + s_poles) / (K - s_poles)
# Zeros all at z = -1; choose the gain g so that H(1) = g 2^N / prod(1 - p) = 1.
gain = np.prod(1 - z_poles).real / 2**order
lib_poles = np.concatenate([np.roots(row[3:]) for row in sos])
lib_zeros = np.concatenate([np.roots(row[:3]) for row in sos])
print("poles:", np.round(np.sort_complex(lib_poles), 6))
print("|p| :", np.round(np.abs(lib_poles), 6))
# Every pole is inside the unit circle: the filter is stable.
assert np.all(np.abs(lib_poles) < 1)
# Our poles match the library's. np.roots goes through an eigenvalue solver; 1e-10 is a
# generous bound for O(1) numbers.
for p in z_poles:
assert np.min(np.abs(lib_poles - p)) < 1e-10
# The four zeros sit at z = -1. A double root is ill-conditioned: an error of eps in the
# coefficients moves it by about sqrt(eps) = 1e-8, hence the looser tolerance.
assert np.allclose(lib_zeros, -1, atol=1e-6)
# The overall gain is the product of the sections' b0.
assert abs(gain - np.prod(sos[:, 0])) / gain < 1e-10
# Largest pole radius: the pair nearest the cutoff.
assert abs(np.max(np.abs(lib_poles)) - 0.862856) < 1e-6
poles: [0.682559-0.108194j 0.682559+0.108194j 0.805864-0.308391j
0.805864+0.308391j]
|p| : [0.69108 0.69108 0.862856 0.862856]
# H(e^{jw}) = g (z + 1)^N / prod(z - p), evaluated directly.
probe = np.array([100.0, 1_000.0, 3_000.0, 7_000.0])
z = np.exp(2j * np.pi * probe / fs)
h = gain * (z + 1) ** order / np.prod(z[:, None] - z_poles[None, :], axis=1)
m, _ = design.frequency_response(probe, fs)
assert np.allclose(np.abs(h), m, rtol=0, atol=1e-12)
fig, ax = plt.subplots(figsize=(4, 4))
th = np.linspace(0, 2 * np.pi, 400)
ax.plot(np.cos(th), np.sin(th), color="grey", lw=0.8)
ax.plot(lib_poles.real, lib_poles.imag, "x", ms=9, label="poles")
ax.plot([-1], [0], "o", mfc="none", ms=9, label="zeros (x4)")
ax.set(aspect="equal", xlabel="Re z", ylabel="Im z", title="Pole-zero plot")
ax.legend(fontsize=8)
plt.show()
The difference equation itself is a five-term loop per section. Running it on an impulse reproduces the library’s output to within rounding (the library uses the transposed direct form, so the rounding differs slightly).
x = np.zeros(320) # 20 ms impulse
x[0] = 1.0
lib = aus.AudioSamples.new_mono(x.copy(), 16_000)
lib.apply_iir_filter(design)
y = x.copy()
for b0, b1, b2, a0, a1, a2 in sos: # direct form I, one section after another
x1 = x2 = y1 = y2 = 0.0
for i, v in enumerate(y):
yn = (b0 * v + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2) / a0
x2, x1, y2, y1 = x1, v, y1, yn
y[i] = yn
assert np.max(np.abs(y - lib.to_numpy())) < 1e-12
# The impulse response sums to the DC gain, 1 (it has decayed within 20 ms).
assert abs(y.sum() - 1) < 1e-6
A 50 Hz hum notch. Butterworth and Chebyshev designs start from analogue prototypes. A single notch is usually designed directly as one biquad, with the formula from Robert Bristow-Johnson’s Audio EQ Cookbook (RBJ): with \(\omega_0 = 2\pi f_0 / f_s\) and \(\alpha = \sin\omega_0 / (2Q)\),
where \(f_0\) is the notch frequency in Hz and \(Q\) (dimensionless) sets the width: the \(-3\) dB
bandwidth is about \(f_0/Q\) Hz. The zeros lie on the unit circle at \(\pm\omega_0\), so \(f_0\) is
removed completely in the steady state; the poles sit just inside the circle at the same angle and
keep the notch narrow. The library’s EqBand(EqBandType.band_stop, f0, 0.0, Q) is exactly this
filter. With \(f_0 = 50\) Hz and \(Q = 10\) at 16 kHz the \(-3\) dB bandwidth is 5.00 Hz and the pole
radius 0.99902; a 1 kHz tone loses 0.0001 dB.
f_n, q_n, fs_n = 50.0, 10.0, 16_000
n_n = np.arange(2 * fs_n)
hum = np.sin(2 * np.pi * f_n * n_n / fs_n) + np.sin(2 * np.pi * 1_000 * n_n / fs_n)
notched = aus.AudioSamples.new_mono(hum.copy(), sample_rate=fs_n) # copy: new_mono shares memory
notched.apply_eq_band(aus.EqBand(aus.EqBandType.band_stop, f_n, 0.0, q_n)) # in place, returns None
y_n = notched.to_numpy()
# The RBJ notch, run by SciPy: the library computes the same recursion.
w0 = 2 * np.pi * f_n / fs_n
alpha = np.sin(w0) / (2 * q_n)
b_n = np.array([1.0, -2 * np.cos(w0), 1.0])
a_n = np.array([1 + alpha, -2 * np.cos(w0), 1 - alpha])
assert np.allclose(y_n, ss.lfilter(b_n, a_n, hum), atol=1e-9)
def tone_db(v, f):
# Level of the component at f Hz in dB re amplitude 1 (v holds whole periods of f).
k = np.arange(len(v))
return 20 * np.log10(2 / len(v) * abs(np.sum(v * np.exp(-2j * np.pi * f * k / fs_n))))
steady = y_n[fs_n:] # the second second: the notch has settled (pole time constant ~64 ms)
print(f"after the notch: 50 Hz at {tone_db(steady, 50.0):.1f} dB, 1 kHz at {tone_db(steady, 1_000.0):.5f} dB")
assert tone_db(steady, 50.0) < -120.0
assert abs(tone_db(steady, 1_000.0) + 0.0001) < 0.00005
# -3 dB bandwidth f_n / q_n = 5 Hz; zeros on the unit circle, poles just inside it.
from scipy.optimize import brentq
notch_db = lambda f: 20 * np.log10(abs(ss.freqz(b_n, a_n, worN=[f], fs=fs_n)[1][0]))
lo = brentq(lambda f: notch_db(f) + 10 * np.log10(2), 40.0, 49.999)
hi = brentq(lambda f: notch_db(f) + 10 * np.log10(2), 50.001, 60.0)
print(f"-3 dB points {lo:.2f} and {hi:.2f} Hz: bandwidth {hi - lo:.2f} Hz")
assert abs((hi - lo) - 5.00) < 0.005
assert np.allclose(np.abs(np.roots(b_n)), 1.0, atol=1e-12)
assert np.allclose(np.abs(np.roots(a_n / a_n[0])), 0.99902, atol=5e-6)
after the notch: 50 Hz at -160.5 dB, 1 kHz at -0.00011 dB
-3 dB points 47.56 and 52.56 Hz: bandwidth 5.00 Hz
Ask the library to explain
IirFilterDesign.explain(sample_rate) designs the filter, tabulates the poles and zeros of
every section and measures the gain at the cutoff. (signal.explain(design) does the same
with the signal’s sample rate.)
doc = design.explain(16_000.0)
doc # renders as Markdown in Jupyter
Butterworth low-pass filter (order 4)
An order-4 Butterworth low-pass filter with cutoff 1000 Hz at f_s = 16000 Hz, realised as 2 second-order section(s) with 4 poles. All poles lie inside the unit circle (largest radius 0.862856), so the filter is stable.
Formulas
Butterworth prototype: maximally flat pass band, -3.01 dB at the cutoff:
$$ |H_a(j\Omega)|^2 = \frac{1}{1 + \left(\frac{\Omega}{\Omega_c}\right)^{2N}} $$
Bilinear transform with pre-warping, so the digital filter has its critical frequency exactly at f_c (the code designs at f_s = 2, so K = 4; any K gives the same H(z)):
$$ s = K \frac{1 - z^{-1}}{1 + z^{-1}}, \quad \Omega_c = K \tan\left(\frac{\pi f_c}{f_s}\right) $$
Realised as a cascade of second-order sections (SOS), which is far less sensitive to coefficient rounding than one high-order polynomial:
$$ H(z) = \prod_{i=1}^{S} \frac{b_{0i} + b_{1i} z^{-1} + b_{2i} z^{-2}}{1 + a_{1i} z^{-1} + a_{2i} z^{-2}} $$
Symbols
| Symbol | Meaning | Value | |—|—|—| | $N$ | prototype order | 4 | | $K$ | bilinear-transform constant | | | $f_c$ | critical (cutoff) frequency | 1000 Hz | | $f_s$ | sample rate | 16000 Hz |
Derived quantities
| Quantity | Value | Formula | |—|—|—| | Sections | $S$ = 2 | $\lceil \text{poles} / 2 \rceil$ | | Poles | $N_p$ = 4 | $N$ | | Pre-warped f_c | $\tfrac{f_s}{\pi} \tan(\pi f_c/f_s)$ = 1013.05 Hz | $\frac{f_s}{\pi}\tan(\pi f / f_s)$ | | Largest pole radius | $\max \vert p\vert $ = 0.862856 | $\max_i \vert p_i\vert $ | | Stability margin | $1 - \max \vert p\vert $ = 0.137144 | $1 - \max_i \vert p_i\vert $ | | Measured gain at the cutoff | $20\log_{10}\vert H(e^{j 2\pi f/f_s})\vert $ = -3.0103 dB | $\text{sosfreqz at the edge}$ | | Design gain at the critical frequency | $G_c$ = -3.0103 dB | $10\log_{10}(1/2)$ |
Second-order sections: zeros and poles in the z-plane
| Section | Zeros | Poles | max |p| | |—|—|—|—| | 1 | -1, -1 | 0.682559 + 0.108194j, 0.682559 - 0.108194j | 0.69108 | | 2 | -1, -1 | 0.805864 + 0.308391j, 0.805864 - 0.308391j | 0.862856 |
Measured magnitude response
| f (Hz) | |H| | |H| (dB) | |—|—|—| | 0 | 1 | 3.8573e-15 | | 250 | 0.999993 | -6.0123e-5 | | 500 | 0.998198 | -0.0156637 | | 1000 | 0.707107 | -3.0103 | | 2000 | 0.0531051 | -25.4973 | | 4000 | 0.00156548 | -56.1071 | | 7992 | 9.5308e-15 | -280.417 |
Trade-offs
Higher order gives a steeper transition band but more phase distortion near the cutoff and poles closer to the unit circle.
Butterworth is flattest, Chebyshev and elliptic trade ripple for steepness, Bessel keeps the group delay flat (least ringing) at the cost of a gentle roll-off.
IIR filters have non-linear phase; filtfilt (forward-backward) removes it at the cost of doubling the attenuation and being non-causal.
See also
Design as SOS:
audio_samples::operations::types::IirFilterDesign::sos_coefficientsApply:
audio_samples::AudioIirFiltering::apply_iir_filterApply (Python):
audio_samples.AudioSamples.apply_iir_filterPython:
audio_samples.IirFilterDesign.explain
assert doc.quantity("Sections") == 2
assert abs(doc.quantity("Measured gain at the cutoff") + 3.0103) < 1e-3
assert abs(doc.quantity("Largest pole radius") - 0.862856) < 1e-6
# A low cutoff relative to fs pushes the poles towards z = 1. At 10 Hz with order 8 the
# stability margin drops below 1e-3 and the explainer warns.
audio = aus.sine_wave(440.0, 0.05, sample_rate=16_000, dtype=F64)
doc8 = audio.explain(aus.IirFilterDesign.butterworth_lowpass(8, 10.0))
margin = doc8.quantity("Stability margin")
assert 0 < margin < 1e-3
assert doc8.has_warning_containing("very sensitive to rounding")
for w in doc8.warnings:
print(f"[{w['level']}] {w['message']}\n hint: {w['hint']}")
[caution] Poles lie within 7.6582e-4 of the unit circle (normalised edge 6.2500e-4 of f_s, order 8); the response is very sensitive to rounding and rings for a long time.
hint: Lower the order, or decimate before filtering so the cutoff is a larger fraction of the sample rate.
Exercises
1. Higher order, same cutoff gain. Predict the gain (dB) of an 8th-order Butterworth
low-pass (1 kHz, 16 kHz) at 2 kHz from the closed form, then check with
frequency_response. Store the measured gain in dB in answer.
answer = None # TODO
# Solution
m8, _ = aus.IirFilterDesign.butterworth_lowpass(8, fc).frequency_response(
np.array([fc, 2 * fc]), fs)
answer = 20 * np.log10(m8[1])
ratio = np.tan(np.pi * 2 * fc / fs) / np.tan(np.pi * fc / fs) # 2.0824
predicted = -10 * np.log10(1 + ratio**16)
assert abs(20 * np.log10(m8[0]) + 3.0103) < 1e-4 # still -3.01 dB at the cutoff
assert abs(answer - predicted) < 1e-9
assert abs(answer + 51.0) < 0.05 # about twice the 4th-order 25.5 dB
print(f"8th order at 2 kHz: {answer:.2f} dB")
8th order at 2 kHz: -50.97 dB
2. Chebyshev versus Butterworth. A 4th-order Chebyshev I low-pass with 1 dB ripple at
1 kHz (IirFilterDesign.chebyshev_i("lowpass", 4, 1000.0, 1.0)): predict its gain at the
cutoff and at DC, then compare its attenuation at 2 kHz with the Butterworth’s 25.5 dB. Put
the Chebyshev gain at 2 kHz (dB) in answer.
answer = None # TODO
# Solution
cheb = aus.IirFilterDesign.chebyshev_i("lowpass", 4, 1_000.0, 1.0)
grid = np.arange(0.0, 1_001.0) # 0..1000 Hz in 1 Hz steps
m, _ = cheb.frequency_response(grid, fs)
g = 20 * np.log10(m)
assert abs(g[1000] + 1.0) < 1e-6 # -rp at the cutoff
assert abs(g[0] + 1.0) < 1e-6 # even order: -rp at DC too
assert abs(g.max()) < 1e-3 # ripple peaks touch 0 dB (to the 1 Hz grid)
# SciPy agrees on the coefficients.
assert np.allclose(cheb.sos(fs), ss.cheby1(4, 1.0, 1_000.0, fs=fs, output="sos"), atol=1e-12)
m2, _ = cheb.frequency_response(np.array([2_000.0]), fs)
answer = 20 * np.log10(m2[0])
assert abs(answer + 35.5) < 0.1 # 10 dB more than the Butterworth
print(f"Chebyshev I at 2 kHz: {answer:.1f} dB")
Chebyshev I at 2 kHz: -35.5 dB
3. Where are the zeros of a high-pass? Predict where the four zeros of a 4th-order
Butterworth high-pass at 1 kHz lie, then find them with numpy.roots. Put the zeros in
answer.
answer = None # TODO
# Solution
sos_hp = aus.IirFilterDesign.butterworth_highpass(4, 1_000.0).sos(fs)
answer = np.concatenate([np.roots(row[:3]) for row in sos_hp])
# A high-pass blocks DC, so all four zeros move to z = +1 (double roots: see the
# sqrt(eps) remark above for the tolerance).
assert len(answer) == 4 and np.allclose(answer, 1, atol=1e-6)
# Equivalently b0 z^2 + b1 z + b2 = b0 (z - 1)^2: b1 = -2 b0 and b2 = b0.
assert np.allclose(sos_hp[:, 1], -2 * sos_hp[:, 0]) and np.allclose(sos_hp[:, 2], sos_hp[:, 0])
4. filtfilt doubles the decibels. Predict the attenuation (dB) of a 2 kHz tone by
filtfilt with the 4th-order 1 kHz Butterworth, then measure it. Put the measured level in
dB in answer.
answer = None # TODO
# Solution
tone2 = aus.sine_wave(2_000.0, 0.5, sample_rate=16_000, dtype=F64)
tone2.filtfilt(design)
peak = np.max(np.abs(tone2.to_numpy()[2_000:6_000]))
answer = 20 * np.log10(peak)
# 2 kHz is 8 samples per period and the tone starts at phase 0, so samples land on the
# peaks: 0.1 dB is enough. Forward and backward each give 25.5 dB.
assert abs(answer - 2 * db[2]) < 0.1
assert abs(answer + 51.0) < 0.1
Common pitfalls
Frequencies are in Hz.
scipy.signal.butter(N, Wn)withoutfsexpects \(W_n\) as a fraction of Nyquist; this library always takes Hz and a sample rate.Cutoff conventions. The cutoff is the \(-3.01\) dB point for Butterworth, the \(-r_p\) point for Chebyshev I and the start of the stop band for Chebyshev II (as in SciPy).
Never cascade a high-order filter as one polynomial. Keep the SOS rows. MATLAB’s
[sos, g]stores the gain separately; SciPy and this library fold it into the first row.apply_iir_filterandfiltfiltwork in place and returnNone; copy first if you need the original.filtfiltdoubles the attenuation in dB and is non-causal: suitable for analysis, not for real-time processing.Low cutoffs at high sample rates put poles close to \(z = 1\): long ringing and sensitivity to rounding. Decimate first, or lower the order.
Double roots and
numpy.roots. Repeated zeros at \(z = \pm 1\) come back with errors of order \(\sqrt{\varepsilon} \approx 10^{-8}\); that is the root finder, not the filter.
See also
Rust guide chapter: https://docs.rs/audio_samples/latest/audio_samples/guide/c06_iir_filters/index.html (available from the next release; until then build the docs locally with
cargo doc --features educational,full_no_plotting --open) and the labexamples/tutorial_06_iir_filters.rs.Python API:
audio_samples.IirFilterDesign,audio_samples.SosFilter,AudioSamples.apply_iir_filter,AudioSamples.filtfilt,audio_samples.EqBand,AudioSamples.apply_eq_band,audio_samples.explain.Previous: 05. Convolution and FIR filters; next: 07. Resampling.
References
Oppenheim, A. V. and Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson. Chapter 7 (IIR design by the bilinear transform; Butterworth and Chebyshev approximations).
Bristow-Johnson, R. Cookbook formulae for audio equalizer biquad filter coefficients (the Audio EQ Cookbook). Published as a W3C Working Group Note: https://www.w3.org/TR/audio-eq-cookbook/.