---
title: "Project: characterizing a filter from noisy data"
heading: Measuring a Bode plot and fitting its corner
eyebrow: C11 · Lesson 28 · Project: characterizing a filter from noisy data
xp: 60
---

::: hook
A filter on the bench, a function generator on its input and a two-channel scope on its input and output: that's the setup for measuring a frequency response. At each frequency the scope captures a noisy record of both channels. A cursor reading of each trace's peak would be crude; a few lines of code give the amplitude and phase of each sine to a fraction of a percent, even through noise, by projecting each record onto a sine and cosine at the known frequency (lesson 16's lock-in, done in software). Then a least-squares fit turns a dozen noisy gain readings into one corner frequency. In this project you'll write all three steps.
:::

::: play
- The dots are six measured gains of an RC low-pass, each with a few tenths of a dB of noise. The curve is the first-order model $-10\log_{10}(1 + (f/f_c)^2)$ for the corner you choose.
- The readout is the sum of squared differences between the dots and the curve. Move $f_c$ to make it as small as you can: that's a least-squares fit, done by hand.
- The best fit lands within a few hertz of the true 1.59 kHz, even though no single dot sits exactly on the true curve.
:::
:::

```sim plot
view: graph
x: f = 50..50k Hz log
y: g = -30..3 dB
slider: fc = 300..8000 = 800 Hz log
plot: -10*log(1 + (f/fc)^2) | label: model
point: 100, 0.13
point: 300, -0.35
point: 1000, -1.15
point: 3000, -6.83
point: 10000, -15.67
point: 30000, -25.82
readout: sum of squared errors, dB² = (0.13 + 10*log(1 + (100/fc)^2))^2 + (-0.35 + 10*log(1 + (300/fc)^2))^2 + (-1.15 + 10*log(1 + (1000/fc)^2))^2 + (-6.83 + 10*log(1 + (3000/fc)^2))^2 + (-15.67 + 10*log(1 + (10000/fc)^2))^2 + (-25.82 + 10*log(1 + (30000/fc)^2))^2 | digits: 3
```

::: predict
## A filter's output measures −1.45 dB relative to its input at 1 kHz. If it's a first-order low-pass, where is its corner?

- [ ] About 1 kHz
- [x] About 1.6 kHz
- [ ] About 3 kHz
- [ ] Below 1 kHz

::: reveal
About 1.6 kHz. Solving $-10\log_{10}(1 + (f/f_c)^2) = -1.45$ gives $(f/f_c)^2 = 10^{0.145} - 1 = 0.396$, so $f_c = 1000/0.629 = 1.59$ kHz. A single reading this close to 0 dB is sensitive to noise, though: a 0.1 dB error moves the answer by about 4%. A fit over many frequencies does much better.
:::
:::

::: nameit
## The pieces

**Amplitude and phase by projection.** Over a whole number of periods of frequency f, a record v(t) of N samples gives

$$a = \frac{2}{N}\sum v_k\cos(2\pi ft_k), \qquad b = \frac{2}{N}\sum v_k\sin(2\pi ft_k)$$

and if $v = A\cos(2\pi ft + \varphi)$ plus noise and any DC, then $a \approx A\cos\varphi$ and $b \approx -A\sin\varphi$:

$$A = \sqrt{a^2 + b^2}, \qquad \varphi = \operatorname{atan2}(-b, a)$$

The DC and the noise at other frequencies average out over whole periods.

**A Bode point.** With amplitude and phase for input and output at the same frequency, the gain is $20\log_{10}(A_\text{out}/A_\text{in})$ dB and the phase is $\varphi_\text{out} - \varphi_\text{in}$, wrapped into −180° to 180°.

**The fit.** For a first-order low-pass, $G(f) = -10\log_{10}(1 + (f/f_c)^2)$. Choose $f_c$ to minimize $\sum(G_i - G(f_i))^2$. Search in $\ln f_c$, since corners span decades: a coarse scan finds the valley, then golden-section search narrows it.

## Single-point formulas

From one gain reading, $f_c = f/\sqrt{10^{-G/10} - 1}$; from one phase reading, $f_c = f/\tan(-\varphi)$. They're useful checks, but each rests on one noisy number.
:::

::: example
## Projection of a record at 1 kHz gives a = 0.537 V and b = 0.273 V. What are the amplitude and phase?

::: solution
1. **Amplitude.**
   $$\begin{aligned} A &= \sqrt{0.537^2 + 0.273^2}\ \text{V} \\ &= 0.602\ \text{V} \end{aligned}$$
2. **Phase.**
   $$\begin{aligned} \varphi &= \operatorname{atan2}(-0.273, 0.537) \\ &= -26.9° \end{aligned}$$

**Answer:** an amplitude of 0.602 V and a phase of −26.9°.
:::
:::

::: example
## A low-pass shows −32.1° of phase at 1 kHz. Where is its corner?

::: solution
1. **Corner from the phase.**
   $$\begin{aligned} f_c &= \frac{1000}{\tan 32.1°}\ \text{Hz} \\ &= 1.59\ \text{kHz} \end{aligned}$$
   This agrees with the gain reading.
2. **Where phase works best.** Phase is most sensitive near the corner, where it changes fastest, so phase readings between 0.3 and 3 times $f_c$ give the best single-point estimates.

**Answer:** the corner is at 1.59 kHz.
:::
:::

::: check
given: f = 500 | 1000 | 2000; G = -0.5 | -2 | -6
answer: f/sqrt(10^(-G/10) - 1)
unit: Hz
tolerance: 0.5%

## A first-order low-pass measures {G} dB at {f} Hz. Where is its corner?

::: right
Right. $f/\sqrt{10^{-G/10} - 1}$ = {answer} Hz.
:::

::: misses
- [f/sqrt(10^(-G/20) - 1)] The model is $10\log_{10}(1 + (f/f_c)^2)$: use $10^{-G/10}$.
- [any] Not yet. Solve $-10\log_{10}(1 + (f/f_c)^2) = G$ for $f_c$.
:::
:::

::: check
given: f = 200 | 1000 | 5000; p = 15 | 40 | 70
answer: f/tan(p*pi/180)
unit: Hz
tolerance: 0.5%

## A first-order low-pass shows −{p}° of phase at {f} Hz. Where is its corner?

::: right
Right. $f/\tan(-\varphi)$ = {answer} Hz.
:::

::: misses
- [f*tan(p*pi/180)] The phase is $-\arctan(f/f_c)$, so $f_c = f/\tan(-\varphi)$.
- [any] Not yet. $f_c = f/\tan(-\varphi)$.
:::
:::

::: check
given: a = 0.3 | 0.8 | 1.5; b = -0.6 | 0.2 | 0.9
answer: sqrt(a^2 + b^2)
unit: V
tolerance: 0.5%

## Projection gives a = {a} V and b = {b} V. What is the sine's amplitude?

::: right
Right. $\sqrt{a^2 + b^2}$ = {answer} V.
:::

::: misses
- [a + b] Combine them as the sides of a right triangle.
- [any] Not yet. $\sqrt{a^2 + b^2}$.
:::
:::

::: check
given: Ai = 0.5 | 1 | 2; Ao = 0.05 | 0.3 | 0.45
answer: 20*log(Ao/Ai)
unit: dB
tolerance: 0.5%

## The input's amplitude is {Ai} V and the output's {Ao} V. What is the gain in dB?

::: right
Right. $20\log_{10}(A_\text{out}/A_\text{in})$ = {answer} dB.
:::

::: misses
- [10*log(Ao/Ai)] Amplitudes are voltages: 20 log.
- [any] Not yet. $20\log_{10}$ of the ratio.
:::
:::

::: check
kind: python

## Write `amp_phase(t, v, f)`: t and v are lists of sample times and values covering a whole number of periods of frequency f. Return `(A, phi)`, the amplitude and phase (radians) of the component $A\cos(2\pi ft + \varphi)$, by projection.

```python starter
def amp_phase(t, v, f):
    return max(v), 0.0
```

```python solution
import math

def amp_phase(t, v, f):
    w = 2 * math.pi * f
    n = len(v)
    a = 2 / n * sum(x * math.cos(w * tt) for tt, x in zip(t, v))
    b = 2 / n * sum(x * math.sin(w * tt) for tt, x in zip(t, v))
    return math.hypot(a, b), math.atan2(-b, a)
```

```python tests
import math, random
fs, N, f = 100000.0, 2000, 1000.0
t = [i / fs for i in range(N)]
v = [0.7 * math.cos(2 * math.pi * f * tt - 0.4) for tt in t]
A, p = amp_phase(t, v, f)
assert abs(A - 0.7) < 1e-9 and abs(p + 0.4) < 1e-9, f"A clean 0.7 V sine at phase -0.4 rad: got A = {A}, phi = {p}."
random.seed(5)
v = [0.3 + 0.7 * math.cos(2 * math.pi * f * tt - 0.4) + random.gauss(0, 0.2) for tt in t]
A, p = amp_phase(t, v, f)
assert abs(A - 0.7) < 0.03 and abs(p + 0.4) < 0.04, f"With 0.3 V of DC and 0.2 V of noise the estimate should stay near 0.7 V and -0.4 rad; got {A:.4f}, {p:.4f}. Is the DC leaking in?"
v = [2 * math.sin(2 * math.pi * f * tt) for tt in t]
A, p = amp_phase(t, v, f)
assert abs(A - 2) < 1e-9 and abs(p + math.pi / 2) < 1e-9, f"2 sin(wt) is 2 cos(wt - pi/2); got {A}, {p}."
```

::: right
Right. That's a lock-in amplifier in four lines.
:::
:::

::: check
kind: python

## Write `bode_point(t, vin, vout, f)`: return `(gain_db, phase_deg)` of the output relative to the input at frequency f, with the phase wrapped into −180° to 180°. Use your `amp_phase` (or the projection inside it).

```python starter
def bode_point(t, vin, vout, f):
    return 0.0, 0.0
```

```python solution
import math

def amp_phase(t, v, f):
    w = 2 * math.pi * f
    n = len(v)
    a = 2 / n * sum(x * math.cos(w * tt) for tt, x in zip(t, v))
    b = 2 / n * sum(x * math.sin(w * tt) for tt, x in zip(t, v))
    return math.hypot(a, b), math.atan2(-b, a)

def bode_point(t, vin, vout, f):
    ai, pin = amp_phase(t, vin, f)
    ao, pout = amp_phase(t, vout, f)
    d = math.degrees(pout - pin)
    d = (d + 180) % 360 - 180
    return 20 * math.log10(ao / ai), d
```

```python tests
import math, random
fc = 1591.55
def record(fr, seed):
    random.seed(seed)
    fs = 200 * fr
    n = 4000
    t = [i / fs for i in range(n)]
    H = 1 / complex(1, fr / fc)
    ph = math.atan2(H.imag, H.real)
    vin = [math.cos(2 * math.pi * fr * tt + 2.5) + random.gauss(0, 0.05) for tt in t]
    vout = [abs(H) * math.cos(2 * math.pi * fr * tt + 2.5 + ph) + random.gauss(0, 0.05) for tt in t]
    return t, vin, vout
for fr in (100.0, 1000.0, 10000.0):
    t, vi, vo = record(fr, 1)
    g, p = bode_point(t, vi, vo, fr)
    gt = -10 * math.log10(1 + (fr / fc) ** 2)
    pt = -math.degrees(math.atan(fr / fc))
    assert abs(g - gt) < 0.3, f"At {fr:.0f} Hz the gain should be near {gt:.2f} dB; got {g:.2f}."
    assert abs(p - pt) < 1.5, f"At {fr:.0f} Hz the phase should be near {pt:.1f} degrees; got {p:.1f}. Is it wrapped into -180 to 180?"
```

::: right
Right. Sweep that over frequency and you have a network analyzer.
:::
:::

::: check
kind: python

## Write `fit_corner(f, g)`: f is a list of frequencies and g the measured gains in dB of a first-order low-pass. Return the corner frequency $f_c$ that minimizes $\sum(g_i + 10\log_{10}(1 + (f_i/f_c)^2))^2$.

```python starter
import math

def fit_corner(f, g):
    return f[len(f) // 2]
```

```python solution
import math

def fit_corner(f, g):
    def cost(lfc):
        fc = math.exp(lfc)
        return sum((gi + 10 * math.log10(1 + (fi / fc) ** 2)) ** 2 for fi, gi in zip(f, g))
    lo, hi = math.log(min(f) / 10), math.log(max(f) * 10)
    steps = 400
    best = min(range(steps + 1), key=lambda k: cost(lo + (hi - lo) * k / steps))
    a = lo + (hi - lo) * max(best - 1, 0) / steps
    b = lo + (hi - lo) * min(best + 1, steps) / steps
    r = (math.sqrt(5) - 1) / 2
    for _ in range(80):
        c = b - r * (b - a)
        d = a + r * (b - a)
        if cost(c) < cost(d):
            b = d
        else:
            a = c
    return math.exp((a + b) / 2)
```

```python tests
import math, random
fl = [100 * 10 ** (k / 4) for k in range(13)]
gl = [-10 * math.log10(1 + (x / 2200.0) ** 2) for x in fl]
got = fit_corner(fl, gl)
assert abs(got / 2200 - 1) < 1e-4, f"Noise-free data from a 2200 Hz corner should fit to 2200 Hz; got {got:.2f}."
random.seed(9)
gl = [-10 * math.log10(1 + (x / 2200.0) ** 2) + random.gauss(0, 0.3) for x in fl]
got = fit_corner(fl, gl)
assert abs(got / 2200 - 1) < 0.02, f"With 0.3 dB of noise the fit should land within 2% of 2200 Hz; got {got:.1f}."
pts = [(100, 0.13), (300, -0.35), (1000, -1.15), (3000, -6.83), (10000, -15.67), (30000, -25.82)]
got = fit_corner([p[0] for p in pts], [p[1] for p in pts])
assert abs(got - 1590) < 10, f"The lesson's six points fit to about 1590 Hz; got {got:.1f}."
```

::: right
Right. Twelve noisy readings, one corner known to about 1%.
:::
:::

::: explain
## Why does fitting a model to many gain readings give a better corner frequency than solving for it from the single reading nearest the corner?

::: model
Each reading carries its own random error, and solving for the corner from one reading passes that error straight into the answer. A least-squares fit uses every reading at once: the random errors at different frequencies are independent, so they partly cancel, and the corner that best explains all of them is much less sensitive to any one. Readings far from the corner also pin down the model's shape (flat below, falling 20 dB per decade above), so the fit uses information a single point can't. The error of the fit shrinks roughly as one over the square root of the number of useful readings.
:::
:::

::: practice

::: check
given: f = 800 | 3000; G = -1 | -3 | -10
answer: f/sqrt(10^(-G/10) - 1)
unit: Hz
tolerance: 0.5%

## Corner from {G} dB at {f} Hz?

::: misses
- [any] $f/\sqrt{10^{-G/10} - 1}$.
:::
:::

::: check
given: f = 300 | 4000; p = 25 | 60
answer: f/tan(p*pi/180)
unit: Hz
tolerance: 0.5%

## Corner from −{p}° at {f} Hz?

::: misses
- [any] $f/\tan(-\varphi)$.
:::
:::

::: check
given: a = 0.4 | 1.2; b = -0.5 | 0.7
answer: sqrt(a^2 + b^2)
unit: V
tolerance: 0.5%

## Amplitude from a = {a} V, b = {b} V?

::: misses
- [any] $\sqrt{a^2 + b^2}$.
:::
:::
:::
