---
title: Adaptive filtering lab
heading: LMS system identification, NLMS scale invariance, an echo canceller's ERLE and the Wiener–Hopf solution, in Python
eyebrow: S7 · Lesson 47 · Adaptive filtering lab
xp: 60
---

::: hook
Lessons 34 to 38 developed optimal and adaptive filters on paper. This lab runs them: LMS identifying an unknown system, NLMS shown to behave identically whatever the input level, an echo canceller measured by how much echo it removes, and the Wiener–Hopf equations solved directly for the FIR filter that adaptive filters converge toward.
:::

::: play
- The curve is an echo canceller's best possible echo return loss enhancement (ERLE) when the microphone also picks up independent noise: the echo's power over the noise's, $10\log_{10}(P_\text{echo}/\sigma_n^2)$.
- No canceller can remove the near-end noise, so that ratio bounds what it can achieve; misadjustment takes a little more.
- With an echo of power 0.35 and noise at σ = 0.01, the bound is 35.4 dB.
:::

```sim plot
view: graph
x: s = 0.001..0.1 log
y: E = 0..60 dB
slider: P = 0.1..1 = 0.35
plot: 10*log(P/s^2) | label: ERLE bound
```

::: predict
## An NLMS filter runs on an input and its desired signal, then again on both scaled by 10. With the same step $\tilde\mu$, how do the two weight trajectories compare?

- [ ] The scaled run converges 100 times faster
- [ ] The scaled run diverges
- [x] They are identical, sample for sample
- [ ] The scaled run's weights are 10 times larger

::: reveal
NLMS divides each update by the input's energy $\|\mathbf{x}\|^2$, which scales by 100, while the error times the input scales by 100 too: the update is unchanged. Plain LMS with the same μ would take steps 100 times larger on the scaled data, and here would diverge.
:::
:::

::: nameit
## What the lab computes

- **LMS**: $e = d - \mathbf{w}^T\mathbf{x}$, $\mathbf{w} \leftarrow \mathbf{w} + \mu e\mathbf{x}$, with $\mathbf{x}[n] = [x[n], \dots, x[n - P + 1]]$ and zeros before the start.
- **NLMS**: the step $\tilde\mu/(\delta + \|\mathbf{x}\|^2)$.
- **ERLE**: $10\log_{10}\frac{\sum\text{echo}^2}{\sum e^2}$ over a block after convergence, where e is what's left after the canceller subtracts its echo estimate.
- **Wiener–Hopf**: solve $\sum_kh[k]\phi_{xx}[i - k] = \phi_{sx}[i]$ by Gaussian elimination. For a unit-variance AR(1) signal (a = 0.9) in unit white noise, $\phi_{xx}[m] = 0.9^{|m|} + \delta[m]$ and $\phi_{sx}[m] = 0.9^{|m|}$.
:::

::: check
kind: python

## Write `lms(x, d, P, mu)`: run LMS and return (final weights, list of errors).

```python starter
def lms(x, d, P, mu):
    return ([0.0] * P, [])
```

```python solution
def lms(x, d, P, mu):
    w, errs = [0.0] * P, []
    for n in range(len(x)):
        u = [x[n - k] if n - k >= 0 else 0.0 for k in range(P)]
        e = d[n] - sum(w[i] * u[i] for i in range(P))
        errs.append(e)
        w = [w[i] + mu * e * u[i] for i in range(P)]
    return (w, errs)
```

```python tests
import random
r = random.Random(7)
h = [0.6, -0.4, 0.25, -0.1, 0.05]
x = [r.gauss(0, 1) for _ in range(5000)]
d = [sum(h[k] * x[n - k] for k in range(5) if n - k >= 0) for n in range(5000)]
w, e = lms(x, d, 5, 0.01)
assert max(abs(a - b) for a, b in zip(w, h)) < 1e-6, "Noise-free white input: LMS finds the system."
assert abs(e[-1]) < 1e-6 < abs(e[0]), "The error falls from the first sample to the last."
```

::: right
Right. With white input every mode converges at the same rate, $1/(\mu\sigma_x^2)$ = 100 samples here.
:::
:::

::: check
kind: python

## Write `nlms(x, d, P, mu, delta=1e-12)`: run NLMS and return (final weights, list of errors).

```python starter
def nlms(x, d, P, mu, delta=1e-12):
    return ([0.0] * P, [])
```

```python solution
def nlms(x, d, P, mu, delta=1e-12):
    w, errs = [0.0] * P, []
    for n in range(len(x)):
        u = [x[n - k] if n - k >= 0 else 0.0 for k in range(P)]
        e = d[n] - sum(w[i] * u[i] for i in range(P))
        errs.append(e)
        g = mu / (delta + sum(v * v for v in u))
        w = [w[i] + g * e * u[i] for i in range(P)]
    return (w, errs)
```

```python tests
import random
r = random.Random(7)
h = [0.6, -0.4, 0.25, -0.1, 0.05]
x = [r.gauss(0, 1) for _ in range(300)]
d = [sum(h[k] * x[n - k] for k in range(5) if n - k >= 0) for n in range(300)]
w1, _ = nlms(x, d, 5, 0.5)
w2, _ = nlms([10 * v for v in x], [10 * v for v in d], 5, 0.5)
assert max(abs(a - b) for a, b in zip(w1, w2)) < 1e-12, "Scaling the data by 10 leaves NLMS's weights unchanged."
assert max(abs(a - b) for a, b in zip(w1, h)) < 0.05, "And after 300 samples it is already close."
```

::: right
Right. Level independence is why echo cancellers use NLMS: talkers get loud and quiet without retuning.
:::
:::

::: check
kind: python

## Use your `nlms` idea to write `erle_db(far, echo, noise_sigma, P, mu, seed)`: the microphone hears echo plus Gaussian noise (from `random.Random(seed)`); cancel it with a P-tap NLMS filter and return the ERLE over the last 1000 samples (echo power over residual power).

```python starter
def erle_db(far, echo, noise_sigma, P, mu, seed):
    return 0.0
```

```python solution
import math, random

def erle_db(far, echo, noise_sigma, P, mu, seed):
    r = random.Random(seed)
    mic = [v + r.gauss(0, noise_sigma) for v in echo]
    w, errs = [0.0] * P, []
    for n in range(len(far)):
        u = [far[n - k] if n - k >= 0 else 0.0 for k in range(P)]
        e = mic[n] - sum(w[i] * u[i] for i in range(P))
        errs.append(e)
        g = mu / (1e-6 + sum(v * v for v in u))
        w = [w[i] + g * e * u[i] for i in range(P)]
    return 10 * math.log10(sum(v * v for v in echo[-1000:]) / sum(v * v for v in errs[-1000:]))
```

```python tests
import random
r = random.Random(7)
path = [0.0] * 20
path[3], path[8], path[15] = 0.5, -0.3, 0.1
far = [r.gauss(0, 1) for _ in range(6000)]
echo = [sum(path[k] * far[n - k] for k in range(20) if n - k >= 0) for n in range(6000)]
E = erle_db(far, echo, 0.01, 32, 0.5, 3)
assert 31 < E < 35.5, "Close to, but below, the 35.4 dB set by the near-end noise."
```

::: right
Right. The near-end noise passes through untouched, and the step size's misadjustment takes another decibel or so.
:::
:::

::: check
kind: python

## Write `solve(A, b)` (Gaussian elimination with partial pivoting) and `wiener_ar1(a, noise_var, P)`: the P-tap FIR Wiener filter for a unit-variance AR(1) signal with coefficient a in white noise of variance noise_var.

```python starter
def solve(A, b):
    return b

def wiener_ar1(a, noise_var, P):
    return [0.0] * P
```

```python solution
def solve(A, b):
    n = len(b)
    M = [list(map(float, A[i])) + [float(b[i])] for i in range(n)]
    for i in range(n):
        p = max(range(i, n), key=lambda r: abs(M[r][i]))
        M[i], M[p] = M[p], M[i]
        for r in range(i + 1, n):
            f = M[r][i] / M[i][i]
            M[r] = [u - f * v for u, v in zip(M[r], M[i])]
    x = [0.0] * n
    for i in reversed(range(n)):
        x[i] = (M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))) / M[i][i]
    return x

def wiener_ar1(a, noise_var, P):
    A = [[a ** abs(i - j) + (noise_var if i == j else 0) for j in range(P)] for i in range(P)]
    return solve(A, [a ** i for i in range(P)])
```

```python tests
h2 = wiener_ar1(0.9, 1.0, 2)
assert abs(h2[0] - 0.3730) < 1e-4 and abs(h2[1] - 0.2821) < 1e-4, "Lesson 36's two-tap example: 0.373 and 0.282."
h3 = wiener_ar1(0.9, 1.0, 3)
assert abs(h3[0] - 0.3298) < 1e-4 and abs(h3[2] - 0.1702) < 1e-4, "Three taps: 0.330, 0.225, 0.170."
assert abs(wiener_ar1(0.9, 1e-9, 3)[0] - 1) < 1e-6, "Without noise the best estimate of s[n] is x[n] itself."
```

::: right
Right. LMS on this data would wander around exactly these weights.
:::
:::

::: explain
## Why can an echo canceller never remove more than the ratio of echo to near-end noise, however long it adapts?

::: model
The canceller builds an estimate of the echo from the far-end signal, which is all it can see, and subtracts it from the microphone signal. The near-end noise, and the near-end talker's speech, are uncorrelated with the far-end signal, so no filter of the far-end signal can predict or cancel them; they pass through to the residual. Even a perfect echo estimate therefore leaves the noise behind, so the echo return loss enhancement is bounded by the echo's power over the noise's. Adaptation noise, the misadjustment, adds a little more residual on top.
:::
:::
