Fourier Analysis and Spectral Estimation¶
When you listen to a symphony orchestra, your ear does not read one messy pressure waveform sample by sample, it effortlessly separates soaring violins from deep cellos by their musical pitch. This section explains why complex exponentials are the natural eigenfunctions of every LTI system, develops the Discrete Fourier Transform and the revolutionary Fast Fourier Transform algorithm, and shows how window functions and Welch averaging recover clean spectra from real finite noisy data.
Why Complex Exponentials Are Eigenfunctions of LTI Systems¶
-
In Chapter 02, we discovered a gem of linear algebra called eigenvectors. Most vectors twist and point in completely new directions when multiplied by a matrix \(\mathbf{A}\), yet a few privileged eigenvectors simply stretch or shrink along their original line (\(\mathbf{A}\mathbf{v} = \lambda \mathbf{v}\)). Rewriting a hard linear problem in its eigenbasis turns coupled tangles into effortless scalar multiplications.
-
Signal processing enjoys an even more remarkable miracle! Every single LTI system \(\mathcal{H}\), whether it is a concert hall, a low-pass circuit, or a seismic medium, shares the exact same universal family of eigenfunctions, namely the complex exponentials \(x[n] = e^{j\omega n}\). Pass a pure spinning phasor \(e^{j\omega n}\) through any LTI system with impulse response \(h[n]\) and watch the convolution sum simplify in two lines.
-
Look closely at what just happened! The rotating phasor \(e^{j\omega n}\) emerged from the system at the exact same frequency \(\omega\), merely multiplied by a single complex eigenvalue \(H(e^{j\omega})\) called the frequency response of the system. Its magnitude \(|H(e^{j\omega})|\) tells you how much the system boosts or attenuates frequency \(\omega\) (its gain), while its angle \(\angle H(e^{j\omega})\) tells you how far it shifts that tone in phase.
-
This single observation explains why Fourier analysis sits at the heart of physics and AI. Break any complicated signal into a weighted recipe of complex exponentials, multiply each frequency component independently by its scalar gain \(H(e^{j\omega})\), and add the pieces back together!
From Fourier Series to the Discrete Fourier Transform¶
-
Think of shining white sunlight through a glass prism. What looked like one uniform beam fans out into a luminous rainbow of pure colours, each travelling at its own wavelength. In 1807, Joseph Fourier proposed the acoustic and mathematical twin of that prism, showing that almost any periodic waveform of period \(T\) can be built by summing harmonically related complex exponentials at integer multiples of the fundamental frequency \(\omega_0 = 2\pi / T\), a representation called the Fourier Series.
-
Letting the period \(T\) stretch toward infinity smoothly merges those discrete harmonic lines into a continuous spectrum, producing the Continuous-Time Fourier Transform (CTFT) for aperiodic signals.
- Digital computers, however, hold finite buffers of \(N\) discrete samples \(x[0], x[1], \dots, x[N-1]\). Projecting that length-\(N\) vector onto \(N\) equally spaced harmonic phasors around the unit circle defines the Discrete Fourier Transform (DFT) and its exact inverse.
- Each output bin \(X[k]\) measures the inner product between your signal \(x[n]\) and a spinning probe wave completing exactly \(k\) full revolutions across the \(N\) samples (corresponding to physical frequency \(f_k = k f_s / N\)). Writing the entire DFT in matrix form \(\mathbf{X} = \mathbf{F}\mathbf{x}\) reveals a gorgeous connection back to Chapter 02. Up to the scaling factor \(1/\sqrt{N}\), the DFT matrix \(\mathbf{F}\) is unitary (\(\mathbf{F}^\dagger \mathbf{F} = N \mathbf{I}\)), meaning its rows are mutually orthogonal complex basis vectors! Taking a DFT is literally rotating your signal into an orthogonal frequency coordinate system without losing a drop of information.
The Cooley-Tukey Fast Fourier Transform (FFT)¶
-
Computing the DFT directly from its summation formula requires \(N\) complex multiply-add operations for each of the \(N\) frequency bins, totalling \(O(N^2)\) work. For a modest one-second audio clip at \(N = 65{,}536\) samples, direct evaluation demands more than four billion complex multiplications, turning real-time audio or medical imaging into an agonising crawl.
-
In 1965, James Cooley and John Tukey popularised an astonishing divide-and-conquer algorithm (earlier glimpsed by Carl Friedrich Gauss in 1805 while tracking asteroids!) called the Fast Fourier Transform (FFT). Notice that the FFT is not an approximation. It computes the exact same numbers as the DFT while slashing complexity from \(O(N^2)\) down to \(O(N \log_2 N)\).
-
The trick is wonderfully simple when \(N\) is a power of two. Split the input sequence \(x[n]\) into two half-length sub-sequences, its even-indexed samples \(x[2m]\) and its odd-indexed samples \(x[2m + 1]\). Writing the twiddle factor \(W_N = e^{-j 2\pi / N}\), the full \(N\)-point DFT breaks cleanly into two \((N/2)\)-point DFTs, \(E[k]\) for the evens and \(O[k]\) for the odds.
-
Look at the symmetry in that pair of equations! Because \(W_N^{k + N/2} = -W_N^k\), once you compute the single product \(W_N^k\,O[k]\), adding it to \(E[k]\) gives bin \(k\) while subtracting it from \(E[k]\) immediately gives bin \(k + N/2\) for free! When drawn as a signal flowgraph, those criss-crossing paths look like the outstretched wings of a butterfly, earning the iconic name butterfly operation.
-
Applying that split recursively across \(\log_2 N\) stages reduces work from \(N^2\) to roughly \(\frac{1}{2} N \log_2 N\) complex multiplications. At \(N = 1{,}024\), the FFT runs over a hundred times faster than the naive DFT; at \(N = 65{,}536\), it runs more than four thousand times faster, making live spectrograms, Wi-Fi OFDM modems, MRI scanners, and fast polynomial multiplication possible on tiny low-power chips.
The Convolution Theorem and Parseval's Energy Law¶
- Once you hold the FFT in your pocket, two crown-jewel theorems unlock astonishing computational and physical shortcuts. The first is the Convolution Theorem, stating that cyclic convolution in the time domain becomes plain element-wise multiplication in the frequency domain!
-
Want to convolve a ten-second audio track (\(N \approx 440{,}000\) samples) with a lush three-second cathedral impulse response (\(L \approx 132{,}000\) samples)? Direct time-domain convolution requires roughly \(58\) billion multiplications, stalling any laptop CPU. Instead, zero-pad both signals to length \(M \ge N + L - 1\) (preventing circular wrap-around), run two \(O(M \log M)\) FFTs, multiply the two spectra pointwise, and run one inverse FFT. The total work drops from \(58\) billion ops to a few million, finishing in milliseconds!
-
The second jewel is Parseval's theorem, which expresses conservation of energy across the unitary basis rotation. Total signal energy summed in time equals total spectral energy summed across all frequency bins (scaled by \(1/N\) under standard DFT normalisation).
- Nothing is created or destroyed when you pass light through a prism, and nothing is created or destroyed when you rotate a signal into frequency space. Parseval's law also serves as a rock-solid sanity check whenever you write spectral code, because any bug in normalisation or window scaling shows up immediately as an energy mismatch.
Finite Windows and Spectral Leakage¶
-
Here is a subtle trap that surprises nearly everyone the first time they run an FFT on real sensor data. The DFT quietly assumes that your finite \(N\)-sample snippet repeats forever end to end like a seamless audio loop. If a pure sine wave happens to fit an exact integer number of cycles inside your \(N\) samples, the end connects smoothly to the start and all its energy lands cleanly inside one sharp DFT bin.
-
In real life, a signal's frequency almost never lands on an exact integer bin. Cutting a finite chunk out of a longer stream is mathematically identical to multiplying the true infinite signal by a sharp rectangular window \(w_{\text{rect}}[n]\) that equals \(1\) inside \([0, N-1]\) and drops like a vertical cliff to \(0\) outside. When the DFT loops that truncated snippet, the mismatched ends create a violent jump discontinuity!
-
By the Convolution Theorem, multiplying in time by \(w[n]\) convolves the true frequency spectrum with the window's Fourier transform \(W(f)\). Because a rectangular cliff has a bright, slowly decaying sinc-like spectrum with tall \(-13\,\text{dB}\) sidelobes, energy from a single loud tone spills outward across every single frequency bin in the entire plot. This artefact is called spectral leakage, and a tall sidelobe from one strong tone can completely bury a quieter neighbouring signal \(40\,\text{dB}\) below it.
-
How do we cure those violent cliff edges? Multiply the data frame by a smooth window function \(w[n]\) that gently tapers the signal down to zero at both ends before taking the FFT! Three classic windows span the fundamental trade-off between frequency resolution (main-lobe width) and dynamic range (sidelobe suppression).
- You never get something for nothing in Fourier analysis. The Rectangular window keeps the narrowest main lobe (\(2\) bins wide, sharpest resolution for separating two equal-strength close tones) at the cost of ugly \(-13\,\text{dB}\) sidelobes. The Hann window doubles main-lobe width to \(4\) bins while pushing the highest sidelobe down to \(-31\,\text{dB}\) with steep roll-off, making it the beloved everyday default for audio spectrograms (Chapter 10). The Hamming window cancels its nearest sidelobe down to \(-43\,\text{dB}\) (with slower distant decay), while the Blackman window widens the main lobe to \(6\) bins in exchange for whisper-quiet \(-58\,\text{dB}\) sidelobes that uncover faint hidden signals right beside booming interferers.
Periodograms and Welch Spectral Estimation¶
- Suppose now you want to measure the Power Spectral Density (PSD) of a genuinely noisy real-world signal, such as an EEG alpha brainwave around \(10\,\text{Hz}\) (Chapter 12), ocean wave swell, or vibration from a jet turbine bearing. The simplest estimator is the periodogram, taking one windowed DFT and squaring its magnitude.
-
Unfortunately, the raw periodogram hides a nasty statistical surprise! Even if you collect ten times more samples (\(N \to 10N\)), the raw periodogram does not grow smoother around a noisy spectrum! Making \(N\) longer merely packs ten times more jagged, spiky frequency bins onto the plot, while the variance of each individual bin refuses to shrink (it stays roughly equal to the squared true PSD, meaning \(100\%\) relative standard error at every frequency).
-
In 1967, Peter Welch introduced an elegant cure called Welch's method that remains the workhorse of scientific spectral estimation today. Instead of computing one gigantic noisy DFT over the entire recording, chop the signal into \(K\) shorter overlapping segments (typically \(50\%\) overlap so samples tapered down at the edge of one Hann window sit right in the tall middle of the next), compute a windowed periodogram on each segment, and average all \(K\) power spectra together.
- Averaging \(K\) overlapping segments slices the estimator's variance down by roughly a factor of \(K\), melting wild grass-like noise spikes into a clean, trustworthy curve where subtle spectral bumps shine through unmistakably. The price is a classic bias-variance trade-off. Shorter segments lower variance by giving you more chunks to average, yet coarsen your frequency bin spacing \(\Delta f = f_s / L_{\text{seg}}\). Balancing segment length, window shape, and overlap gives engineers surgical control over real-world spectral measurement, and lays the exact foundation for the Short-Time Fourier Transform (STFT) spectrograms we will build next in Section 4 (and apply directly to audio in Chapter 10).
Take-Home¶
- Complex exponentials \(e^{j\omega n}\) are universal eigenfunctions of all LTI systems, emerging at the exact same frequency scaled by the complex frequency response \(H(e^{j\omega})\).
- The DFT is a unitary orthogonal change of basis projecting \(N\) time samples onto \(N\) harmonic phasors, conserving total energy under Parseval's theorem.
- The Cooley-Tukey FFT exploits even-odd butterfly symmetries to slash DFT complexity from \(O(N^2)\) to \(O(N \log N)\), unlocking fast convolution via the Convolution Theorem.
- Abrupt finite truncation causes spectral leakage, which smooth windows like Hann, Hamming, and Blackman tame by trading a slightly wider main lobe for deep sidelobe suppression.
- Welch's method tames the high variance of raw periodograms by averaging windowed spectra across overlapping segments, trading modest frequency resolution for clean noise-free estimates.
Coding Tasks (use CoLab or notebook)¶
-
Implement a recursive Cooley-Tukey radix-2 FFT from scratch in Python and JAX, confirm exact numerical agreement with both a direct \(O(N^2)\) DFT matrix and
jnp.fft.fft, and verify Parseval's theorem and the Convolution Theorem numerically.import jax import jax.numpy as jnp import matplotlib.pyplot as plt def radix2_fft(x): N = x.shape[0] if N == 1: return x.astype(jnp.complex64) E = radix2_fft(x[0::2]) O = radix2_fft(x[1::2]) k = jnp.arange(N // 2, dtype=jnp.float32) twiddle = jnp.exp(-2j * jnp.pi * k / N) return jnp.concatenate([E + twiddle * O, E - twiddle * O]) def direct_dft(x): N = x.shape[0] n = jnp.arange(N, dtype=jnp.float32) k = n[:, None] F = jnp.exp(-2j * jnp.pi * k * n[None, :] / N) return jnp.dot(F, x) key = jax.random.PRNGKey(7) N = 64 x = jax.random.normal(key, shape=(N,)) h = jnp.concatenate([jnp.array([0.5, 0.3, 0.15, 0.05]), jnp.zeros(N - 4)]) X_mine = radix2_fft(x) X_direct = direct_dft(x) X_jax = jnp.fft.fft(x) print(f"Max error vs direct DFT: {float(jnp.max(jnp.abs(X_mine - X_direct))):.2e}") print(f"Max error vs jnp.fft.fft: {float(jnp.max(jnp.abs(X_mine - X_jax))):.2e}") # Parseval energy check time_energy = float(jnp.sum(jnp.abs(x) ** 2)) freq_energy = float(jnp.sum(jnp.abs(X_mine) ** 2) / N) print(f"Parseval check | Time energy: {time_energy:.4f} | Freq energy: {freq_energy:.4f}") # Convolution theorem (zero-padded linear convolution via FFT) L_pad = 128 x_pad = jnp.concatenate([x, jnp.zeros(L_pad - N)]) h_pad = jnp.concatenate([h[:4], jnp.zeros(L_pad - 4)]) y_fft = jnp.real(jnp.fft.ifft(radix2_fft(x_pad) * radix2_fft(h_pad)))[:N + 3] y_time = jnp.convolve(x, h[:4]) print(f"Convolution theorem max error: {float(jnp.max(jnp.abs(y_fft - y_time))):.2e}") # Plot O(N^2) vs O(N log2 N) operation counts Ns = jnp.array([16, 64, 256, 1024, 4096, 16384, 65536], dtype=jnp.float32) fig, ax = plt.subplots(figsize=(7.5, 4.0)) ax.loglog(Ns, Ns ** 2, "o-", color="#e74c3c", lw=2, label="Direct DFT: O(N^2)") ax.loglog(Ns, Ns * jnp.log2(Ns), "s-", color="#27ae60", lw=2, label="Cooley-Tukey FFT: O(N log2 N)") ax.set_xlabel("Signal Length N (log scale)") ax.set_ylabel("Operation Count (log scale)") ax.set_title("Why the FFT Changed Modern Science and Engineering") ax.legend() ax.grid(alpha=0.3, which="both") plt.tight_layout() plt.show() -
Create a challenging two-tone signal containing a loud non-integer-bin sinusoid (\(f_1 = 50.4\,\text{Hz}\), amplitude \(1.0\)) right beside a faint neighbour (\(f_2 = 64.0\,\text{Hz}\), amplitude \(0.005\), or \(-46\,\text{dB}\) weaker). Compare Rectangular, Hann, Hamming, and Blackman windows to watch the buried weak tone emerge cleanly once sidelobes drop.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt fs = 512.0 N = 256 n = jnp.arange(N, dtype=jnp.float32) t = n / fs # Strong tone off-bin (50.4 Hz) + weak hidden tone (-46 dB at 64 Hz) x = 1.0 * jnp.sin(2.0 * jnp.pi * 50.4 * t) + 0.005 * jnp.sin(2.0 * jnp.pi * 64.0 * t) windows = { "Rectangular": jnp.ones(N, dtype=jnp.float32), "Hann": 0.5 - 0.5 * jnp.cos(2.0 * jnp.pi * n / (N - 1)), "Hamming": 0.54 - 0.46 * jnp.cos(2.0 * jnp.pi * n / (N - 1)), "Blackman": 0.42 - 0.5 * jnp.cos(2.0 * jnp.pi * n / (N - 1)) + 0.08 * jnp.cos(4.0 * jnp.pi * n / (N - 1)), } colours = {"Rectangular": "#e74c3c", "Hann": "#3498db", "Hamming": "#f39c12", "Blackman": "#27ae60"} # Zero-pad to 2048 points for smooth high-resolution spectral plotting N_fft = 2048 freqs = jnp.fft.rfftfreq(N_fft, d=1.0 / fs) fig, ax = plt.subplots(figsize=(9.5, 4.6)) for name, w in windows.items(): xw = x * w spec = jnp.abs(jnp.fft.rfft(xw, n=N_fft)) spec_db = 20.0 * jnp.log10(spec / (jnp.max(spec) + 1e-12) + 1e-12) ax.plot(freqs, spec_db, lw=1.8, color=colours[name], label=name) # Report measured level at the weak tone 64 Hz idx_64 = int(jnp.argmin(jnp.abs(freqs - 64.0))) idx_58 = int(jnp.argmin(jnp.abs(freqs - 58.0))) print(f"{name:12s} | Level at 64 Hz target: {float(spec_db[idx_64]):6.1f} dB | Leakage floor at 58 Hz: {float(spec_db[idx_58]):6.1f} dB") ax.axvline(64.0, color="#9b59b6", ls="--", lw=1.3, label="Hidden weak tone (64 Hz, -46 dB)") ax.set_xlim(25, 100) ax.set_ylim(-95, 5) ax.set_xlabel("Frequency (Hz)") ax.set_ylabel("Normalised Magnitude (dB)") ax.set_title("Window Tapering Uncovers a -46 dB Signal Buried Under Rectangular Leakage") ax.legend(loc="upper right", fontsize=8.5) ax.grid(alpha=0.3) plt.tight_layout() plt.show() -
Compare a raw single-frame periodogram against Welch's averaged overlapping periodogram on a long noisy sensor recording containing two subtle oscillations (\(10\,\text{Hz}\) EEG-like alpha rhythm and \(27\,\text{Hz}\) narrow tone), and measure the noise-floor variance drop quantitatively.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(123) fs = 256.0 N_total = 4096 # 16 seconds at 256 Hz t = jnp.arange(N_total, dtype=jnp.float32) / fs # Two faint oscillations buried in strong white Gaussian noise x = (0.35 * jnp.sin(2.0 * jnp.pi * 10.0 * t) + 0.28 * jnp.sin(2.0 * jnp.pi * 27.0 * t) + 1.6 * jax.random.normal(key, shape=(N_total,))) # 1. Raw full-length Hann periodogram n_all = jnp.arange(N_total, dtype=jnp.float32) w_all = 0.5 - 0.5 * jnp.cos(2.0 * jnp.pi * n_all / (N_total - 1)) U_all = jnp.sum(w_all ** 2) X_all = jnp.fft.rfft(x * w_all) psd_raw = (jnp.abs(X_all) ** 2) / (fs * U_all) freqs_raw = jnp.fft.rfftfreq(N_total, d=1.0 / fs) # 2. Welch's method (segment length 256, 50% overlap -> 31 segments!) seg_len = 256 hop = 128 n_seg = jnp.arange(seg_len, dtype=jnp.float32) w_seg = 0.5 - 0.5 * jnp.cos(2.0 * jnp.pi * n_seg / (seg_len - 1)) U_seg = jnp.sum(w_seg ** 2) seg_psds = [] for start in range(0, N_total - seg_len + 1, hop): chunk = x[start:start + seg_len] * w_seg X_chunk = jnp.fft.rfft(chunk) seg_psds.append((jnp.abs(X_chunk) ** 2) / (fs * U_seg)) psd_welch = jnp.mean(jnp.stack(seg_psds, axis=0), axis=0) freqs_welch = jnp.fft.rfftfreq(seg_len, d=1.0 / fs) # Measure variance in pure noise band (60 Hz to 110 Hz) raw_noise_band = psd_raw[(freqs_raw >= 60.0) & (freqs_raw <= 110.0)] welch_noise_band = psd_welch[(freqs_welch >= 60.0) & (freqs_welch <= 110.0)] var_reduction = float(jnp.var(raw_noise_band) / jnp.var(welch_noise_band)) print(f"Welch segments averaged: {len(seg_psds)}") print(f"Noise-band PSD std | Raw periodogram: {float(jnp.std(raw_noise_band)):.4f} | Welch: {float(jnp.std(welch_noise_band)):.4f}") print(f"Variance reduction factor achieved by Welch: {var_reduction:.1f}x") fig, ax = plt.subplots(figsize=(9.5, 4.4)) ax.plot(freqs_raw, 10.0 * jnp.log10(psd_raw + 1e-12), color="#e74c3c", alpha=0.45, lw=1.0, label="Raw Periodogram (High Variance)") ax.plot(freqs_welch, 10.0 * jnp.log10(psd_welch + 1e-12), color="#27ae60", lw=2.3, label=f"Welch PSD ({len(seg_psds)} Overlapping Segments)") ax.axvline(10.0, color="#3498db", ls="--", lw=1.2, label="True peaks (10 Hz and 27 Hz)") ax.axvline(27.0, color="#3498db", ls="--", lw=1.2) ax.set_xlim(0, 80) ax.set_xlabel("Frequency (Hz)") ax.set_ylabel("Power Spectral Density (dB / Hz)") ax.set_title("Welch Averaging Calms Periodogram Noise to Reveal Faint Spectral Peaks") ax.legend(loc="upper right", fontsize=8.5) ax.grid(alpha=0.3) plt.tight_layout() plt.show()