Skip to content

Time-Frequency Analysis and Wavelets

A standard Fourier transform tells you which musical notes were played during a concert, yet it blends the opening chord and the final cymbal crash into one timeless soup. In this section, we build the Short-Time Fourier Transform, uncover the Gabor time-frequency uncertainty limit, step up to multi-resolution wavelet filter banks, and construct the analytic signal via the Hilbert transform to track instantaneous amplitude and phase.

Why One Global Spectrum Loses Time

  • Imagine finding a crumpled shopping list backstage after a piano recital that reads twenty middle C notes, fourteen F sharps, and eight low G notes. You know the exact musical ingredients of the piece, yet you have no idea whether the pianist played a gentle lullaby forwards or hammered the entire score backwards! Playing a melody in reverse uses the very same notes in the very same proportions, so an ingredient list alone cannot distinguish past from future.

  • That exact blindness happens whenever we feed a whole recording into one global Discrete Fourier Transform (DFT). Every frequency bin \(X[k]\) sums the signal over the entire duration from \(n = 0\) to \(N - 1\), averaging every moment together. Consider a linear chirp whose pitch glides smoothly upward from \(f_0\) to \(f_1\), written \(x_{\text{up}}(t) = \cos(2\pi (f_0 t + \frac{1}{2}\kappa t^2))\), alongside its time-reversed twin \(x_{\text{down}}(t) = x_{\text{up}}(T - t)\) sliding downward from \(f_1\) to \(f_0\).

  • Because reversing time simply conjugates the Fourier transform without changing its length, the two opposing signals share identical magnitude spectra.

\[|X_{\text{up}}(f)| = |X_{\text{down}}(f)|\]
  • All timing information disappears out of the magnitude plot and hides inside delicate phase cancellations across thousands of bins. Yet almost every signal we care about in science and AI is non-stationary, meaning its frequency mix evolves moment by moment. Spoken syllables glide rapidly from vowels to fricatives in chapter 10, cortical brain waves burst into brief oscillations in chapter 12, and heartbeats produce crisp rhythmic spikes in chapter 24. To read these signals, we need the mathematical equivalent of musical sheet notation, a time-frequency representation.

The Short-Time Fourier Transform and Spectrograms

  • How do you read a vast medieval tapestry when you only own a small camera? Instead of stepping back until every figure blurs into beige, you slide a spotlight smoothly along the wall and take overlapping close-up photographs of one small patch at a time. Each photograph captures local detail while its position along the wall preserves where that detail lived.

  • The Short-Time Fourier Transform (STFT) applies that exact sliding-spotlight trick to a waveform \(x[n]\). We multiply a short slice of \(N\) samples by a smooth tapered window function \(w[n]\) (such as a Hann or Hamming bell curve that fades gently to zero at both edges, avoiding abrupt spectral leakage), compute its \(N\)-point DFT, advance the window forward by a hop size \(H\), and repeat across the whole signal.

\[X[m, k] = \sum_{n=0}^{N-1} x[n + mH] \, w[n] \, e^{-j 2\pi k n / N}\]
  • Here \(m\) indexes the time frame, \(k\) indexes the frequency bin \(f_k = k f_s / N\), and the complex number \(X[m, k]\) reports both the local amplitude and local phase inside that patch. Plotting the squared magnitude \(|X[m, k]|^2\) (almost always compressed onto a logarithmic decibel scale, \(10 \log_{10}(|X[m, k]|^2 + \epsilon)\)) creates a spectrogram, with time running horizontally, frequency rising vertically, and colour intensity showing local energy. On a spectrogram, an upward chirp traces a crisp rising diagonal stripe while a downward chirp slopes unmistakably down.

  • Better still, the STFT is cleanly invertible. Suppose you want to mute background hiss in specific time-frequency bins or separate a singer from drums (chapter 10) and turn the edited spectrogram back into playable audio. Taking the inverse DFT of each modified frame \(x_m[n] = \text{IDFT}\{X[m, k]\}\), multiplying by a synthesis window, and summing all shifted overlapping frames produces the overlap-add inverse STFT (iSTFT).

\[\hat{x}[n] = \frac{\sum_{m} w[n - mH] \, x_m[n - mH]}{\sum_{m} w[n - mH]^2}\]
  • When the analysis window and hop size satisfy the Constant Overlap-Add (COLA) condition (for example, a periodic Hann window shifted by \(50\%\) or \(75\%\) overlap), the denominator adds up to a flat constant everywhere. Unmodified frames then reconstruct the original waveform to floating-point machine precision, making the STFT-edit-iSTFT loop the workhorse of audio restoration and neural source separation.

The Gabor Time-Frequency Uncertainty Limit

  • If sliding a window works so cleanly, why not shrink \(w[n]\) down to three samples so we pinpoint both the exact microsecond and the exact frequency of every event? Picture trying to judge the pitch of a double bass note from a one-millisecond audio snippet. In one millisecond, a \(50\,\text{Hz}\) bass string completes barely one-twentieth of a single oscillation, looking almost like a straight flat line! Conversely, if you stretch your listening window to two full seconds to count a hundred cycles and measure the bass pitch to \(0.5\,\text{Hz}\) accuracy, any sharp handclap occurring inside those two seconds gets smeared across the entire window.

  • Dennis Gabor proved in 1946 that this frustration is not a flaw in our code, it is a hard mathematical law of Fourier analysis, the exact signal processing twin of Heisenberg's uncertainty principle in quantum physics. Measure a window's effective time spread \(\Delta t\) (the standard deviation of its energy density \(|w(t)|^2\)) and its effective frequency spread \(\Delta f\) (the standard deviation of \(|W(f)|^2\)). Their product can never fall below a strict universal floor.

\[\Delta t \cdot \Delta f \ge \frac{1}{4\pi}\]
  • Only one curve in all of mathematics touches equality in that bound, the Gaussian bell curve (producing a Gabor atom, a sinusoid tucked snugly inside a Gaussian envelope). Every other window trades a slightly larger area in exchange for sharper sidelobe roll-off.

  • Notice what this bound imposes on the STFT. Once you pick one fixed window length \(N\), every single cell in the time-frequency plane becomes a rigid rectangle of identical width \(\Delta t\) and identical height \(\Delta f\). That uniform tiling works nicely when all frequencies of interest live in a narrow band, yet it struggles badly whenever a recording mixes slow low-frequency waves with brief high-frequency transients. In a real EEG brain recording (chapter 12) or a piece of music (chapter 10), slow \(4\,\text{Hz}\) rhythms need long windows spanning hundreds of milliseconds to separate neighbouring pitches, whereas sudden \(2\,\text{ms}\) acoustic clicks or fast \(100\,\text{Hz}\) gamma bursts demand millisecond timing. No single STFT window size can flatter both at once.

Continuous and Discrete Wavelet Transforms

  • Think about how a skilled carpenter works. Nobody measures both the width of a dining room and the thickness of a hairline crack with one rigid metre stick. Instead, you reach for a long tape measure for sweeping spans and a fine vernier calliper for tiny edges. Wavelet analysis brings that exact multi-scale toolbox to signal processing.

  • A wavelet (literally a "little wave") is a brief, oscillating, zero-mean template \(\psi(t)\) localised in both time and frequency. Rather than chopping a signal with one fixed window and changing how many sine cycles squeeze inside, we keep one mother wavelet \(\psi(t)\) and generate a whole family of daughter wavelets by stretching or squeezing its time axis by a scale \(a > 0\) and sliding its centre to position \(b\).

\[\psi_{a,b}(t) = \frac{1}{\sqrt{a}} \, \psi\!\left(\frac{t - b}{a}\right)\]
  • Sliding every scaled daughter across the signal via inner products defines the Continuous Wavelet Transform (CWT) (connecting directly to inner products from chapter 01).
\[W_x(a, b) = \frac{1}{\sqrt{a}} \int_{-\infty}^{\infty} x(t) \, \psi^*\!\left(\frac{t - b}{a}\right) dt\]
  • Look at how naturally the Gabor rectangle adapts! When scale \(a\) is small, \(\psi_{a,b}\) compresses into a needle-sharp high-frequency probe with tiny \(\Delta t\) and broad \(\Delta f\), catching sudden clicks and high-frequency bursts at the exact millisecond they strike. When scale \(a\) is large, \(\psi_{a,b}\) stretches into a gentle low-frequency probe with wide \(\Delta t\) and razor-thin \(\Delta f\), distinguishing closely spaced slow rhythms effortlessly. Every tile still respects \(\Delta t \cdot \Delta f \ge \frac{1}{4\pi}\) with equal area, yet its proportions reshape dynamically across octaves.

Comparison of fixed-tile STFT grids and adaptive multi-resolution wavelet tiling in the time-frequency plane

  • Computing the CWT at every continuous scale \(a\) is redundant and slow for compression or real-time hardware, so Stephane Mallat developed the fast \(O(N)\) Discrete Wavelet Transform (DWT) using multi-resolution filter banks. Restricting scales to powers of two (\(a = 2^j\), dyadic octaves), each stage splits the incoming signal through two paired filters, a low-pass scaling filter \(h[n]\) yielding smooth approximation coefficients \(A_j\) and a high-pass wavelet filter \(g[n]\) yielding crisp detail coefficients \(D_j\), followed immediately by downsampling by \(2\).

  • Recursively splitting only the low-pass approximation \(A_j\) into \(A_{j+1}\) and \(D_{j+1}\) builds an octave pyramid whose total coefficient count equals the original sample count \(N\) with zero redundancy! Three famous wavelet families appear throughout science and engineering.

    • Haar wavelet. The oldest and simplest orthonormal wavelet, using two-tap averages \((x[2k] + x[2k+1]) / \sqrt{2}\) for approximations and differences \((x[2k] - x[2k+1]) / \sqrt{2}\) for details. Its blocky step shape excels at catching sudden jumps and piecewise-constant edges.
    • Daubechies wavelets (db4, db8). Compactly supported smooth orthonormal wavelets engineered with vanishing moments, meaning polynomial trends produce zero detail coefficients. That sparsity powers JPEG 2000 image compression and biomedical signal coding.
    • Morlet wavelet. A complex sinusoid tapered by a Gaussian envelope, \(\psi(t) \propto e^{j\omega_0 t} e^{-t^2 / (2\sigma^2)}\). Because it is smooth, complex-valued, and reaches the Gabor limit, Morlet CWT scalograms are the gold standard for analysing time-varying EEG and LFP brain oscillations in chapter 12.
  • One of the most magical applications of the DWT is wavelet denoising via soft thresholding. Real signals concentrate their energy into a tiny handful of large wavelet coefficients where edges or oscillations live, whereas white Gaussian noise spreads thinly and uniformly across every scale. A classic linear low-pass filter strips high-frequency noise only by blurring sharp edges. Instead, David Donoho's VisuShrink rule computes a universal threshold \(\lambda = \hat{\sigma} \sqrt{2 \ln N}\) (estimating noise standard deviation \(\hat{\sigma}\) robustly from the finest detail band via its median absolute deviation) and gently pulls every detail coefficient toward zero.

\[\eta_\lambda(d) = \operatorname{sign}(d) \max(|d| - \lambda, \, 0)\]
  • Inverting the thresholded DWT removes noise cleanly across smooth flats while leaving sharp steps, spikes, and ECG complexes remarkably crisp!

The Analytic Signal and the Hilbert Transform

  • Picture watching a glowing reflector taped to the rim of a spinning bicycle wheel strictly from straight ahead. All your eye perceives is a dot bobbing up and down along one vertical line, tracing a real cosine wave \(x(t) = A(t) \cos(\phi(t))\). Whenever the dot crosses zero at the centre of the axle, you cannot tell whether the wheel has shrunk to zero radius or is still wide and simply passing through horizontal! You also cannot tell whether it is spinning clockwise or anticlockwise.

  • Now imagine mounting a second camera from the side to record the horizontal shadow \(y(t) = A(t) \sin(\phi(t))\), lagging by exactly \(90^\circ\) (a quarter cycle). Pairing the vertical and horizontal shadows reconstructs the full rotating 2D wheel \(z(t) = x(t) + j y(t) = A(t) e^{j\phi(t)}\), letting you read off the exact radius and exact angle at every split second.

  • In signal processing, that \(90^\circ\) phase-shifted quadrature twin is produced by the Hilbert transform \(\mathcal{H}\{x\}(t)\). In the frequency domain, the Hilbert transform multiplies every positive frequency by \(-j\) (a \(-90^\circ\) shift) and every negative frequency by \(+j\) (a \(+90^\circ\) shift), leaving DC untouched. Adding \(j\,\mathcal{H}\{x\}(t)\) to the original real signal creates the complex analytic signal.

\[z(t) = x(t) + j \, \mathcal{H}\{x\}(t) = A(t) \, e^{j \phi(t)}\]
  • Notice a wonderfully tidy trick in the Fourier domain! Because a real signal's positive and negative frequencies are conjugate twins, adding \(j\,\mathcal{H}\{x\}(t)\) doubles every positive frequency component and cancels every negative frequency component to exactly zero. Computing the discrete analytic signal in code therefore takes just four lines, run the FFT, double the positive frequency bins, zero the negative frequency bins, and run the inverse FFT.

Constructing the complex analytic signal via the Hilbert transform to extract instantaneous amplitude envelope and unwrapped phase

  • Once you hold the complex rotating phasor \(z(t)\), three physical quantities fall straight into your lap at every single sample.

    • Instantaneous amplitude envelope \(A(t) = |z(t)| = \sqrt{x(t)^2 + \mathcal{H}\{x\}(t)^2}\), smoothly tracing how loudness, carrier power, or rhythmic burst strength rises and falls over time.
    • Instantaneous phase \(\phi(t) = \operatorname{atan2}(\operatorname{Im} z(t), \operatorname{Re} z(t))\), telling you the exact angle of the oscillation inside \((-\pi, \pi]\). Unwrapping the \(2\pi\) jumps turns that sawtooth into a smooth climbing curve \(\phi_{\text{unwrap}}(t)\).
    • Instantaneous frequency \(f_{\text{inst}}(t) = \frac{1}{2\pi} \frac{d \phi_{\text{unwrap}}(t)}{dt}\), tracking the moment-by-moment pitch glide of a narrowband chirp or voice harmonic.
  • Analytic signals appear everywhere downstream in this Compendium. Communications receivers use \(A(t)\) and \(f_{\text{inst}}(t)\) to demodulate AM and FM radio waves, speech processors in chapter 10 track syllable-rate modulation envelopes, and computational neuroscientists in chapter 12 band-pass filter brain recordings and apply the Hilbert transform to measure phase locking across brain regions and phase-amplitude coupling (where the slow phase of a \(6\,\text{Hz}\) theta wave gates the burst amplitude envelope of \(80\,\text{Hz}\) gamma activity!).

Take-Home

  • A single global DFT sums across all time, so reversing a linear chirp produces an identical magnitude spectrum and hides all timing inside subtle phase relations.
  • The Short-Time Fourier Transform (STFT) slides a smooth tapered window across the signal to build spectrograms and supports exact signal editing and reconstruction via overlap-add inverse STFT when the window obeys Constant Overlap-Add.
  • The Gabor uncertainty limit (\(\Delta t \cdot \Delta f \ge \frac{1}{4\pi}\)) forbids arbitrary simultaneous sharpness in time and frequency, forcing every fixed STFT window to compromise when slow low pitches coexist with sharp high-frequency bursts.
  • Continuous and Discrete Wavelet Transforms adapt their tile aspect ratio by frequency using scaled templates or iterated two-channel filter banks, enabling sparse multi-resolution representations and edge-preserving denoising through soft thresholding.
  • The Hilbert transform pairs a real oscillation with its \(90^\circ\) quadrature partner to build the complex analytic signal \(z(t) = A(t) e^{j\phi(t)}\), exposing instantaneous envelope, phase, and frequency for radio, speech, and brain-rhythm analysis.

Coding Tasks (use CoLab or notebook)

  1. Expose the chirp magnitude paradox, visualise the Gabor STFT window trade-off, and verify exact overlap-add iSTFT reconstruction from scratch in JAX. Compare global spectra of upward and downward chirps, inspect short-window versus long-window spectrograms on a mixed multi-scale signal, and measure round-trip iSTFT error.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    fs = 1024
    duration = 1.0
    t = jnp.arange(0, duration, 1.0 / fs)
    N = len(t)
    
    # Upward linear chirp (40 Hz to 340 Hz) and its exact time-reversed downward twin
    f0, f1 = 40.0, 340.0
    phase_up = 2.0 * jnp.pi * (f0 * t + 0.5 * (f1 - f0) * t ** 2 / duration)
    x_up = jnp.cos(phase_up)
    x_down = x_up[::-1]
    
    # Global magnitude spectra are virtually identical despite opposite time directions
    mag_up = jnp.abs(jnp.fft.rfft(x_up)) / N
    mag_down = jnp.abs(jnp.fft.rfft(x_down)) / N
    freqs_global = jnp.fft.rfftfreq(N, d=1.0 / fs)
    print(f"Max global magnitude spectrum diff (up vs down chirp): {float(jnp.max(jnp.abs(mag_up - mag_down))):.2e}")
    
    def compute_stft(x, n_fft, hop):
        pad = n_fft // 2
        x_pad = jnp.concatenate([jnp.zeros(pad), x, jnp.zeros(pad)])
        win = 0.5 - 0.5 * jnp.cos(2.0 * jnp.pi * jnp.arange(n_fft) / n_fft)  # Periodic Hann
        n_frames = (len(x_pad) - n_fft) // hop + 1
        frames = jnp.stack([x_pad[m * hop : m * hop + n_fft] * win for m in range(n_frames)])
        return jnp.fft.rfft(frames, axis=-1)
    
    def compute_istft(X, n_fft, hop, out_len):
        pad = n_fft // 2
        win = 0.5 - 0.5 * jnp.cos(2.0 * jnp.pi * jnp.arange(n_fft) / n_fft)
        n_frames = X.shape[0]
        total_len = (n_frames - 1) * hop + n_fft
        frames_t = jnp.fft.irfft(X, n=n_fft, axis=-1)
        # Pure functional overlap-add using padded frame stacks (no in-place scatter)
        num_parts, den_parts = [], []
        for m in range(n_frames):
            s = m * hop
            tail = total_len - s - n_fft
            num_parts.append(jnp.concatenate([jnp.zeros(s), frames_t[m] * win, jnp.zeros(tail)]))
            den_parts.append(jnp.concatenate([jnp.zeros(s), win ** 2, jnp.zeros(tail)]))
        x_rec = jnp.sum(jnp.stack(num_parts), axis=0) / jnp.maximum(jnp.sum(jnp.stack(den_parts), axis=0), 1e-8)
        return x_rec[pad : pad + out_len]
    
    # Verify exact overlap-add iSTFT round-trip on the upward chirp
    X_up = compute_stft(x_up, n_fft=128, hop=32)
    x_rec = compute_istft(X_up, n_fft=128, hop=32, out_len=N)
    print(f"Overlap-add iSTFT max reconstruction error: {float(jnp.max(jnp.abs(x_up - x_rec))):.2e}")
    
    # Mixed signal: two close low tones (45 Hz + 62 Hz) plus a brief 320 Hz click at t = 0.50 s
    x_mix = (0.7 * jnp.sin(2.0 * jnp.pi * 45.0 * t)
             + 0.7 * jnp.sin(2.0 * jnp.pi * 62.0 * t)
             + 1.6 * jnp.exp(-0.5 * ((t - 0.50) / 0.008) ** 2) * jnp.cos(2.0 * jnp.pi * 320.0 * t))
    
    S_short = 20.0 * jnp.log10(jnp.abs(compute_stft(x_mix, n_fft=64, hop=16)).T + 1e-4)
    S_long = 20.0 * jnp.log10(jnp.abs(compute_stft(x_mix, n_fft=256, hop=32)).T + 1e-4)
    
    fig, axes = plt.subplots(1, 3, figsize=(13.2, 3.8))
    axes[0].plot(freqs_global, mag_up, color="#3498db", lw=2.0, label="Upward Chirp")
    axes[0].plot(freqs_global, mag_down, color="#e74c3c", lw=1.4, ls="--", label="Downward Chirp")
    axes[0].set_xlim(0, 420); axes[0].set_title("Global FFT (Identical Magnitude!)")
    axes[0].set_xlabel("Frequency (Hz)"); axes[0].set_ylabel("Magnitude"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    axes[1].imshow(S_short, aspect="auto", origin="lower", extent=[0, duration, 0, fs / 2], cmap="magma")
    axes[1].set_ylim(0, 420); axes[1].set_title("Short Window (N=64, Sharp Click)")
    axes[1].set_xlabel("Time (s)"); axes[1].set_ylabel("Frequency (Hz)")
    
    axes[2].imshow(S_long, aspect="auto", origin="lower", extent=[0, duration, 0, fs / 2], cmap="magma")
    axes[2].set_ylim(0, 420); axes[2].set_title("Long Window (N=256, Resolves 45/62 Hz)")
    axes[2].set_xlabel("Time (s)"); axes[2].set_ylabel("Frequency (Hz)")
    plt.tight_layout(); plt.show()
    

  2. Build a 4-level Haar Discrete Wavelet Transform (DWT) filter bank and soft-thresholding denoiser from scratch in JAX. Corrupt a piecewise-smooth signal containing sharp jumps and a narrow spike with Gaussian noise, apply Donoho's universal threshold \(\lambda = \hat{\sigma} \sqrt{2 \ln N}\), and compare edge preservation and SNR against a standard moving-average low-pass filter.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(7)
    N = 512
    t = jnp.linspace(0.0, 1.0, N)
    
    # Piecewise-smooth test signal: slow wave + sharp step + narrow transient bump
    x_clean = (0.8 * jnp.sin(2.0 * jnp.pi * 2.5 * t)
               + jnp.where((t >= 0.30) & (t <= 0.55), 1.8, 0.0)
               + 2.2 * jnp.exp(-0.5 * ((t - 0.78) / 0.012) ** 2))
    sigma_true = 0.28
    x_noisy = x_clean + sigma_true * jax.random.normal(key, shape=(N,))
    
    inv_s2 = 1.0 / jnp.sqrt(2.0)
    
    def haar_dwt(x, levels=4):
        approx = x
        details = []
        for _ in range(levels):
            a = (approx[0::2] + approx[1::2]) * inv_s2
            d = (approx[0::2] - approx[1::2]) * inv_s2
            details.append(d)
            approx = a
        return approx, details
    
    def haar_idwt(approx, details):
        x = approx
        for d in reversed(details):
            even = (x + d) * inv_s2
            odd = (x - d) * inv_s2
            x = jnp.stack([even, odd], axis=-1).reshape(-1)
        return x
    
    # Decompose, estimate noise via MAD of finest detail band D1, and soft-threshold
    approx, details = haar_dwt(x_noisy, levels=4)
    sigma_est = float(jnp.median(jnp.abs(details[0])) / 0.6745)
    lam = sigma_est * float(jnp.sqrt(2.0 * jnp.log(N)))
    
    details_shrunk = [jnp.sign(d) * jnp.maximum(jnp.abs(d) - lam, 0.0) for d in details]
    x_wavelet = haar_idwt(approx, details_shrunk)
    
    # Compare against a linear 13-tap moving-average low-pass filter
    kernel = jnp.ones(13) / 13.0
    x_lowpass = jnp.convolve(x_noisy, kernel, mode="same")
    
    def snr_db(clean, est):
        return float(10.0 * jnp.log10(jnp.sum(clean ** 2) / jnp.maximum(jnp.sum((clean - est) ** 2), 1e-10)))
    
    print(f"Estimated noise sigma: {sigma_est:.3f} (true {sigma_true:.3f}) | Threshold lambda: {lam:.3f}")
    print(f"Noisy SNR: {snr_db(x_clean, x_noisy):.2f} dB | Low-pass SNR: {snr_db(x_clean, x_lowpass):.2f} dB | Wavelet SNR: {snr_db(x_clean, x_wavelet):.2f} dB")
    
    fig, axes = plt.subplots(1, 3, figsize=(13.2, 3.6))
    axes[0].plot(t, x_noisy, color="#95a5a6", lw=0.9, label="Noisy")
    axes[0].plot(t, x_clean, color="#333", lw=1.6, label="Ground Truth")
    axes[0].set_title(f"Noisy Input ({snr_db(x_clean, x_noisy):.1f} dB)"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    axes[1].plot(t, x_clean, color="#333", lw=1.2, ls="--", label="Truth")
    axes[1].plot(t, x_lowpass, color="#e74c3c", lw=1.8, label="Moving Average")
    axes[1].set_title(f"Linear Low-Pass ({snr_db(x_clean, x_lowpass):.1f} dB, Blurred)"); axes[1].legend(); axes[1].grid(alpha=0.3)
    
    axes[2].plot(t, x_clean, color="#333", lw=1.2, ls="--", label="Truth")
    axes[2].plot(t, x_wavelet, color="#27ae60", lw=1.8, label="Haar Soft-Thresh")
    axes[2].set_title(f"Wavelet Denoised ({snr_db(x_clean, x_wavelet):.1f} dB, Crisp Edges)"); axes[2].legend(); axes[2].grid(alpha=0.3)
    for ax in axes:
        ax.set_xlabel("Time (s)")
    plt.tight_layout(); plt.show()
    

  3. Construct the discrete analytic signal via the Hilbert transform in pure JAX and extract both the instantaneous amplitude envelope \(A(t)\) and instantaneous frequency \(f_{\text{inst}}(t)\) of a modulated oscillation packet. Verify the recovered envelope and pitch glide against ground truth across the interior of the burst.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    fs = 512.0
    N = 1024
    t = jnp.arange(N) / fs
    
    # Ground-truth modulated burst (analogous to an EEG oscillation spindle or FM speech glide)
    env_true = 0.25 + 1.15 * jnp.exp(-0.5 * ((t - 1.0) / 0.32) ** 2)
    f_true = 16.0 + 18.0 * t  # Linearly rising instantaneous frequency from 16 Hz to 52 Hz
    phi_true = 2.0 * jnp.pi * (16.0 * t + 0.5 * 18.0 * t ** 2)
    x = env_true * jnp.cos(phi_true)
    
    # Analytic signal via one-sided FFT multiplier (zero negative bins, double positive bins)
    X = jnp.fft.fft(x)
    idx = jnp.arange(N)
    h = jnp.where((idx == 0) | (idx == N // 2), 1.0, jnp.where(idx < N // 2, 2.0, 0.0))
    z = jnp.fft.ifft(X * h)
    
    env_est = jnp.abs(z)
    phi_wrap = jnp.angle(z)
    # Pure functional phase unwrapping without external libraries
    dphi = jnp.diff(phi_wrap)
    dphi_unwrapped = (dphi + jnp.pi) % (2.0 * jnp.pi) - jnp.pi
    f_inst = dphi_unwrapped * fs / (2.0 * jnp.pi)
    
    # Evaluate interior accuracy away from FFT boundary edges
    sl = slice(60, N - 60)
    env_mae = float(jnp.mean(jnp.abs(env_est[sl] - env_true[sl])))
    freq_mae = float(jnp.mean(jnp.abs(f_inst[sl] - f_true[1:][sl])))
    print(f"Interior Envelope MAE: {env_mae:.4f} | Interior Instantaneous Freq MAE: {freq_mae:.3f} Hz")
    
    fig, axes = plt.subplots(1, 3, figsize=(13.2, 3.7))
    axes[0].plot(t, x, color="#3498db", lw=0.9, alpha=0.8, label="Real wave x(t)")
    axes[0].plot(t, env_est, color="#e74c3c", lw=2.1, label="Hilbert Envelope |z(t)|")
    axes[0].plot(t, env_true, color="#333", lw=1.3, ls="--", label="True Envelope")
    axes[0].set_title("Signal & Hilbert Envelope"); axes[0].set_xlabel("Time (s)"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    axes[1].plot(t[:200], phi_wrap[:200], color="#f39c12", lw=1.4, label="Wrapped Phase (-pi, pi)")
    axes[1].set_title("Instantaneous Wrapped Phase (Zoom)"); axes[1].set_xlabel("Time (s)"); axes[1].set_ylabel("Radians")
    axes[1].legend(); axes[1].grid(alpha=0.3)
    
    axes[2].plot(t[sl], f_true[sl], color="#333", lw=2.0, ls="--", label="True Freq f(t)")
    axes[2].plot(t[1:][sl], f_inst[sl], color="#27ae60", lw=1.8, label="Hilbert f_inst(t)")
    axes[2].set_title("Instantaneous Frequency Recovery"); axes[2].set_xlabel("Time (s)"); axes[2].set_ylabel("Frequency (Hz)")
    axes[2].legend(); axes[2].grid(alpha=0.3)
    plt.tight_layout(); plt.show()