03. The DFT, windows and leakage
The discrete Fourier transform (DFT) converts a block of samples into amplitudes and phases at evenly spaced frequencies. Most of the later notebooks (spectrograms, mel features, pitch, filtering by FFT) depend on it. This notebook covers exactly what it returns, why a pure tone often spreads over many bins (leakage), and what a window can and cannot do about that.
Learning outcomes. After working through this notebook you can
state the DFT convention used by
audio_samples(and NumPy), and read amplitudes off its output;compute bin frequencies and explain spectral leakage;
compare windows by coherent gain, ENBW, scalloping loss and side-lobe level;
explain why zero padding does not improve frequency resolution, and choose \(N\) to resolve two tones.
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as ss
import audio_samples as aus
rng = np.random.default_rng(seed=2026)
F64 = np.dtype("float64")
WT = aus.WindowType
Concept
Definition. For a block of \(N\) samples \(x[n]\), \(n = 0, \dots, N-1\):
where \(k\) is the integer bin index, \(j = \sqrt{-1}\) and \(X[k]\) is a complex number in the units
of \(x\) (here: full scale) times samples. The exponent is negative and there is no \(1/N\)
factor (the same as numpy.fft.fft).
Bin frequencies. Bin \(k\) sits at
where \(f_s\) is the sample rate in Hz and \(\Delta f\) the bin spacing in Hz. For real \(x\), \(X[N-k] = \overline{X[k]}\), so only bins \(0 \dots \lfloor N/2\rfloor\) carry information; the library returns exactly those \(\lfloor N/2\rfloor + 1\).
A tone on a bin. For \(x[n] = A\cos(2\pi k_0 n/N)\), \(X[k_0] = A N/2\) (real); for \(A\sin(\cdot)\), \(X[k_0] = -jAN/2\). With a window \(w[n]\) applied first, the peak becomes \(A \sum_n w[n] / 2\).
Leakage. The DFT treats the block as one period of a periodic signal. If the tone does not complete a whole number of cycles in the block, the implied periodic signal has a jump at the block edge, and the energy spreads over all bins. Multiplying by a window that tapers to zero removes the jump, at the cost of a wider main lobe. A window \(w[n]\) is summarised by:
where the coherent gain CG (dimensionless) scales the peak of a bin-centred tone relative to no window, and the equivalent noise bandwidth ENBW (in bins) is how much broadband noise each bin collects. Two more figures are read off the window’s spectrum \(W(f)\) (with \(f\) in bins): the scalloping loss \(-20\log_{10}|W(1/2)/W(0)|\) in dB, the worst-case peak drop for a tone halfway between bins, and the peak side-lobe level (PSL), the highest lobe outside the main lobe in dB relative to \(W(0)\).
The library’s WindowType.hanning is the symmetric Hann window
(denominator \(N-1\), so \(w[0] = w[N-1] = 0\)), i.e. SciPy’s scipy.signal.windows.hann(N, sym=True),
not the periodic one (denominator \(N\)) that scipy.signal.get_window('hann', N) gives.
Zero padding (appending zeros before the DFT) samples the same spectrum on a finer grid. It does not narrow the main lobe; only a longer stretch of signal does.
With the library
AudioSamples.fft(n_fft) returns the complex non-negative-frequency bins and
AudioSamples.rfft(n_fft) their magnitudes (NumPy’s rfft returns complex values). Both are
shaped (channels, n_fft // 2 + 1).
# 64 samples: 0.25 (DC) + sin at bin 4 + 0.5 cos at bin 9.
t = np.arange(64) / 64
x = 0.25 + np.sin(2 * np.pi * 4 * t) + 0.5 * np.cos(2 * np.pi * 9 * t)
audio = aus.AudioSamples.new_mono(x, sample_rate=16_000)
spec = audio.fft(64)
assert spec.shape == (1, 33) # N/2 + 1 bins
assert abs(spec[0, 0] - 16.0) < 1e-9 # N x 0.25
assert abs(spec[0, 4] - (-32.0j)) < 1e-9 # -j A N / 2: negative exponent
assert abs(spec[0, 9] - 16.0) < 1e-9 # 0.5 N / 2
mags = audio.rfft(64)
assert mags.dtype == np.float64 # real numbers ...
assert abs(mags[0, 4] - 32.0) < 1e-9 # ... equal to |X[4]|
Measuring leakage: at \(f_s = 16\) kHz and \(N = 512\), \(\Delta f = 31.25\) Hz, so 1000 Hz is bin 32
and 1015.625 Hz is bin 32.5, the worst case. Window the tone with AudioSamples.apply_window and
coefficients from WindowType.make_hanning (the rectangular window is np.ones):
def windowed_spectrum(f, window):
tone = aus.sine_wave(f, 0.032, sample_rate=16_000, dtype=F64) # 512 samples
return tone.apply_window(window).rfft(512)[0]
db = lambda r: 20 * np.log10(r)
assert 16_000 / 512 == 31.25 and 1000 / 31.25 == 32 and 1015.625 / 31.25 == 32.5
rect, hann = np.ones(512), WT.make_hanning(512)
on, off = windowed_spectrum(1000.0, rect), windowed_spectrum(1015.625, rect)
drop_rect, leak_rect = db(on.max() / off.max()), db(off[52] / off.max())
on_h, off_h = windowed_spectrum(1000.0, hann), windowed_spectrum(1015.625, hann)
drop_hann, leak_hann = db(on_h.max() / off_h.max()), db(off_h[52] / off_h.max())
print(f"rectangular: off-bin peak drop {drop_rect:.2f} dB, 19.5 bins away {leak_rect:.1f} dB")
print(f"Hann: off-bin peak drop {drop_hann:.2f} dB, 19.5 bins away {leak_hann:.1f} dB")
# Rectangular: peak drops 3.86 dB off-bin, and 19.5 bins away the leakage is still only 34 dB down.
assert abs(drop_rect - 3.86) < 0.01 and abs(leak_rect + 34.0) < 0.1
# Hann: the peak drops only 1.42 dB, and 19.5 bins away the leakage is 86 dB down.
assert abs(drop_hann - 1.42) < 0.01 and abs(leak_hann + 86.0) < 0.1
rectangular: off-bin peak drop 3.86 dB, 19.5 bins away -34.0 dB
Hann: off-bin peak drop 1.42 dB, 19.5 bins away -86.0 dB
f_axis = np.arange(257) * 31.25
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(f_axis, db(off / off.max()), label="rectangular, 1015.625 Hz")
ax.plot(f_axis, db(off_h / off_h.max()), label="Hann, 1015.625 Hz")
ax.set(xlabel="Frequency (Hz)", ylabel="Level re peak (dB)", xlim=(0, 4000), ylim=(-120, 5),
title="A tone halfway between bins (N = 512, fs = 16 kHz)")
ax.legend()
plt.show()
(The rectangular drop of 3.86 dB is slightly less than the window’s 3.92 dB scalloping loss because a real sine also has a negative-frequency image whose leakage adds to the bins near the peak.)
Zero padding versus a longer signal: two tones 20 Hz apart, Hann window.
def peaks_near(m, n_fft, lo_hz, hi_hz):
# Count local maxima above half the largest one between lo_hz and hi_hz.
bin_hz = 16_000 / n_fft
lo, hi = int(lo_hz / bin_hz), int(hi_hz / bin_hz)
top = m[lo:hi].max()
return sum(1 for i in range(lo, hi) if m[i] > m[i - 1] and m[i] >= m[i + 1] and m[i] > 0.5 * top)
def two_tones_hann(n_samples, n_fft, f1=1000.0, f2=1020.0):
t = np.arange(n_samples) / 16_000
v = np.sin(2 * np.pi * f1 * t) + np.sin(2 * np.pi * f2 * t)
a = aus.AudioSamples.new_mono(v, sample_rate=16_000).apply_window(WT.make_hanning(n_samples))
return a.rfft(n_fft)[0]
assert peaks_near(two_tones_hann(512, 512), 512, 900, 1120) == 1 # 32 ms
assert peaks_near(two_tones_hann(512, 8192), 8192, 900, 1120) == 1 # zero-padded: still 1
assert peaks_near(two_tones_hann(4096, 8192), 8192, 900, 1120) == 2 # 256 ms: resolved
fig, ax = plt.subplots(figsize=(8, 3))
for n_samples, n_fft, lab in [(512, 512, "512 samples"), (512, 8192, "512 samples, zero-padded to 8192"),
(4096, 8192, "4096 samples, padded to 8192")]:
m = two_tones_hann(n_samples, n_fft)
fa = np.arange(m.size) * 16_000 / n_fft
ax.plot(fa, db(m / m.max()), marker="." if n_fft == 512 else None, label=lab)
ax.set(xlabel="Frequency (Hz)", ylabel="Level re peak (dB)", xlim=(850, 1170), ylim=(-40, 3),
title="1000 Hz + 1020 Hz, Hann window")
ax.legend(fontsize=7)
plt.show()
How it works
This section re-derives four results: the DFT itself, the window coefficients, the symmetric-Hann figures in closed form, and the rectangular window’s scalloping loss and Hann’s side-lobe level.
# 1. The DFT as a matrix product, against the library's FFT and NumPy's.
x = (np.arange(64) * 7 % 13 - 6.0) / 6.0
n = np.arange(64)
k = np.arange(33)[:, None]
naive = (x * np.exp(-2j * np.pi * k * n / 64)).sum(axis=1)
lib = aus.AudioSamples.new_mono(x, sample_rate=16_000).fft(64)[0]
# 64-term sums of O(1) values: rounding of order 1e-14.
assert np.allclose(lib, naive, atol=1e-12)
assert np.allclose(lib, np.fft.rfft(x), atol=1e-12)
assert np.allclose(np.abs(lib), aus.AudioSamples.new_mono(x, sample_rate=16_000).rfft(64)[0], atol=1e-12)
# 2. The library's windows are SciPy's *symmetric* windows (fftbins=False), to rounding.
for name, scipy_name in [("hanning", "hann"), ("hamming", "hamming"), ("blackman", "blackman")]:
w = getattr(WT, "make_" + name)(512)
assert np.allclose(w, ss.get_window(scipy_name, 512, fftbins=False), rtol=0, atol=1e-14)
# ... and differ from the periodic default by up to half a percent of full scale.
periodic_gap = np.max(np.abs(WT.make_hanning(512) - ss.get_window("hann", 512)))
print(f"max |symmetric - periodic| Hann, N=512: {periodic_gap:.4f}")
assert 0.004 < periodic_gap < 0.005
# 3. Symmetric Hann: sum w = (N-1)/2 and sum w^2 = 3(N-1)/8, so CG = (N-1)/(2N) and
# ENBW = 1.5 N/(N-1). For N = 512: 0.4990 and 1.5029.
N = 512
w = WT.make_hanning(N)
cg = w.sum() / N
enbw = N * np.sum(w ** 2) / w.sum() ** 2
assert abs(cg - (N - 1) / (2 * N)) < 1e-12 and abs(enbw - 1.5 * N / (N - 1)) < 1e-12
assert abs(cg - 0.4990) < 1e-4 and abs(enbw - 1.5029) < 1e-4
assert w[0] == 0.0 and abs(w[-1]) < 1e-15 # symmetric: zero at both ends,
assert abs(w[256] - 0.999991) < 1e-6 # and no sample exactly at 1.0
max |symmetric - periodic| Hann, N=512: 0.0047
# 4a. Rectangular window: |W(f)| = |sin(pi f) / sin(pi f / N)|, so half a bin off,
# |W(1/2)/W(0)| = 1 / (N sin(pi / 2N)), i.e. 3.92 dB.
loss_rect = -20 * np.log10(1 / (N * np.sin(np.pi / (2 * N))))
assert abs(loss_rect - 3.92) < 0.01
# 4b. Hann's peak side-lobe level from a heavily zero-padded spectrum of the window itself:
# the first local minimum marks the end of the main lobe; the PSL is the largest value after it.
Wf = np.abs(np.fft.rfft(w, 64 * N))
Wdb = 20 * np.log10(Wf / Wf[0] + 1e-300)
first_null = np.argmax(np.diff(Wdb) > 0) # first index where the curve turns upwards
psl_hann = Wdb[first_null:].max()
print(f"Hann PSL from the spectrum: {psl_hann:.2f} dB; first null at {first_null / 64:.2f} bins")
assert abs(psl_hann - (-31.47)) < 0.01
assert abs(first_null / 64 - 2.0) < 0.02 # main lobe +-2 bins wide
Hann PSL from the spectrum: -31.47 dB; first null at 2.00 bins
The same comparison holds for the Kaiser window across small and large \(\beta\).
for beta in [2.0, 3.75, 4.0, 8.0]:
gap = np.max(np.abs(WT.make_kaiser(64, beta) - ss.windows.kaiser(64, beta, sym=True)))
print(f"beta = {beta:4.2f}: max |library - scipy| = {gap:.2e}")
assert gap < 1e-6
beta = 2.00: max |library - scipy| = 1.73e-08
beta = 3.75: max |library - scipy| = 2.25e-08
beta = 4.00: max |library - scipy| = 2.11e-08
beta = 8.00: max |library - scipy| = 1.07e-08
Ask the library to explain
aus.explain.dft explains bin spacing and the mirror symmetry; aus.explain.window (or
aus.explain.explain(window_type, n_fft=..., sample_rate=...)) measures the window figures from
the actual coefficients the STFT uses:
dft_doc = aus.explain.dft(512, 16_000.0)
assert dft_doc.quantity("Bin spacing") == 31.25
assert dft_doc.quantity("Non-redundant bins") == 257
hann_doc = aus.explain.window(WT.hanning, 512, 16_000.0)
assert abs(hann_doc.quantity("Coherent gain") - cg) < 1e-12
assert abs(hann_doc.quantity("Equivalent noise bandwidth") - enbw) < 1e-12
assert abs(hann_doc.quantity("Peak side-lobe level") - psl_hann) < 0.01
assert abs(hann_doc.quantity("Scalloping loss") - 1.42) < 0.01
rect_doc = aus.explain.window(WT.rectangular, 512, 16_000.0)
assert abs(rect_doc.quantity("Scalloping loss") - loss_rect) < 0.01
# (window, coherent gain, ENBW in bins, peak side-lobe level in dB), N = 512
rows = []
for wt, cg_, enbw_, psl_ in [
(WT.rectangular, 1.0, 1.0, -13.26),
(WT.hanning, 0.4990, 1.5029, -31.47),
(WT.hamming, 0.5391, 1.3647, -42.67),
(WT.blackman, 0.4192, 1.7301, -58.11),
]:
d = aus.explain.explain(wt, n_fft=512, sample_rate=16_000.0)
got = (d.quantity("Coherent gain"), d.quantity("Equivalent noise bandwidth"), d.quantity("Peak side-lobe level"))
rows.append((str(wt), *got))
assert abs(got[0] - cg_) < 1e-4 and abs(got[1] - enbw_) < 1e-4 and abs(got[2] - psl_) < 0.01
for r in rows:
print("{:12s} CG {:.4f} ENBW {:.4f} bins PSL {:7.2f} dB".format(*r))
Rectangular CG 1.0000 ENBW 1.0000 bins PSL -13.26 dB
Hanning CG 0.4990 ENBW 1.5029 bins PSL -31.47 dB
Hamming CG 0.5391 ENBW 1.3647 bins PSL -42.67 dB
Blackman CG 0.4192 ENBW 1.7301 bins PSL -58.11 dB
doc = aus.explain.explain(WT.hanning, n_fft=512, sample_rate=16_000.0)
assert doc.has_warning_containing("symmetric")
doc
Hann window
A 512-point Hann window. Its main lobe is 2.00384 bins wide at -6 dB and its highest side lobe is at -31.4676 dB; each bin collects noise from 1.50294 bins’ worth of bandwidth.
Formulas
Window coefficients as generated (n = 0, …, N-1):
$$ w[n] = 0.5 - 0.5 \cos\left(\frac{2 \pi n}{N-1}\right) $$
Coherent gain: amplitude of a bin-centred tone relative to a rectangular window:
$$ \mathrm{CG} = \frac{1}{N}\sum_{n=0}^{N-1} w[n] $$
Equivalent noise bandwidth in bins: how much broadband noise each bin collects:
$$ \mathrm{ENBW} = \frac{N \sum_{n} w^2[n]}{\left(\sum_{n} w[n]\right)^2} $$
Window spectrum (f in bins), measured on a zero-padded FFT:
$$ W(f) = \sum_{n=0}^{N-1} w[n] , e^{-j \frac{2\pi}{N} f n} $$
Symbols
| Symbol | Meaning | Value | |—|—|—| | $N$ | window length | 512 samples | | $w[n]$ | window coefficient | |
Derived quantities
| Quantity | Value | Formula | |—|—|—| | Coherent gain | $CG$ = 0.499023 | $\frac{1}{N}\sum_n w[n]$ | | Coherent gain (dB) | $20\log_{10} CG$ = -6.03758 dB | $20 \log_{10} CG$ | | Equivalent noise bandwidth | $ENBW$ = 1.50294 bins | $N \sum_n w^2[n] / (\sum_n w[n])^2$ | | Scalloping loss | $L_s$ = 1.41797 dB | $-20\log_{10} \vert W(\tfrac{1}{2},\mathrm{bin})\vert / \vert W(0)\vert $ | | Peak side-lobe level | $PSL$ = -31.4676 dB | $\max_{f > f_{null}} 20\log_{10}\vert W(f)/W(0)\vert $ | | Main-lobe width (-3 dB) | $B_{3}$ = 1.44327 bins | $\vert W(B_3/2)\vert ^2 = \tfrac{1}{2}\vert W(0)\vert ^2$ | | Main-lobe width (-6 dB) | $B_{6}$ = 2.00384 bins | $\vert W(B_6/2)\vert = \tfrac{1}{2}\vert W(0)\vert $ | | First null | $f_{null}$ = 2 bins | $\text{first minimum of } \vert W(f)\vert $ | | Window duration | $N / f_s$ = 32 ms | $1000 N / f_s$ | | ENBW (Hz) | $\mathrm{ENBW} \cdot f_s/N$ = 46.9667 Hz | $\mathrm{ENBW} \cdot f_s / N$ | | Main-lobe width (-6 dB, Hz) | $B_{6} f_s/N$ = 62.6199 Hz | $B_6 \cdot f_s / N$ |
Trade-offs
A wider main lobe (poorer frequency resolution) gives lower side lobes (less leakage from strong components into weak ones).
Higher ENBW means more noise per bin; low coherent gain means smaller peak values, which amplitude-calibrated plots must correct for.
Warnings
Info: The generated window is symmetric (w[n] = w[N-1-n], denominator N-1), not periodic (DFT-even, denominator N). Hint: Symmetric windows suit filter design; periodic ones tile exactly under overlap-add. The STFT explanation reports the measured overlap-add ripple.
See also
Coefficients:
spectrograms::make_windowApply to a signal:
audio_samples::AudioProcessing::apply_windowApply to a signal (Python):
audio_samples.AudioSamples.apply_windowPython:
audio_samples.explain.window
The table shows the standard trade-off: lower side lobes (less leakage from loud components into quiet ones) cost a wider main lobe and more noise per bin.
Exercises
At \(f_s = 44.1\) kHz with \(N = 4096\), which bin is nearest to 440 Hz? Store the bin index in
answer, compute its centre frequency, and check that a Hann-windowed 440 Hz tone peaks there.
answer = None # TODO
# Solution
answer = round(440 * 4096 / 44_100) # round(40.87) = 41
assert answer == 41
assert abs(answer * 44_100 / 4096 - 441.43) < 0.01
tone = np.sin(2 * np.pi * 440 * np.arange(4096) / 44_100)
m = aus.AudioSamples.new_mono(tone, sample_rate=44_100).apply_window(WT.make_hanning(4096)).rfft(4096)[0]
assert np.argmax(m) == answer
A sine of amplitude 0.5 lies exactly on a bin, Hann window, \(N = 1024\). Predict \(|X[k]|\) at the peak, then measure.
answer = None # TODO
# Solution
answer = 0.5 * WT.make_hanning(1024).sum() / 2 # A * sum(w) / 2 = 0.5 * 511.5 / 2
assert abs(answer - 127.875) < 1e-9 # sum of a symmetric Hann is (N-1)/2
x = aus.sine_wave(1000.0, 0.064, sample_rate=16_000, amplitude=0.5, dtype=F64) # 1024 samples, bin 64
m = x.apply_window(WT.make_hanning(1024)).rfft(1024)[0]
# The tone's negative-frequency image leaks a little into bin 64: allow 1e-3.
assert abs(m[64] - answer) < 1e-3
With a Hann window (main lobe about 2 bins wide at \(-6\) dB), what is the smallest \(N\) that should separate two tones 10 Hz apart at 16 kHz? Check that the next power of two separates 1000 Hz and 1010 Hz, and that \(N = 1024\) does not.
answer = None # TODO
# Solution
answer = 2 * 16_000 / 10 # main lobe 2 fs / N <= 10 Hz => N >= 3200
assert answer == 3200
assert abs(aus.explain.window(WT.hanning, 4096, 16_000.0).quantity("Main-lobe width (-6 dB)") - 2.0) < 0.01
assert peaks_near(two_tones_hann(4096, 4096, 1000.0, 1010.0), 4096, 950, 1060) == 2
assert peaks_near(two_tones_hann(1024, 1024, 1000.0, 1010.0), 1024, 950, 1060) == 1
Common pitfalls
AudioSamples.rfftreturns magnitudes, not NumPy’s complexrfft; useAudioSamples.fftfor phase.Neither transform normalises: a full-scale bin-centred sine gives \(N/2\), not 1 or 0.5. Divide by \(\sum w / 2\) to read amplitudes.
n_fftmust be at least the signal length (shorter signals are zero-padded; longer ones raiseAudioSpectrogramError, they are not truncated).WindowType.hanningis the symmetric Hann;scipy.signal.get_window('hann', N)gives the periodic one. Values differ by up to about 0.005; build the window yourself (scipy.signal.get_window) and useWindowType.customto match them exactly.Zero padding makes plots smoother; it does not improve resolution.
See also
Rust guide chapter: 03. The DFT, windows and leakage (available from the next release; until then build the docs locally with
cargo doc --features educational,full_no_plotting --open) and the labexamples/tutorial_03_dft_windows.rs.Python API:
AudioSamples.fft,AudioSamples.rfft,AudioSamples.apply_window,WindowType,audio_samples.utils.fft_frequencies,aus.explain.dft,aus.explain.window(API reference).Previous: 02. Quantisation and dither. Next: 04. STFT and spectrograms.
References
Harris, F. J. (1978). On the use of windows for harmonic analysis with the discrete Fourier transform. Proceedings of the IEEE, 66(1), 51-83. The window figures of merit (coherent gain, ENBW, scalloping loss, highest side lobe) reproduced in this notebook.
Oppenheim, A. V. and Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson. Chapters 8 and 10 (the DFT; Fourier analysis with windows).