---
title: "Filter design lab: Kaiser, Butterworth and Welch"
heading: Designing a Kaiser-window FIR filter and a bilinear Butterworth IIR filter from their specifications, and estimating power spectra by Welch's method, in Python
eyebrow: S7 · Lesson 48 · Filter design lab
xp: 60
---

::: hook
Filter design programs hide a few dozen lines of arithmetic. In this lab you'll write those lines: a Kaiser-window FIR designer that takes band edges and a ripple and returns the coefficients, a Butterworth IIR designer that prewarps, picks the order, places the poles and maps them through the bilinear transform, and a Welch spectrum estimator scaled correctly in units per hertz. The tests check each design the way an engineer would, by evaluating it on a dense frequency grid against the specification, using the examples from lessons 19, 17 and 25.
:::

::: predict
## The Kaiser formulas give M = 37 for $\omega_p$ = 0.4π, $\omega_s$ = 0.6π and δ = 0.001. Will the finished filter meet δ = 0.001 exactly at every passband and stopband frequency?

- [ ] Yes, exactly, by construction
- [x] Very nearly: Kaiser's formulas are empirical, and the true peak error lands within a few percent of δ
- [ ] No, it will be about 10 times worse
- [ ] Only in the stopband

::: reveal
Very nearly. Kaiser fitted his β and M formulas to many designs, so they predict the length and shape well but not to the last digit; the test allows a 20% margin and the design uses much less. When a specification must be met exactly, designers check the response and add a tap if needed, which is what the dense-grid test does.
:::
:::

::: nameit
## The three procedures

**Kaiser window** (lesson 22): $A = -20\log\delta$; β from Kaiser's three-range formula; $M = \lceil (A - 8)/(2.285\Delta\omega)\rceil$; $\omega_c = (\omega_p + \omega_s)/2$; $h[n] = \frac{\omega_c}{\pi}\text{sinc}\left(\frac{\omega_c(n - M/2)}{\pi}\right)w[n]$ with `np.kaiser(M + 1, beta)` (NumPy's sinc is $\sin(\pi x)/(\pi x)$).

**Bilinear Butterworth** (lesson 19, T = 1): prewarp $\Omega = 2\tan(\omega/2)$; $N = \left\lceil\frac{\log[(10^{A_s/10} - 1)/(10^{A_p/10} - 1)]}{2\log(\Omega_s/\Omega_p)}\right\rceil$; $\Omega_c = \Omega_s/(10^{A_s/10} - 1)^{1/2N}$; analog poles $s_k = \Omega_ce^{j\pi(2k + N - 1)/2N}$ for k = 1, …, N; digital poles $z_k = \frac{1 + s_k/2}{1 - s_k/2}$; all N zeros at z = −1; scale so H(1) = 1. `np.poly(roots)` gives polynomial coefficients.

**Welch** (lesson 31): Hann segments of length L hopping L/2; average $|X|^2$; divide by $f_s\sum w^2$ for a density; double every bin except DC and Nyquist for the one-sided spectrum.
:::

::: example
## What does the Butterworth procedure give for Oppenheim and Schafer's Example 7.3?

::: solution
1. **Prewarp.** $\Omega_p$ = 0.6498 and $\Omega_s$ = 1.0191.
2. **Order and cutoff.** N = ⌈5.30⌉ = 6 and $\Omega_c$ = 0.766.
3. **Analog poles.** The six poles lie on a circle of that radius in the left half-plane, at angles 105°, 135°, 165° and their conjugates.
4. **Digital poles and zeros.** The bilinear map puts the poles inside the unit circle near z = 1, and the six zeros at −1 make the stopband fall steeply toward π.

**Answer:** N = 6 and $\Omega_c$ = 0.766, with analog poles at 105°, 135° and 165° (and their conjugates) and all six zeros at z = −1.
:::
:::

::: example
## Check the Welch scaling with white noise of variance 4 at 8 kHz.

::: solution
1. **Expected density.** The one-sided density should be flat at
   $$\begin{aligned} \frac{2\sigma^2}{f_s} &= \frac{8}{8000} \\ &= 0.001\ \text{per hertz} \end{aligned}$$
2. **Total power.** Summing the estimate over all bins times the bin width $f_s/L$ should return the variance, 4.
3. **A tone.** A tone $\sqrt{2}\cos(\cdot)$, of power 1, should integrate to 1 across the few bins its Hann window spreads it over.

**Answer:** a flat density of 0.001 per hertz that integrates to the variance, 4.
:::
:::

::: check
kind: python

## Step 1. Write `kaiser_lowpass(wp, ws, delta)`: a Kaiser-window lowpass from its band edges and ripple.

```python starter
import numpy as np

def kaiser_lowpass(wp, ws, delta):
    # wp, ws: passband and stopband edges in radians; delta: allowed ripple in both bands.
    # Return the impulse response h (length M + 1) of a Kaiser-window lowpass design.
    return np.zeros(1)

h = kaiser_lowpass(0.4*np.pi, 0.6*np.pi, 0.001)
print(len(h))
```

```python solution
import numpy as np

def kaiser_lowpass(wp, ws, delta):
    A = -20*np.log10(delta)
    if A > 50:
        beta = 0.1102*(A - 8.7)
    elif A >= 21:
        beta = 0.5842*(A - 21)**0.4 + 0.07886*(A - 21)
    else:
        beta = 0.0
    M = int(np.ceil((A - 8)/(2.285*(ws - wp))))
    wc = (wp + ws)/2
    n = np.arange(M + 1) - M/2
    hd = wc/np.pi*np.sinc(wc*n/np.pi)
    return hd*np.kaiser(M + 1, beta)

h = kaiser_lowpass(0.4*np.pi, 0.6*np.pi, 0.001)
print(len(h))
```

```python tests
import numpy as np
def resp(h, w):
    n = np.arange(len(h))
    return np.abs(np.exp(-1j*np.outer(w, n)) @ h)
h = kaiser_lowpass(0.4*np.pi, 0.6*np.pi, 0.001)
assert len(h) == 38, f"Oppenheim and Schafer's example needs M = 37, 38 taps; got {len(h)}."
assert np.allclose(h, h[::-1]), "A linear-phase design must be symmetric."
wp = np.linspace(0, 0.4*np.pi, 2000); ws = np.linspace(0.6*np.pi, np.pi, 2000)
ep = np.max(np.abs(resp(h, wp) - 1)); es = np.max(resp(h, ws))
assert ep < 0.0012 and es < 0.0012, f"The design should meet δ = 0.001 (to within a little): passband error {ep:.5f}, stopband {es:.5f}."
h2 = kaiser_lowpass(0.2*np.pi, 0.3*np.pi, 0.01)
ep2 = np.max(np.abs(resp(h2, np.linspace(0, 0.2*np.pi, 2000)) - 1)); es2 = np.max(resp(h2, np.linspace(0.3*np.pi, np.pi, 2000)))
assert ep2 < 0.012 and es2 < 0.012, f"A 40 dB, 0.1π design should meet δ = 0.01: passband {ep2:.4f}, stopband {es2:.4f}."
assert abs(len(h2) - 1 - int(np.ceil(32/(2.285*0.1*np.pi)))) == 0, "Use M = ⌈(A − 8)/(2.285Δω)⌉."
```

::: right
Right. Your designer reproduces Oppenheim and Schafer's 38-tap filter and meets both specifications on a dense grid.
:::
:::

::: check
kind: python

## Step 2. Write `butter_bilinear(wp, ws, Ap, As)`: a digital Butterworth lowpass by the bilinear transform.

```python starter
import numpy as np

def butter_bilinear(wp, ws, Ap, As):
    # Digital Butterworth lowpass by the bilinear transform (T = 1).
    # wp, ws in radians; at most Ap dB loss at wp, at least As dB at ws.
    # Return (b, a), coefficient arrays in powers of z^-1, with H(1) = 1.
    return np.array([1.0]), np.array([1.0])

b, a = butter_bilinear(0.2*np.pi, 0.3*np.pi, 1, 15)
print(len(a) - 1)
```

```python solution
import numpy as np

def butter_bilinear(wp, ws, Ap, As):
    Wp, Ws = 2*np.tan(wp/2), 2*np.tan(ws/2)
    N = int(np.ceil(np.log10((10**(As/10) - 1)/(10**(Ap/10) - 1))/(2*np.log10(Ws/Wp))))
    Wc = Ws/(10**(As/10) - 1)**(1/(2*N))
    k = np.arange(1, N + 1)
    s = Wc*np.exp(1j*np.pi*(2*k + N - 1)/(2*N))
    z = (1 + s/2)/(1 - s/2)
    a = np.real(np.poly(z))
    b = np.real(np.poly(-np.ones(N)))
    b = b*np.sum(a)/np.sum(b)
    return b, a

b, a = butter_bilinear(0.2*np.pi, 0.3*np.pi, 1, 15)
print(len(a) - 1)
```

```python tests
import numpy as np
def H(b, a, w):
    e = np.exp(-1j*np.outer(np.atleast_1d(w), np.arange(max(len(a), len(b)))))
    return (e[:, :len(b)] @ b)/(e[:, :len(a)] @ a)
b, a = butter_bilinear(0.2*np.pi, 0.3*np.pi, 1, 15)
assert len(a) - 1 == 6, f"Oppenheim and Schafer's Example 7.3 needs order 6; got {len(a) - 1}."
assert abs(abs(H(b, a, 0)[0]) - 1) < 1e-9, "Normalize so that H(1) = 1."
assert np.all(np.abs(np.roots(a)) < 1), "All poles must be inside the unit circle."
gp = 20*np.log10(abs(H(b, a, 0.2*np.pi)[0])); gs = 20*np.log10(abs(H(b, a, 0.3*np.pi)[0]))
assert gp >= -1 - 1e-6, f"At most 1 dB loss at 0.2π; got {gp:.3f} dB."
assert gs <= -15 + 1e-6, f"At least 15 dB at 0.3π; got {gs:.3f} dB."
w = np.linspace(0.3*np.pi, np.pi, 500)
assert np.all(20*np.log10(np.abs(H(b, a, w)) + 1e-300) <= -15 + 1e-6), "The whole stopband must be at least 15 dB down."
b2, a2 = butter_bilinear(0.1*np.pi, 0.25*np.pi, 0.5, 40)
assert abs(20*np.log10(abs(H(b2, a2, 0.25*np.pi)[0])) + 40) < 1e-6, "With Ωc set by the stopband, the loss at ω_s is exactly A_s."
```

::: right
Right. Order 6 with every pole inside the unit circle, less than 1 dB of loss at 0.2π and at least 15 dB across the whole stopband.
:::
:::

::: check
kind: python

## Step 3. Write `welch(x, L, fs)`: a one-sided power spectral density estimate in units² per hertz.

```python starter
import numpy as np

def welch(x, L, fs):
    # One-sided PSD estimate (units²/Hz) by Welch's method: Hann windows of length L, 50% overlap.
    # Return (f, P) with f = np.arange(L//2 + 1)*fs/L.
    f = np.arange(L//2 + 1)*fs/L
    return f, np.zeros(len(f))

rng = np.random.default_rng(1)
f, P = welch(rng.normal(size=8192), 256, 1000.0)
print(P[:3])
```

```python solution
import numpy as np

def welch(x, L, fs):
    w = np.hanning(L)
    step = L//2
    starts = range(0, len(x) - L + 1, step)
    P = np.zeros(L//2 + 1)
    for s in starts:
        X = np.fft.rfft(w*x[s:s + L])
        P += np.abs(X)**2
    P /= len(starts)*fs*np.sum(w**2)
    P[1:-1] *= 2
    return np.arange(L//2 + 1)*fs/L, P

rng = np.random.default_rng(1)
f, P = welch(rng.normal(size=8192), 256, 1000.0)
print(P[:3])
```

```python tests
import numpy as np
rng = np.random.default_rng(5)
x = 2.0*rng.normal(size=65536)
f, P = welch(x, 512, 8000.0)
assert len(f) == 257 and abs(f[1] - 15.625) < 1e-9, "Frequencies should run 0, fs/L, …, fs/2."
mid = np.mean(P[5:-5])
assert abs(mid/(2*4.0/8000.0) - 1) < 0.05, f"White noise of variance 4 at 8 kHz has a one-sided PSD of 2σ²/fs = 0.001; the estimate averages {mid:.6f}."
total = np.sum(P)*8000.0/512
assert abs(total/4.0 - 1) < 0.05, f"Integrating the PSD should give the variance, 4; got {total:.3f}."
spread = np.std(P[5:-5])/mid
assert spread < 0.15, f"With about 255 overlapping segments the bins should scatter by well under 15%; got {100*spread:.1f}%."
n = np.arange(65536)
f2, P2 = welch(np.sqrt(2)*np.cos(2*np.pi*1000*n/8000.0), 512, 8000.0)
k = int(round(1000*512/8000))
assert np.argmax(P2) == k, f"A 1 kHz tone should peak in bin {k}; got {np.argmax(P2)}."
pw = np.sum(P2[k - 3:k + 4])*8000.0/512
assert abs(pw - 1) < 0.02, f"A tone of power 1 should integrate to 1 around its peak; got {pw:.4f}."
```

::: right
Right. Your estimate integrates to the variance, puts white noise at 2σ²/f_s and recovers a tone's power, with averaging that keeps the bins within a few percent.
:::
:::

::: explain
## Why does the Butterworth designer set the cutoff from the stopband edge rather than the passband edge?

::: model
Once the order has been rounded up to a whole number, the filter is steeper than the specification strictly needs, so there's slack to place the cutoff anywhere in a small range and still meet both requirements. Setting $\Omega_c$ so the stopband edge lands exactly at the required attenuation uses all of the slack on the passband side, giving it less loss than the 1 dB allowed. Setting it from the passband edge would meet the passband exactly and exceed the stopband requirement instead. Either is correct; choosing the stopband is common because bilinear designs often matter most where the stopband begins, and it makes the test at $\omega_s$ come out exactly at $A_s$.
:::
:::

::: practice

::: check
given: A = 55 | 75; d = 0.08 | 0.2
answer: ceil((A - 8)/(2.285*d*pi))
tolerance: 0

## Kaiser M for {A} dB and a {d}π transition, rounded up?

::: misses
- [any] ⌈(A − 8)/(2.285Δω)⌉.
:::
:::

::: check
given: p = 0.15 | 0.25; s = 0.35 | 0.45; A = 20 | 30
answer: ceil(log((10^(A/10) - 1)/(10^0.1 - 1))/(2*log(tan(s*pi/2)/tan(p*pi/2))))
tolerance: 0

## Bilinear Butterworth order: 1 dB at {p}π, {A} dB at {s}π?

::: misses
- [any] Prewarp, then the order formula.
:::
:::

::: check
given: v = 0.5 | 9; s = 1 | 44.1
answer: 2*v/(s*1000)
tolerance: 0.5%

## One-sided PSD of white noise, variance {v}, at {s} kHz?

::: misses
- [any] $2\sigma^2/f_s$.
:::
:::
:::
