---
title: Spectral analysis lab
heading: DFTs, peak finding, fast convolution and resampling in Python
eyebrow: C9 · Lesson 29 · Spectral analysis lab
xp: 50
---

::: hook
Lessons 21 to 27 covered sampling, rate changes, the DFT, windows and the FFT. In this lab you'll put them to work the way an instrument or an audio program does: check a DFT against the FFT, find a tone's frequency to a fraction of a bin, filter a long signal by overlap-add, cut a sample rate without aliasing, and follow a chirp through a spectrogram.
:::

::: play
- The curve is the cost of overlap-add filtering, in real multiplications per output sample, against the FFT size $N = 2^m$, for a filter of M taps.
- Each block costs two FFTs and N products and yields N − M + 1 new samples. Too small an FFT wastes most of each block on overlap; too large a one pays $\log_2 N$ for nothing.
- The readout is direct convolution's cost, M per sample. For short filters it wins; somewhere around 30 to 60 taps the FFT takes over.
:::

```sim plot
view: graph
x: m = 6..14
y: c = 0..250
slider: M = 8..400 step 1 = 101
plot: (4*2^m*m + 4*2^m)/(2^m - M + 1)*step(2^m - M - 0.5) + 999*step(M - 2^m + 0.5) | samples: 801 | label: overlap-add, per output
plot: M | dashed | label: direct
readout: overlap-add with 1024-point FFTs = (4*1024*10 + 4*1024)/(1024 - M + 1)*step(1024 - M - 0.5) | digits: 4
readout: direct = M | digits: 4
```

::: predict
## A 101-tap filter runs by overlap-add with 1024-point FFTs. Counting real multiplications, about how many does each output sample cost?

- [ ] 101
- [x] About 49
- [ ] About 11
- [ ] About 1000

::: reveal
About 49: two 1024-point FFTs at $2N\log_2N$ real multiplications each, plus 1024 complex products, is 45,056 per block, spread over 924 new samples. Direct convolution costs 101 per sample, so the FFT is twice as fast here, and much faster for longer filters.
:::
:::

::: nameit
## The techniques

- **The DFT by definition**: $X[k] = \sum_n x[n]e^{-j2\pi kn/N}$, N² operations. Checking it against `numpy.fft.fft` is the standard test that an FFT routine is right.
- **Peak interpolation**: a tone between bins puts its peak between two DFT samples. Fitting a parabola through the log magnitudes α, β, γ at bins k − 1, k, k + 1 puts the peak at $k + \delta$ with
$$\delta = \frac{\tfrac12(\alpha - \gamma)}{\alpha - 2\beta + \gamma}$$
With a Hann window this is accurate to a few hundredths of a bin.
- **Overlap-add**: split x into blocks of L = N − M + 1, convolve each with h by FFT (padding both to N), and add the overlapping tails.
- **Decimation**: low-pass to the new Nyquist frequency, then keep every Mth sample. Without the filter, everything above the new Nyquist frequency folds down.
- **Spectrogram**: windowed DFTs of overlapping frames; the strongest bin in each frame tracks a changing tone.
:::

::: example
## A Hann-windowed 1024-point DFT at 8 kHz has log magnitudes −6.1, −1.2 and −4.0 dB at bins 127, 128 and 129. Where is the tone?

::: solution
1. **Interpolate the peak.**
   $$\begin{aligned} \delta &= \frac{\tfrac12(-6.1 - (-4.0))}{-6.1 + 2.4 - 4.0} \\ &= \tfrac12(-2.1)/(-7.7) \\ &= 0.136 \end{aligned}$$
2. **Convert to hertz.** The peak is at bin 128.136, which is
   $$\begin{aligned} f &= 128.136 \times 8000/1024 \\ &= 1001.1\ \text{Hz} \end{aligned}$$
3. **Compare.** Without interpolation the answer would be bin 128, 1000 Hz: off by about an eighth of a bin.

**Answer:** the tone is at bin 128.136, which is 1001.1 Hz.
:::
:::

::: example
## A 48 kHz signal is decimated by 4 without filtering. Where does a 9 kHz tone end up?

::: solution
1. **New rate.** The new rate is 12 kHz and its Nyquist frequency 6 kHz.
2. **Fold the tone.** 9 kHz is 3 kHz above it, so it folds to
   $$12 - 9 = 3\ \text{kHz}$$
   right in the middle of the band, where no later filter can tell it from a real 3 kHz tone.
3. **The fix.** A low-pass with its cutoff at 6 kHz (π/4 at 48 kHz) before the downsampling removes it.

**Answer:** it ends up at 3 kHz, where it can't be told from a real 3 kHz tone.
:::
:::

::: check
given: M = 31 | 101 | 255; m = 9 | 10 | 11
answer: (4*2^m*m + 4*2^m)/(2^m - M + 1)
tolerance: 0.5%

## Overlap-add with $N = 2^{\given{m}}$ for a {M}-tap filter. Real multiplications per output?

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

::: misses
- [any] Not yet. $(4N\log_2N + 4N)/(N - M + 1)$.
:::
:::

::: check
kind: python

## Write `dft(x)`: the DFT of a list by its definition, as a numpy array of complex values.

```python starter
import numpy as np

def dft(x):
    return np.array(x, dtype=complex)
```

```python solution
import numpy as np

def dft(x):
    x = np.asarray(x, dtype=complex)
    N = len(x)
    n = np.arange(N)
    return np.array([np.sum(x * np.exp(-2j * np.pi * k * n / N)) for k in range(N)])
```

```python tests
import numpy as np
rng = np.random.default_rng(3)
for N in (1, 4, 7, 64):
    x = rng.standard_normal(N) + 1j * rng.standard_normal(N)
    assert np.allclose(dft(x), np.fft.fft(x), atol=1e-9), f"For N = {N}, dft should match numpy.fft.fft."
assert np.allclose(dft([1, 1, 1, 1]), [4, 0, 0, 0], atol=1e-12), "Four ones: all the energy is at bin 0."
```

::: right
Right. N² work, but it's the definition every fast version is tested against.
:::
:::

::: check
kind: python

## Write `peak_frequency(x, fs)`: apply a Hann window, take `np.fft.rfft`, find the largest bin k (not 0 or the last), interpolate a parabola through the log magnitudes at k − 1, k, k + 1, and return the frequency in hertz.

```python starter
import numpy as np

def peak_frequency(x, fs):
    X = np.abs(np.fft.rfft(x))
    return np.argmax(X) * fs / len(x)
```

```python solution
import numpy as np

def peak_frequency(x, fs):
    x = np.asarray(x, dtype=float)
    N = len(x)
    w = 0.5 * (1 - np.cos(2 * np.pi * np.arange(N) / N))
    X = np.abs(np.fft.rfft(x * w))
    k = 1 + int(np.argmax(X[1:-1]))
    a, b, c = np.log(X[k - 1]), np.log(X[k]), np.log(X[k + 1])
    d = 0.5 * (a - c) / (a - 2 * b + c)
    return (k + d) * fs / N
```

```python tests
import numpy as np
n = np.arange(1024)
for f in (1000.0, 1010.0, 1234.5, 3017.0):
    est = peak_frequency(np.cos(2 * np.pi * f * n / 8000 + 0.3), 8000)
    assert abs(est - f) < 0.05 * 8000 / 1024, f"A {f} Hz tone should be found within 0.05 bin; got {est:.2f} Hz."
```

::: right
Right. Three samples of the spectrum pin the peak down far more finely than the bin spacing.
:::
:::

::: check
kind: python

## Write `overlap_add(x, h, nfft)`: the full linear convolution of x and h (length len(x) + len(h) − 1), computed with FFTs of size `nfft` on blocks of nfft − len(h) + 1 samples.

```python starter
import numpy as np

def overlap_add(x, h, nfft):
    return np.real(np.fft.ifft(np.fft.fft(x, nfft) * np.fft.fft(h, nfft)))
```

```python solution
import numpy as np

def overlap_add(x, h, nfft):
    x = np.asarray(x, dtype=float)
    h = np.asarray(h, dtype=float)
    L = nfft - len(h) + 1
    H = np.fft.fft(h, nfft)
    y = np.zeros(len(x) + len(h) - 1)
    for start in range(0, len(x), L):
        block = x[start:start + L]
        yb = np.real(np.fft.ifft(np.fft.fft(block, nfft) * H))
        end = min(start + nfft, len(y))
        y[start:end] += yb[:end - start]
    return y
```

```python tests
import numpy as np
rng = np.random.default_rng(5)
for nx, nh, nfft in [(1000, 31, 128), (5000, 101, 512), (37, 5, 16)]:
    x, h = rng.standard_normal(nx), rng.standard_normal(nh)
    y = overlap_add(x, h, nfft)
    assert len(y) == nx + nh - 1, f"The output should have {nx + nh - 1} samples, got {len(y)}."
    assert np.allclose(y, np.convolve(x, h), atol=1e-9), f"With {nx} samples, {nh} taps and N = {nfft}, it should equal numpy.convolve."
```

::: right
Right. Block by block, it's exactly linear convolution, at FFT speed.
:::
:::

::: check
kind: python

## Write `decimate(x, M, ntaps)`: filter x with an `ntaps`-tap Hamming-windowed sinc low-pass with cutoff π/M (ntaps odd, unity gain at DC), then keep every Mth sample, starting with the first.

```python starter
import numpy as np

def decimate(x, M, ntaps):
    return np.asarray(x, dtype=float)[::M]
```

```python solution
import numpy as np

def decimate(x, M, ntaps):
    c = (ntaps - 1) // 2
    n = np.arange(ntaps) - c
    h = np.sinc(n / M) / M
    h *= 0.54 + 0.46 * np.cos(np.pi * n / c)
    h /= np.sum(h)
    y = np.convolve(np.asarray(x, dtype=float), h)[:len(x)]
    return y[::M]
```

```python tests
import numpy as np
fs, M = 48000, 4
t = np.arange(48000) / fs
def amp(y, f):
    y = y[204:12000]
    n = np.arange(len(y))
    return 2 * abs(np.sum(y * np.exp(-2j * np.pi * f * n / 12000))) / len(y)
keep = amp(decimate(np.cos(2 * np.pi * 1000 * t), M, 101), 1000)
gone = amp(decimate(np.cos(2 * np.pi * 9000 * t), M, 101), 3000)
assert abs(keep - 1) < 0.01, f"A 1 kHz tone should pass with gain 1, got {keep:.4f}."
assert gone < 0.01, f"A 9 kHz tone must not fold to 3 kHz: it should be 40 dB down, got {gone:.4f}."
assert len(decimate(np.ones(100), 4, 21)) == 25, "Every fourth sample of 100 is 25 samples."
```

::: right
Right. Filter first, then throw samples away: the order is what prevents aliasing.
:::
:::

::: check
kind: python

## Write `track(x, fs, n, hop)`: a spectrogram's peak frequencies. For frames of n samples starting every `hop` samples (while a whole frame fits), apply a Hann window, take `rfft`, and return the list of frequencies (bin × fs/n) of each frame's largest bin.

```python starter
def track(x, fs, n, hop):
    return []
```

```python solution
import numpy as np

def track(x, fs, n, hop):
    x = np.asarray(x, dtype=float)
    w = 0.5 * (1 - np.cos(2 * np.pi * np.arange(n) / n))
    out = []
    for s in range(0, len(x) - n + 1, hop):
        X = np.abs(np.fft.rfft(x[s:s + n] * w))
        out.append(int(np.argmax(X)) * fs / n)
    return out
```

```python tests
import numpy as np
fs = 8000
t = np.arange(fs) / fs
chirp = np.cos(2 * np.pi * (500 * t + 1250 * t ** 2))
f = track(chirp, fs, 256, 128)
assert len(f) == (8000 - 256) // 128 + 1, f"Expected {(8000 - 256) // 128 + 1} frames, got {len(f)}."
assert all(b >= a for a, b in zip(f, f[1:])), "A rising chirp's peak should never fall."
assert abs(f[0] - 540) < 32 and abs(f[-1] - 2960) < 32, f"It sweeps from about 500 to 3000 Hz; the first and last frames read {f[0]} and {f[-1]}."
```

::: right
Right. That's a spectrogram reduced to its ridge, the way a tuner or a bird-song analyzer follows a pitch.
:::
:::

::: explain
## Why must a signal be low-pass filtered before its sample rate is reduced, and not after?

::: model
Keeping every Mth sample is itself a sampling operation at the new, lower rate, so any content above the new Nyquist frequency folds down into the band below it. Once that has happened, the folded energy sits at the same frequencies as genuine signal, and no filter can separate the two. Filtering first, while the signal is still at the high rate, removes everything above the new Nyquist frequency while it's still distinguishable, so that the downsampling has nothing left to fold. The same reasoning is why an analog anti-aliasing filter comes before an ADC.
:::
:::
