---
title: Signals lab
heading: Convolution, difference equations and frequency response in Python
eyebrow: C9 · Lesson 52 · Signals lab
xp: 50
---

::: hook
Every signal-processing library has three functions at its core: one that convolves, one that runs a difference equation over a signal (called `lfilter` in SciPy), and one that evaluates a filter's frequency response. They're short, and writing them yourself is the surest way to know exactly what they compute, including the conventions that trip people up, like the sign of the feedback coefficients. In this lab you'll write all three and use them on the 60 Hz notch filter from lesson 39.
:::

::: play
- The input stems are two tones, a slow one at ω = 0.2 and a fast one at ω = 2.5 (half the size). The output stems are what an M-point moving average makes of them, once it has filled (after M − 1 samples).
- At M = 1 nothing changes. Raise M: the fast tone shrinks quickly while the slow one barely changes. At M = 5 the fast tone is nearly gone: 2.5 is almost exactly the 5-point average's second null, 2 × 2π/5 = 2.51.
- Your `lfilter` will produce exactly these output samples, and `freq_response` the gains in the readouts.
:::
:::

```sim plot
view: graph
x: n = 0..40
y: v = -1.8..1.8
slider: M = 1..12 = 3 step 1
plot: cos(0.2*n) + 0.5*cos(2.5*n) | stems | label: x[n]
plot: sin(M*0.1)/(M*sin(0.1))*cos(0.2*(n - (M - 1)/2)) + 0.5*sin(M*1.25)/(M*sin(1.25))*cos(2.5*(n - (M - 1)/2)) | stems | label: y[n]
readout: gain of the slow tone = sin(M*0.1)/(M*sin(0.1)) | digits: 3
readout: gain of the fast tone = sin(M*1.25)/(M*sin(1.25)) | digits: 3
```

::: predict
## `lfilter(b=[1], a=[1, -0.5], x=[1, 0, 0, 0])` runs $y[n] = 0.5\,y[n-1] + x[n]$. What does it return?

- [ ] [1, −0.5, 0.25, −0.125]
- [x] [1, 0.5, 0.25, 0.125]
- [ ] [1, 0, 0, 0]
- [ ] [1, 1.5, 1.75, 1.875]

::: reveal
[1, 0.5, 0.25, 0.125]. In the `b, a` convention the denominator is $1 + a_1z^{-1} + \cdots$, so a = [1, −0.5] means $y[n] - 0.5y[n-1] = x[n]$: the feedback coefficient enters with its sign flipped. Getting that sign wrong gives the first option.
:::
:::

::: nameit
## The conventions

A filter is two coefficient lists, b (numerator) and a (denominator, with a[0] usually 1):

$$H(z) = \frac{b_0 + b_1z^{-1} + \cdots + b_Mz^{-M}}{a_0 + a_1z^{-1} + \cdots + a_Nz^{-N}}$$

which is the difference equation

$$a_0\,y[n] = \sum_{k=0}^{M} b_k\,x[n-k] - \sum_{k=1}^{N} a_k\,y[n-k]$$

starting at rest (samples before n = 0 are zero). An FIR filter has a = [1].

## The three functions

- **convolve(x, h):** output length len(x) + len(h) − 1, with y[i + j] += x[i]·h[j].
- **lfilter(b, a, x):** compute each y[n] from the formula above, in order, using outputs already computed.
- **freq_response(b, a, w):** with $z^{-1} = e^{-j\omega}$, add up $b_k z^{-k}$ and $a_k z^{-k}$ and divide.
:::

::: example
## Run `lfilter([0.25, 0.25, 0.25, 0.25], [1], [1, 1, 1, 1, 1, 1])`.

::: solution
1. **What it computes.** A 4-point moving average of a step.
2. **The output.**
   $$0.25,\ 0.5,\ 0.75,\ 1,\ 1,\ 1$$
3. **Filling up.** It takes M − 1 = 3 samples to fill, then outputs the input's average.

**Answer:** 0.25, 0.5, 0.75, 1, 1, 1.
:::
:::

::: example
## What is `abs(freq_response([1], [1, -0.5], pi))`?

::: solution
1. **At ω = π.**
   $$\begin{aligned} z^{-1} &= e^{-j\pi} \\ &= -1 \end{aligned}$$
2. **Evaluate.**
   $$\begin{aligned} H &= 1/(1 + 0.5) \\ &= 0.667 \end{aligned}$$
3. **Compare DC.** At DC it would be 1/(1 − 0.5) = 2.

**Answer:** 0.667.
:::
:::

::: check
given: a = 0.4 | 0.7 | -0.5; n = 3 | 5
answer: a^n
tolerance: 0.5%

## `lfilter([1], [1, -({a})], impulse)` gives h. What is h[{n}]?

::: right
Right. a = [1, −({a})] means $y[n] = (\given{a})y[n-1] + x[n]$: $h[n] = (\given{a})^n$ = {answer}.
:::

::: misses
- [(-a)^n] The a list's coefficient enters with its sign flipped: −(−{a}) = {a}.
- [any] Not yet. Write out the difference equation from the a list.
:::
:::

::: check
given: M = 3 | 4 | 8; n = 1 | 2
answer: (n + 1)/M
tolerance: 0.5%

## `lfilter([1/{M}]*{M}, [1], step)` averages a unit step over {M} points. What is the output at n = {n}?

::: right
Right. (n + 1)/M = {answer} while the window fills.
:::

::: misses
- [1/M] At n = {n} there are {n} + 1 ones in the window.
- [any] Not yet. Count the ones in the window and divide by {M}.
:::
:::

::: check
kind: python

## Write `convolve(x, h)`: the linear convolution of two lists, of length len(x) + len(h) − 1.

```python starter
def convolve(x, h):
    return [a * b for a, b in zip(x, h)]
```

```python solution
def convolve(x, h):
    y = [0] * (len(x) + len(h) - 1)
    for i, xv in enumerate(x):
        for j, hv in enumerate(h):
            y[i + j] += xv * hv
    return y
```

```python tests
assert convolve([1, 2, 3], [1, 1]) == [1, 3, 5, 3], f"[1, 2, 3] * [1, 1] should be [1, 3, 5, 3], got {convolve([1, 2, 3], [1, 1])}."
assert convolve([1, 0, -1], [2, 3, 4]) == [2, 3, 2, -3, -4], f"[1, 0, -1] * [2, 3, 4] should be [2, 3, 2, -3, -4], got {convolve([1, 0, -1], [2, 3, 4])}."
assert convolve([5], [1, 2, 3]) == [5, 10, 15], "Convolving with a single sample scales."
assert convolve([0, 0, 1], [1, 2]) == [0, 0, 1, 2], "Convolving with a shifted impulse delays."
```

::: right
Right. Two nested loops: the polynomial-multiplication picture of convolution.
:::
:::

::: check
kind: python

## Write `lfilter(b, a, x)`: run the difference equation with coefficient lists b and a (a[0] divides, a[1:] are feedback with the sign convention above), starting at rest, and return the output list.

```python starter
def lfilter(b, a, x):
    return list(x)
```

```python solution
def lfilter(b, a, x):
    y = []
    for n in range(len(x)):
        acc = sum(b[k] * x[n - k] for k in range(len(b)) if n - k >= 0)
        acc -= sum(a[k] * y[n - k] for k in range(1, len(a)) if n - k >= 0)
        y.append(acc / a[0])
    return y
```

```python tests
import math
h = lfilter([1], [1, -0.5], [1, 0, 0, 0, 0])
assert all(abs(u - v) < 1e-12 for u, v in zip(h, [1, 0.5, 0.25, 0.125, 0.0625])), f"y[n] = 0.5 y[n-1] + x[n] on an impulse should halve each sample, got {h}."
s = lfilter([0.25] * 4, [1], [1] * 6)
assert all(abs(u - v) < 1e-12 for u, v in zip(s, [0.25, 0.5, 0.75, 1, 1, 1])), f"A 4-point average of a step: {s}."
w0 = 2 * math.pi * 60 / 1000; r = 0.98
b = [1, -2 * math.cos(w0), 1]; a = [1, -2 * r * math.cos(w0), r * r]
y = lfilter(b, a, [math.cos(w0 * n) for n in range(2000)])
assert max(abs(v) for v in y[1500:]) < 1e-6, "The 60 Hz notch should remove a 60 Hz tone completely once it settles."
y2 = lfilter(b, a, [math.cos(0.3 * n) + math.cos(w0 * n) for n in range(3000)])
assert 0.95 < max(abs(v) for v in y2[2000:]) < 1.05, "A tone well away from 60 Hz should pass the notch at nearly full size."
assert abs(lfilter([2], [2, -1], [1, 0, 0])[2] - 0.25) < 1e-12, "Divide by a[0]: [2], [2, -1] is y[n] = 0.5 y[n-1] + x[n]."
```

::: right
Right. That's the whole engine of an IIR filter: a few multiply-adds per sample.
:::
:::

::: check
kind: python

## Write `freq_response(b, a, w)`: the complex value $H(e^{j\omega})$ of the filter at frequency w (radians per sample).

```python starter
def freq_response(b, a, w):
    return sum(b) / sum(a)
```

```python solution
import cmath

def freq_response(b, a, w):
    z = cmath.exp(-1j * w)
    num = sum(bk * z ** k for k, bk in enumerate(b))
    den = sum(ak * z ** k for k, ak in enumerate(a))
    return num / den
```

```python tests
import math
assert abs(abs(freq_response([0.25] * 4, [1], 0)) - 1) < 1e-12, "A moving average has gain 1 at DC."
assert abs(freq_response([0.25] * 4, [1], math.pi / 2)) < 1e-12, "A 4-point average has a null at ω = π/2."
assert abs(abs(freq_response([1], [1, -0.5], math.pi)) - 2 / 3) < 1e-12, "1/(1 - 0.5 z^-1) at ω = π is 1/1.5."
w0 = 2 * math.pi * 60 / 1000; r = 0.98
b = [1, -2 * math.cos(w0), 1]; a = [1, -2 * r * math.cos(w0), r * r]
assert abs(freq_response(b, a, w0)) < 1e-9, "The notch's gain at 60 Hz is 0."
assert abs(abs(freq_response(b, a, 0)) - 1.0174513) < 1e-6, "The notch's DC gain is 1.0175."
assert abs(freq_response([1, 1], [1], 0.6) - (1 + complex(math.cos(0.6), -math.sin(0.6)))) < 1e-12, "The value is complex: keep the phase."
```

::: right
Right. Evaluate on a grid of ω and you have a Bode plot of any digital filter.
:::
:::

::: explain
## Why does `lfilter` have to compute the outputs in order, while `convolve` could compute them in any order?

::: model
Convolution's output samples each depend only on the input, which is all known in advance, so every output can be computed independently. A recursive filter's output depends on its own earlier outputs through the feedback terms, so y[n] can't be computed until y[n − 1], y[n − 2], … exist. That chain is what lets a short recursion produce an infinitely long impulse response, and it's also why IIR filters are harder to run in parallel than FIR filters.
:::
:::

::: practice

::: check
given: a = 0.5 | 0.8; n = 2 | 4
answer: a^n
tolerance: 0.5%

## `lfilter([1], [1, -{a}], impulse)[{n}]`?

::: misses
- [any] $a^n$.
:::
:::

::: check
given: M = 4 | 5; n = 0 | 2
answer: (n + 1)/M
tolerance: 0.5%

## An {M}-point average of a step, at n = {n}?

::: misses
- [any] (n + 1)/M.
:::
:::

::: check
given: a = 0.1 | 0.25 | 0.4 | 0.5 | 0.6 | 0.8 | 0.9
answer: 1/(1 + a)
tolerance: 0.5%

## `abs(freq_response([1], [1, -{a}], pi))`?

::: misses
- [any] $1/(1 + a)$.
:::
:::
:::
