---
title: "Lab: noise in code"
heading: Generating, filtering, averaging and measuring noise
eyebrow: A11 · Lesson 47 · Lab: noise in code
xp: 60
---

::: hook
Lessons 32 and 33, and 40 to 42, described noise by its statistics: its RMS, its autocorrelation, its power spectral density, and how filtering and averaging change them. In this lab you'll generate white Gaussian noise and measure its crest factor, smooth it with a moving average and a one-pole filter and check the output noise against the formulas, estimate its spectrum by averaging periodograms, and pull a weak repeated signal out of noise by averaging triggered records.
:::

::: play
- The solid curve is a one-pole low-pass's power gain $\frac{1}{1 + (f/f_c)^2}$; the dashed box is the ideal filter that would pass the same white-noise power.
- The box's width, $\frac\pi2f_c$, is the filter's **noise bandwidth**: 57% wider than its 3 dB corner, because of the long skirt.
- Change $f_c$: both scale together. The ratio is fixed by the filter's shape.
:::

```sim plot
view: graph
x: f = 0..10 kHz
y: gain = 0..1.1
slider: fc = 0.5..3 step 0.1 = 1 kHz
plot: 1/(1 + (f/fc)^2) | label: power gain |H|² | samples: 600
plot: step(pi/2*fc - f) | dashed | color: ch2 | label: equivalent ideal filter | samples: 600
readout: noise bandwidth, kHz = pi/2*fc | digits: 4
```

::: predict
## White noise of RMS 1 passes through a 16-point moving average. What RMS comes out?

- [ ] 1/16
- [x] 1/4
- [ ] 1/2
- [ ] 1, since averaging doesn't change noise

::: reveal
1/4. Each output is the mean of 16 independent samples, so its variance is $\frac{1}{16}$ and its RMS $\frac14$. Successive outputs share 15 of their 16 samples, so they're strongly correlated, but each one alone has that spread.
:::
:::

::: nameit
## White noise

`rng.normal(0, sigma, n)` gives independent Gaussian samples: white noise, with equal power at every frequency up to half the sample rate.

## Filtering

- A **moving average** of $N$ samples divides the noise variance by $N$: `np.convolve(x, np.ones(N) / N, mode="valid")`.
- A **one-pole low-pass**, $y_n = ay_{n-1} + (1 - a)x_n$, passes a fraction $\frac{1 - a}{1 + a}$ of white noise's variance; it's the discrete version of an RC filter, with time constant about $\frac{1}{1 - a}$ samples.

## Estimating a spectrum

A single periodogram, $\frac{|X_k|^2}{N}$ from one FFT, scatters by 100% around the true density. Averaging $M$ periodograms of separate segments (Bartlett's method) reduces the scatter to about $\frac{1}{\sqrt M}$.

## Synchronous averaging

If a signal repeats exactly and you can trigger on it, averaging $M$ records keeps the signal and divides the noise's RMS by $\sqrt M$: a 20 dB SNR gain for $M = 100$.
:::

::: example
## A one-pole filter $y_n = 0.9y_{n-1} + 0.1x_n$ smooths unit white noise. What output RMS should you measure?

::: solution
1. **Output variance.**
   $$\begin{aligned} \frac{1 - a}{1 + a} &= \frac{0.1}{1.9} \\ &= 0.0526 \end{aligned}$$
   an RMS of 0.229.
2. **Equivalent moving average.** A moving average with the same noise reduction would need
   $$\frac{1}{0.0526} = 19\ \text{points}$$
3. **Why it's popular.** The one-pole filter gets it with one multiply-add per sample and one stored value, which is why it's the standard cheap smoother in firmware.

**Answer:** you should measure an output RMS of 0.229.
:::
:::

::: example
## A 0.1 V repeated pulse sits in 1 V RMS of noise. How many triggered records must be averaged to see it with an SNR of 10 in amplitude?

::: solution
1. **One record.** One record has amplitude SNR 0.1.
2. **Average $M$ records.** That divides the noise by $\sqrt M$, so the SNR is $0.1\sqrt M$:
   $$0.1\sqrt M = 10 \quad\text{needs}\quad M = 10\,000$$
3. **With 64 records.** The noise falls to $\frac18$ V, an SNR of 0.8: the pulse becomes visible but not clean.

**Answer:** 10 000 records.
:::
:::

::: check
given: N = 4 | 16 | 100; s = 1 | 5
answer: s/sqrt(N)
tolerance: 0.5%

## White noise of RMS {s} passes through an {N}-point moving average. What RMS comes out?

::: right
Right. {answer}.
:::

::: misses
- [s/N] The variance falls by $N$; the RMS by $\sqrt N$.
- [any] Not yet. Averaging $N$ independent samples divides the variance by $N$.
:::
:::

::: check
given: a = 0.5 | 0.9 | 0.99
answer: sqrt((1 - a)/(1 + a))
tolerance: 0.5%

## Unit white noise passes through $y_n = \given{a}y_{n-1} + (1 - \given{a})x_n$. What RMS comes out?

::: right
Right. $\sqrt{\frac{1 - a}{1 + a}}$ = {answer}.
:::

::: misses
- [1 - a] That's the input weight, not the output spread.
- [(1 - a)/(1 + a)] That's the variance; take the square root.
- [any] Not yet. The output variance is $\frac{1 - a}{1 + a}$.
:::
:::

::: check
kind: python

## Generate 10⁵ samples of unit white Gaussian noise (`np.random.default_rng(1)`) and set `crest` to the largest absolute value divided by the RMS.

```python starter
import numpy as np

crest = 1.0
print(crest)
```

```python solution
import numpy as np

rng = np.random.default_rng(1)
n = rng.normal(size=10**5)
crest = np.max(np.abs(n)) / np.sqrt(np.mean(n**2))
print(crest)
```

```python tests
assert 4 < crest < 5.5, f"In 1e5 samples the largest peak is typically 4.3 to 5 sigma; got {crest}."
```

::: right
Right. Gaussian noise has no fixed peak, but in a hundred thousand samples it reaches about 4.5σ.
:::
:::

::: check
kind: python

## Pass 10⁶ unit white noise samples (`np.random.default_rng(2)`) through a 16-point moving average, and set `ratio` to the input RMS divided by the output RMS.

```python starter
import numpy as np

ratio = 1.0
print(ratio)
```

```python solution
import numpy as np

rng = np.random.default_rng(2)
x = rng.normal(size=10**6)
y = np.convolve(x, np.ones(16) / 16, mode="valid")
ratio = x.std() / y.std()
print(ratio)
```

```python tests
assert abs(ratio - 4) < 0.08, f"A 16-point average divides the noise RMS by 4; got {ratio}."
```

::: right
Right. A factor of 4, as $\sqrt{16}$ predicts.
:::
:::

::: check
kind: python

## Filter 10⁵ unit white noise samples (`np.random.default_rng(3)`) with $y_n = 0.9y_{n-1} + 0.1x_n$ (a plain loop is fine). Set `var_out` to the variance of the output after the first 1000 samples, and `formula` to $\frac{1 - a}{1 + a}$.

```python starter
import numpy as np

var_out = formula = 0.0
print(var_out, formula)
```

```python solution
import numpy as np

rng = np.random.default_rng(3)
x = rng.normal(size=10**5)
y = np.zeros_like(x)
a = 0.9
for i in range(1, len(x)):
    y[i] = a * y[i - 1] + (1 - a) * x[i]
var_out = y[1000:].var()
formula = (1 - a) / (1 + a)
print(var_out, formula)
```

```python tests
assert abs(formula - 0.0526316) < 1e-6, "formula should be 0.1/1.9."
assert abs(var_out / formula - 1) < 0.05, f"The output variance should match 0.0526 within 5%; got {var_out}."
```

::: right
Right. One stored value and one multiply-add per sample cut the noise power 19 times.
:::
:::

::: check
kind: python

## Estimate the spectrum of unit white noise by averaging periodograms: split 102 400 samples (`np.random.default_rng(4)`) into 400 segments of 256, compute $\frac{|X_k|^2}{256}$ for each with `np.fft.fft`, and average. Set `level` to the mean over all bins and `scatter` to the standard deviation across bins divided by the mean.

```python starter
import numpy as np

level = scatter = 0.0
print(level, scatter)
```

```python solution
import numpy as np

rng = np.random.default_rng(4)
x = rng.normal(size=400 * 256).reshape(400, 256)
P = np.mean(np.abs(np.fft.fft(x, axis=1))**2 / 256, axis=0)
level = P.mean()
scatter = P.std() / P.mean()
print(level, scatter)
```

```python tests
assert abs(level - 1) < 0.02, f"White noise of variance 1 has a flat periodogram level of 1; got {level}."
assert scatter < 0.08, f"Averaging 400 periodograms leaves about 5% scatter; got {scatter}."
```

::: right
Right. Flat at the noise variance, with the scatter cut to about 5% by averaging 400 segments.
:::
:::

::: check
kind: python

## A pulse of 0.1 V (a half sine over 100 samples) repeats in records of unit white noise. Average 64 triggered records (`np.random.default_rng(5)`) and set `noise_left` to the RMS of the average minus the pulse.

```python starter
import numpy as np

noise_left = 1.0
print(noise_left)
```

```python solution
import numpy as np

rng = np.random.default_rng(5)
pulse = 0.1 * np.sin(np.pi * np.arange(100) / 100)
records = pulse + rng.normal(size=(64, 100))
avg = records.mean(axis=0)
noise_left = np.sqrt(np.mean((avg - pulse)**2))
print(noise_left)
```

```python tests
assert abs(noise_left - 1 / 8) < 0.02, f"Averaging 64 records leaves noise of 1/8; got {noise_left}."
```

::: right
Right. The noise falls to $\frac18$ while the pulse stays at full size.
:::
:::

::: explain
## Why does averaging triggered records improve the SNR, while averaging adjacent samples of one record would also blur the signal?

::: model
Triggered averaging lines up records so the signal is in the same place every time: averaging leaves it unchanged, while the noise, independent from record to record, is divided by $\sqrt M$ in RMS. Averaging adjacent samples within one record also reduces noise, but it treats the signal as constant over the averaging window, so any detail shorter than the window is smeared: it's a low-pass filter. The trigger is what makes the difference: it gives you many independent looks at the same moment of the signal, rather than one look at neighboring moments.
:::
:::

::: practice

::: check
given: N = 2..1000 int; s = 0.1..10
answer: s/sqrt(N)
tolerance: 0.5%

## RMS after an {N}-point moving average of white noise of RMS {s}?

::: misses
- [any] $s/\sqrt N$.
:::
:::

::: check
given: fc = 0.1..100
answer: pi/2*fc
tolerance: 0.5%

## Noise bandwidth of a one-pole filter with corner {fc} kHz?

::: misses
- [any] $\frac\pi2f_c$.
:::
:::
:::
