---
title: Correlation and convolution lab
heading: Correlating, finding periods, and undoing a filter in Python
eyebrow: C9 · Lesson 12 · Correlation and convolution lab
xp: 50
---

::: hook
The last few lessons built a toolkit on paper: convolution, impulse responses, difference equations and correlation. In this lab you'll write the pieces that use them on real data: a full cross-correlation, a period finder that works through noise, a deconvolver that recovers an input from a filter's output, the inverse of an echo, and a matched-filter detector that finds every copy of a pulse in a noisy record.
:::

::: play
- The first stems are an echo, $h[n] = \delta[n] + a\,\delta[n - D]$: the sound, then a copy D samples later scaled by a.
- The second stems are its inverse, $h_\text{inv}[n] = (-a)^{n/D}$ at multiples of D: each term cancels the echo the previous term made.
- Raise a toward 1: the inverse decays more and more slowly. Past 1, an echo louder than the sound itself, the inverse grows without bound and can't be used.
:::

```sim plot
view: graph
x: n = 0..30
y: h = -1.6..1.6
slider: a = -1.2..1.2 step 0.05 = 0.6
slider: D = 2..6 step 1 = 3
plot: step(0.5 - abs(n)) + a*step(0.5 - abs(n - D)) | stems | label: echo h
plot: 0.8*(-a)^floor(n/D)*step(0.5 - (n - D*floor(n/D))) | stems | label: inverse (scaled 0.8)
readout: sum of the inverse's magnitudes = 1/(1 - abs(a) + 0.0000001)*step(1 - abs(a)) + 99999*step(abs(a) - 1) | digits: 4
```

::: predict
## A recording has an echo 0.6 times as loud, 3 samples late. After how many samples has its inverse filter's response fallen below 1% of its first value?

- [ ] 3
- [ ] 9
- [x] 30
- [ ] It never does

::: reveal
30: the inverse's terms are $0.6^k$ at n = 3k. $0.6^9 = 0.0101$ is still just above 1%, and $0.6^{10} = 0.006$ is the first below, at n = 30. An echo at 0.9 would need 44 terms, 132 samples. A weak echo is easy to remove; a strong one takes a long inverse filter.
:::
:::

::: nameit
## The tools

- **Cross-correlation**: $r_{xy}[k] = \sum_n x[n + k]\,y[n]$, for every lag k where the two overlap, from $-(L_y - 1)$ to $L_x - 1$.
- **Periods from autocorrelation**: a periodic signal correlates strongly with itself shifted by one period. Skipping the lags where $r_{xx}$ is still positive from the main peak, the next highest point is the period. Noise adds mostly to lag 0, so this works where watching for zero crossings fails.
- **Deconvolution**: if y = x * h and h[0] ≠ 0, the convolution sum can be run backward one sample at a time: $x[n] = \big(y[n] - \sum_{k \ge 1} h[k]\,x[n - k]\big)/h[0]$. It's the inverse filter, applied as a recursion.
- **Matched-filter detection**: correlate with the known pulse, and report each lag where the result is a local maximum above a set fraction of the pulse's energy.
:::

::: example
## Deconvolve y = [1, 2.5, 4, 5.5, 2] by h = [1, 0.5].

::: solution
1. **First sample.**
   $$\begin{aligned} x[0] &= 1/1 \\ &= 1 \end{aligned}$$
2. **Peel off the echo.** Each sample takes away 0.5 times the one before:
   $$\begin{aligned} x[1] &= (2.5 - 0.5 \times 1)/1 \\ &= 2 \\ x[2] &= 4 - 0.5 \times 2 \\ &= 3 \\ x[3] &= 5.5 - 0.5 \times 3 \\ &= 4 \end{aligned}$$
3. **Check.** Indeed [1, 2, 3, 4] * [1, 0.5] = [1, 2.5, 4, 5.5, 2]. The last sample of y isn't needed: it's a check.

**Answer:** x = [1, 2, 3, 4].
:::
:::

::: example
## The autocorrelation of a 25-sample-period sine is computed over 200 samples. Where are its first negative value and its next peak?

::: solution
1. **Shape of the autocorrelation.**
   $$r[k] \approx \tfrac12\cos(2\pi k/25)$$
   times the number of overlapping samples.
2. **First negative value.** It first goes negative past a quarter period, at k = 7.
3. **Next peak.** It peaks again at k = 25, a full period. The peak at 50 is lower, because fewer samples overlap at larger lags.

**Answer:** the first negative value is at k = 7, and the next peak is at k = 25.
:::
:::

::: check
given: a = 0.3 | 0.6 | 0.9; D = 2 | 3 | 5
answer: D*ceil(ln(0.01)/ln(a) - 0.000001)
tolerance: 0

## An echo of {a}, {D} samples late. At what sample does its inverse's response first fall to 1% of its start or below?

::: right
Right: n = {answer}.
:::

::: misses
- [ceil(ln(0.01)/ln(a) - 0.000001)] That's the number of terms; each term is {D} samples apart.
- [any] Not yet. Find the first k with $a^k \le 0.01$; the term is at n = kD.
:::
:::

::: check
kind: python

## Write `xcorr(x, y)`: the cross-correlation $r_{xy}[k] = \sum_n x[n + k]\,y[n]$ for every lag k from $-(\text{len}(y) - 1)$ to $\text{len}(x) - 1$, as a list in that order.

```python starter
def xcorr(x, y):
    return [sum(a * b for a, b in zip(x, y))]
```

```python solution
def xcorr(x, y):
    out = []
    for k in range(-(len(y) - 1), len(x)):
        out.append(sum(x[n + k] * y[n] for n in range(len(y)) if 0 <= n + k < len(x)))
    return out
```

```python tests
assert xcorr([1, 2, 3], [1, 2, 3]) == [3, 8, 14, 8, 3], f"The autocorrelation of [1, 2, 3] is [3, 8, 14, 8, 3], got {xcorr([1, 2, 3], [1, 2, 3])}."
assert xcorr([1, 0, 0], [0, 1]) == [1, 0, 0, 0], f"[1, 0, 0] against [0, 1] matches only at lag -1: [1, 0, 0, 0], got {xcorr([1, 0, 0], [0, 1])}."
assert xcorr([2, -1, 3, 0], [1, 1]) == [2, 1, 2, 3, 0], f"Expected [2, 1, 2, 3, 0], got {xcorr([2, -1, 3, 0], [1, 1])}."
assert xcorr([1, 2], [3]) == [3, 6], "A one-sample y just scales x."
```

::: right
Right. Each lag is one dot product of the overlapping parts.
:::
:::

::: check
kind: python

## Write `period(x)`: compute the autocorrelation for lags 0 to len(x) // 2 − 1, skip lags until it first goes negative, and return the lag of the highest value after that.

```python starter
def period(x):
    return 1
```

```python solution
def period(x):
    n = len(x)
    r = [sum(x[i] * x[i + k] for i in range(n - k)) for k in range(n // 2)]
    k = 1
    while k < len(r) and r[k] >= 0:
        k += 1
    return max(range(k, len(r)), key=lambda j: r[j])
```

```python tests
import math, random
s25 = [math.sin(2 * math.pi * i / 25) for i in range(200)]
assert period(s25) == 25, f"A sine with a 25-sample period, got {period(s25)}."
sq16 = [1 if (i // 8) % 2 == 0 else -1 for i in range(160)]
assert period(sq16) == 16, f"A square wave with a 16-sample period, got {period(sq16)}."
saw = [(i % 30) / 30 - 0.5 for i in range(300)]
assert period(saw) == 30, f"A sawtooth with a 30-sample period, got {period(saw)}."
random.seed(7)
noisy = [math.sin(2 * math.pi * i / 40) + random.gauss(0, 0.5) for i in range(400)]
assert abs(period(noisy) - 40) <= 1, f"A 40-sample sine in noise should come out within a sample of 40, got {period(noisy)}."
```

::: right
Right. That's the core of many pitch detectors.
:::
:::

::: check
kind: python

## Write `deconvolve(y, h)`: given y = x * h with h[0] ≠ 0, return x, which has len(y) − len(h) + 1 samples.

```python starter
def deconvolve(y, h):
    return y[:len(y) - len(h) + 1]
```

```python solution
def deconvolve(y, h):
    x = []
    for n in range(len(y) - len(h) + 1):
        acc = y[n] - sum(h[k] * x[n - k] for k in range(1, min(n, len(h) - 1) + 1))
        x.append(acc / h[0])
    return x
```

```python tests
def conv(a, b):
    return [sum(a[i] * b[n - i] for i in range(len(a)) if 0 <= n - i < len(b)) for n in range(len(a) + len(b) - 1)]
for x, h in [([1, 2, 3, 4], [1, 0.5]), ([3, -1, 2], [2, 1, 1]), ([0.5, 0, -2, 1, 4], [1, -0.9, 0.2])]:
    got = deconvolve(conv(x, h), h)
    assert len(got) == len(x) and all(abs(a - b) < 1e-9 for a, b in zip(got, x)), f"Deconvolving {h} should give back {x}, got {got}."
```

::: right
Right. It's exact without noise; with noise, dividing by a small h[0] or a nearly unstable inverse amplifies it.
:::
:::

::: check
kind: python

## Write `echo_inverse(a, D, N)`: the first N samples of the inverse of the echo $\delta[n] + a\,\delta[n - D]$.

```python starter
def echo_inverse(a, D, N):
    return [1] + [0] * (N - 1)
```

```python solution
def echo_inverse(a, D, N):
    return [(-a) ** (n // D) if n % D == 0 else 0 for n in range(N)]
```

```python tests
got = echo_inverse(0.5, 3, 10)
want = [1, 0, 0, -0.5, 0, 0, 0.25, 0, 0, -0.125]
assert all(abs(u - v) < 1e-12 for u, v in zip(got, want)) and len(got) == 10, f"Expected {want}, got {got}."
def conv(a, b):
    return [sum(a[i] * b[n - i] for i in range(len(a)) if 0 <= n - i < len(b)) for n in range(len(a) + len(b) - 1)]
check = conv([1, 0, 0, 0, 0.8], echo_inverse(0.8, 4, 40))[:40]
assert all(abs(u - v) < 1e-12 for u, v in zip(check, [1] + [0] * 39)), "The echo convolved with its inverse should give an impulse."
```

::: right
Right. Convolving the two cancels every echo except the far tail beyond N.
:::
:::

::: check
kind: python

## Write `detect(y, pulse, threshold)`: correlate y with the pulse at every lag k where the pulse fits (0 to len(y) − len(pulse)), and return the lags whose value is at least `threshold` times the pulse's energy and is the largest within len(pulse) − 1 lags either side.

```python starter
def detect(y, pulse, threshold):
    return []
```

```python solution
def detect(y, pulse, threshold):
    E = sum(p * p for p in pulse)
    L = len(pulse)
    r = [sum(pulse[n] * y[k + n] for n in range(L)) for k in range(len(y) - L + 1)]
    hits = []
    for k, v in enumerate(r):
        if v >= threshold * E and all(v >= r[j] for j in range(max(0, k - L + 1), min(len(r), k + L))):
            hits.append(k)
    return hits
```

```python tests
import random
pulse = [1, 1, 1, -1, -1, 1, -1]
clean = [0] * 60
for at in (5, 40):
    for i, p in enumerate(pulse):
        clean[at + i] += p
assert detect(clean, pulse, 0.5) == [5, 40], f"Two pulses, at 5 and 40, got {detect(clean, pulse, 0.5)}."
random.seed(11)
noisy = [v + random.gauss(0, 0.6) for v in clean]
assert detect(noisy, pulse, 0.5) == [5, 40], f"The same two in noise, got {detect(noisy, pulse, 0.5)}."
assert detect([0] * 30, pulse, 0.5) == [], "Nothing to find in silence."
```

::: right
Right. A matched filter, a threshold and a peak picker: the skeleton of every radar and modem receiver.
:::
:::

::: explain
## Why does the autocorrelation find a period in noise more reliably than counting zero crossings?

::: model
Zero crossings depend on individual samples near zero, and noise moves those samples back and forth across zero, adding false crossings. The autocorrelation at a lag adds up products over the whole record, so the periodic part reinforces itself at a lag of one period while the noise, which is uncorrelated from sample to sample, contributes products of random sign that largely cancel. White noise adds its power only at lag 0, which the method skips. The longer the record, the more the sum averages the noise away, so the peak at the true period stands out clearly even when the waveform itself is hard to see.
:::
:::
