Skip to content

Digital Filtering and Adaptive Signal Processing

Once you can inspect a signal across frequency and time, the next superpower is sculpting it cleanly, removing mains hum, carving out target rhythms, and cancelling interference that changes in real time. In this closing section of chapter 09, we link the z-transform's pole-zero geometry to FIR and IIR filter design, derive Wiener optimal spectral denoising, and build the adaptive Least Mean Squares filter that turns online stochastic gradient descent into live echo and artefact cancellation.

Sculpting Spectra With Frequency-Selective Filters

  • Imagine standing inside a sunlit stained-glass chapel. Ruby glass lets warm red light stream onto the stone floor while blocking blue glare, whereas cobalt glass does the reverse. A digital filter acts as an exact mathematical pane of stained glass for waveforms, letting desired oscillations glide straight through untouched while dimming or silencing unwanted frequencies.

  • Four everyday filter shapes form the backbone of audio, neuroscience, and biomedical pipelines.

    • Low-pass filter. Keeps slow trends below a cutoff frequency \(f_c\) and strips fast high-frequency hiss. Every analogue-to-digital converter relies on a low-pass anti-aliasing filter before sampling.
    • High-pass filter. Lets fast fluctuations pass while discarding steady DC offset and slow baseline drift (such as slow breathing drift underneath an electrocardiogram trace in chapter 24).
    • Band-pass filter. Carves out one target frequency window \([f_1, f_2]\), isolating an \(8\,\text{Hz}\) to \(12\,\text{Hz}\) cortical alpha rhythm in chapter 12 or one vocal band in chapter 10.
    • Notch (band-stop) filter. Surgically punches out one narrow intrusive tone while leaving neighbouring frequencies intact, famous for stripping \(50\,\text{Hz}\) or \(60\,\text{Hz}\) wall-outlet mains hum from studio microphones and clinical sensors.
  • Because linear time-invariant (LTI) filters treat complex exponentials \(e^{j\omega n}\) as eigenfunctions (connecting directly to eigenvectors in chapter 02), feeding in a pure sine wave at normalised radian frequency \(\omega = 2\pi f / f_s\) returns the exact same frequency multiplied by one complex number, the frequency response \(H(e^{j\omega})\).

\[H(e^{j\omega}) = |H(e^{j\omega})| \, e^{j \phi(\omega)}\]
  • The magnitude response \(|H(e^{j\omega})|\) scales the wave's height, while the phase response \(\phi(\omega) = \angle H(e^{j\omega})\) shifts its timing. How severely a filter distorts sharp pulse shapes depends on its group delay, the negative slope of phase with respect to frequency.
\[\tau_g(\omega) = -\frac{d\phi(\omega)}{d\omega}\]
  • Think of a marching band stepping down an avenue where tubas (low notes) and flutes (high notes) start perfectly aligned. If every frequency experiences the exact same group delay \(\tau_g(\omega) = D\) samples (a linear-phase filter, \(\phi(\omega) = -\omega D\)), the whole band arrives \(D\) samples later in spotless formation! If \(\tau_g(\omega)\) varies unevenly across frequencies, fast harmonics outrun or lag behind slow harmonics and sharp pulses smear into wavy ringing tails.

The z-Transform and Pole-Zero Geometry

  • Every practical discrete-time linear filter computes its current output \(y[n]\) as a weighted mix of recent inputs \(x[n - k]\) and (optionally) recent past outputs \(y[n - k]\).
\[y[n] = \sum_{k=0}^{M} b_k \, x[n - k] - \sum_{k=1}^{L} a_k \, y[n - k]\]
  • Applying the z-transform (where multiplying by \(z^{-1}\) simply means delaying a sequence by one sample) turns that recursive recipe into a compact rational transfer function \(H(z)\), which factors cleanly into its numerator roots (zeros \(q_m\)) and denominator roots (poles \(p_\ell\)).
\[H(z) = \frac{\sum_{k=0}^{M} b_k z^{-k}}{1 + \sum_{k=1}^{L} a_k z^{-k}} = G \, \frac{\prod_{m=1}^{M} (1 - q_m z^{-1})}{\prod_{\ell=1}^{L} (1 - p_\ell z^{-1})}\]
  • Now comes one of the most delightful visual analogies in all of engineering. Picture stretching a giant rubber circus tent tightly across the entire complex \(z\)-plane. Wherever you place a pole \(p_\ell\), imagine pushing an infinitely tall tent pole straight upward from underneath so the canvas rises into a sharp mountain peak. Wherever you place a zero \(q_m\), imagine hammering a tent peg right into the floor so the canvas touches zero height.

  • To discover the filter's exact frequency response \(|H(e^{j\omega})|\), simply walk counter-clockwise along the unit circle \(|z| = 1\) from angle \(\omega = 0\) (DC) to \(\omega = \pi\) (Nyquist) and record the height of the rubber tent overhead! Mathematically, plugging \(z = e^{j\omega}\) into the factored transfer function reveals a pure distance formula.

\[|H(e^{j\omega})| = |G| \, \frac{\prod_{m=1}^{M} |e^{j\omega} - q_m|}{\prod_{\ell=1}^{L} |e^{j\omega} - p_\ell|}\]
  • Every term \(|e^{j\omega} - q_m|\) is literally the straight-line distance from your current frequency point on the unit circle to zero \(q_m\), and \(|e^{j\omega} - p_\ell|\) is the distance to pole \(p_\ell\). Placing a zero right on the unit circle at angle \(\omega_0\) forces the numerator to zero when you walk past \(\omega_0\), carving a razor-deep notch. Placing a pole just inside the unit circle at angle \(\omega_p\) makes the denominator tiny as you pass \(\omega_p\), lifting a tall resonant peak!

Geometric relationship between poles and zeros on the complex z-plane unit circle and the resulting magnitude frequency response

  • That same unit circle governs BIBO stability (Bounded Input yields Bounded Output). Because each pole \(p_\ell\) contributes a natural impulse response mode scaling like \(p_\ell^n\), every pole must sit strictly inside the unit circle (\(|p_\ell| < 1\)) so echoes decay smoothly to zero. Let a single pole drift onto \(|z| = 1\) and the filter rings forever like an undamped bell; push it outside (\(|p_\ell| > 1\)) and output values explode exponentially to infinity!

FIR Versus IIR Filter Design

  • Splitting filters by whether they use output feedback (\(a_k \neq 0\)) divides digital filtering into two great families with wonderfully complementary strengths.

  • Finite Impulse Response (FIR) filters drop all feedback (\(a_k = 0\)), so every pole rests harmlessly at the origin \(z = 0\) and the filter simply convolves the input with \(M + 1\) taps \(b_k\) (identical to a 1D convolutional layer from chapter 06).

    • Windowed sinc design. An ideal brick-wall low-pass filter with cutoff \(f_c\) has an infinitely long impulse response \(h_{\text{ideal}}[n] = 2 f_c \operatorname{sinc}(2 f_c n)\). Truncating that tail abruptly causes ringing ripples (Gibbs phenomenon), so engineers multiply by a smooth tapered window (Hann, Hamming, or Kaiser) to trade a slightly gentler transition slope for clean stopband suppression.
    • Why engineers love FIR. FIR filters are unconditionally stable (they can never explode) and achieve exact linear phase effortlessly whenever their taps are mirror-symmetric (\(b_k = b_{M-k}\)), keeping delicate heartbeat peaks (chapter 24) and spike waveforms (chapter 12) completely undistorted. Their main cost is size, because carving a razor-sharp cutoff can require dozens or hundreds of taps and extra delay.
  • Infinite Impulse Response (IIR) filters keep feedback (\(a_k \neq 0\)), placing active poles close to the unit circle so a handful of taps create dramatic resonant peaks or steep frequency cliffs.

    • Classic analogue-inspired families. Butterworth filters deliver a maximally flat passband with zero ripple and gentle roll-off. Chebyshev filters achieve a much steeper cliff for the same order by tolerating tiny controlled ripples in either the passband or stopband. Elliptic (Cauer) filters reach the steepest transition mathematically possible for a given order by allowing equiripple behaviour in both bands.
    • Biquad cascades. High-order IIR polynomials are notoriously sensitive to floating-point rounding, which can accidentally nudge a pole past \(|z| = 1\). Real audio synthesisers and embedded DSP chips therefore factor any high-order IIR filter into a chain of robust second-order sections (biquads, two poles and two zeros each).
    • Trade-offs. IIR filters deliver sharp cutoffs with tiny memory and minimal latency (often four to eight coefficients where an FIR needs eighty), at the price of nonlinear phase dispersion (which offline pipelines cancel by filtering forward once and backward once via zero-phase filtering) and careful stability checks near \(|z| = 1\).

Wiener Filtering and Adaptive LMS Cancellation

  • Classical FIR and IIR filters shine when signal and noise occupy separate frequency bands, yet life is rarely that tidy. What happens when broadband hiss sits right on top of a human voice across the very same frequencies?

  • Wiener filtering (optimal stationary denoising). Rather than chopping off a whole band blindly, Norbert Wiener asked which linear filter minimises the expected mean squared error \(\mathbb{E}[(s[n] - \hat{s}[n])^2]\) when the clean signal power spectrum \(S_{ss}(\omega)\) and uncorrelated noise spectrum \(S_{vv}(\omega)\) are known and stationary. The frequency-domain solution is remarkably intuitive, shrinking each frequency bin according to its local signal-to-noise ratio \(\text{SNR}(\omega) = S_{ss}(\omega) / S_{vv}(\omega)\).

\[W(\omega) = \frac{S_{ss}(\omega)}{S_{ss}(\omega) + S_{vv}(\omega)} = \frac{\text{SNR}(\omega)}{1 + \text{SNR}(\omega)}\]
  • Where clean signal towers over noise (\(\text{SNR} \gg 1\)), \(W(\omega) \approx 1\) lets the frequency glide through cleanly. Where noise dominates (\(\text{SNR} \ll 1\)), \(W(\omega) \to 0\) gently turns that bin down, achieving the lowest possible linear reconstruction error.

  • Adaptive filtering and the Least Mean Squares (LMS) algorithm. Now imagine a trickier world where the noise path mutates from second to second, someone shifts chairs during a video call, changing room echoes, or a runner's smartwatch strap slips slightly mid-stride. Any fixed Wiener filter goes stale immediately.

  • Suppose you have two microphones (or two sensors), a primary sensor \(d[n] = s[n] + v[n]\) capturing the clean signal plus correlated interference, and a reference sensor \(x[n]\) listening cleanly to the noise source (for example, your laptop's own loudspeaker stream or a wrist accelerometer). Feed the recent \(M\) reference samples \(\mathbf{x}[n] = [x[n], x[n-1], \dots, x[n-M+1]]^\top\) into an adaptive \(M\)-tap FIR filter \(\mathbf{w}[n]\) to predict the interference \(\hat{y}[n] = \mathbf{w}[n]^\top \mathbf{x}[n]\), and subtract it from the primary signal to form the residual \(e[n] = d[n] - \hat{y}[n]\).

  • Minimising the instantaneous squared error \(\mathcal{L}[n] = \frac{1}{2} e[n]^2\) with respect to the filter taps yields gradient \(\nabla_{\mathbf{w}} \mathcal{L}[n] = -e[n] \mathbf{x}[n]\). Stepping opposite that gradient produces Bernard Widrow and Ted Hoff's celebrated Least Mean Squares (LMS) update rule (1960).

\[\mathbf{w}[n + 1] = \mathbf{w}[n] + \mu \, e[n] \, \mathbf{x}[n]\]
  • Take a moment to admire that equation! LMS is literally online Stochastic Gradient Descent (chapter 06) operating one sample at a time on a linear FIR neuron, invented decades before modern deep learning! In practice, dividing the step size by instantaneous input power produces Normalised LMS (NLMS), \(\mathbf{w}[n+1] = \mathbf{w}[n] + \frac{\mu}{\|\mathbf{x}[n]\|_2^2 + \epsilon} e[n] \mathbf{x}[n]\), keeping convergence rock-steady whether the reference signal whispers or shouts. Choosing \(0 < \mu < 2 / \lambda_{\max}(\mathbf{R}_{xx})\) guarantees convergence in the mean, trading brisk tracking speed against steady-state tap jitter.

Adaptive LMS noise cancellation loop subtracting a filtered reference signal and updating filter weights online from the residual error

  • Because the clean signal \(s[n]\) is uncorrelated with the reference \(x[n]\), LMS cannot predict \(s[n]\) and settles right onto the hidden physical coupling path that produced \(v[n]\), leaving clean \(e[n] \approx s[n]\) behind! That simple feedback loop silently powers acoustic echo cancellation on every video call, active noise-cancelling headphones in chapter 10, and wearable motion-artefact cancellation in chapter 24 (where wrist accelerometer readings strip violent jogging bounces out of optical heart-rate traces in real time).

Bridging to State-Space Filtering and the Chapters Ahead

  • What if the signal we wish to track is not just a stationary spectrum, yet instead obeys known physical equations of motion (like an autonomous rover's position and velocity, or a smoothly drifting latent neural state)? Rudolf Kalman generalised Wiener's frequency-domain framework into recursive state-space estimation. At every tick, the Kalman filter predicts the next hidden state from physics, measures the noisy sensor residual (innovation), and blends prediction with measurement using the optimal variance-minimising Kalman gain (connecting Gaussian conditioning in chapter 05 to robotics localisation in chapter 14).

  • Stepping back at the end of chapter 09, notice how cleanly signal processing links mathematics to every sensory AI chapter ahead. Chapter 10 (Audio and Speech) builds directly on STFT spectrograms, overlap-add synthesis, mel filterbanks, biquad equalisers, and adaptive echo cancellation. Chapter 12 (NeuroAI) uses linear-phase band-pass filters, Morlet wavelets, and Hilbert phase-amplitude envelopes to decode cortical brain rhythms. Chapter 24 (BioAI) combines notch hum filters, wavelet spike denoising, and accelerometer-guided LMS cancellation to turn noisy wearable and hospital biosensors into trustworthy medical data. Whenever raw physical waves enter an intelligent machine, these tools stand right at the doorway.

Take-Home

  • Frequency-selective filters (low-pass, high-pass, band-pass, and notch) shape spectra via complex gain \(H(e^{j\omega})\), while constant group delay (\(\tau_g(\omega) = -d\phi/d\omega\)) keeps sharp waveforms undistorted.
  • Factoring the \(z\)-transform transfer function \(H(z)\) onto the complex unit circle gives instant geometric intuition, zeros pull nearby frequency gain down to zero, poles push gain upward into resonant peaks, and every pole must stay strictly inside \(|z| < 1\) for BIBO stability.
  • FIR filters (such as windowed-sinc designs) guarantee unconditional stability and exact linear phase at higher tap counts, whereas IIR filters (Butterworth, Chebyshev, and biquad cascades) achieve steep roll-offs with minimal taps and latency at the cost of nonlinear phase.
  • Wiener filtering achieves minimum mean squared error linear denoising for stationary spectra by scaling each frequency bin by \(\text{SNR}(\omega) / (1 + \text{SNR}(\omega))\).
  • The adaptive LMS algorithm (\(\mathbf{w}[n+1] = \mathbf{w}[n] + \mu e[n] \mathbf{x}[n]\)) applies online stochastic gradient descent sample by sample to track shifting interference paths in echo cancellers, active noise control, and wearable biosensors.

Coding Tasks (use CoLab or notebook)

  1. Design a second-order pole-zero \(60\,\text{Hz}\) notch filter directly on the complex \(z\)-plane unit circle. Place conjugate zeros right on \(|z| = 1\) at \(60\,\text{Hz}\) and matching poles at radii \(r \in \{0.72, 0.90, 0.97\}\), visualise the pole-zero map and magnitude response across radii, and run the recursive difference equation to strip mains hum from a \(10\,\text{Hz}\) biological signal.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    fs = 500.0
    f_notch = 60.0
    w0 = 2.0 * jnp.pi * f_notch / fs
    
    # Evaluate H(exp(jw)) directly from pole-zero coefficients for three pole radii
    w_grid = jnp.linspace(0.0, jnp.pi, 600)
    freqs_hz = w_grid * fs / (2.0 * jnp.pi)
    z = jnp.exp(1j * w_grid)
    
    radii = [0.72, 0.90, 0.97]
    colours = ["#f39c12", "#3498db", "#9b59b6"]
    
    def notch_coeffs(w0_rad, r):
        c = jnp.cos(w0_rad)
        # Normalise gain so DC (z = 1) has exact unity magnitude
        g = (1.0 - 2.0 * r * c + r ** 2) / (2.0 - 2.0 * c)
        b = g * jnp.array([1.0, -2.0 * c, 1.0])
        a = jnp.array([1.0, -2.0 * r * c, r ** 2])
        return b, a
    
    # Generate a clean 10 Hz alpha rhythm corrupted by strong 60 Hz power-line hum
    t = jnp.arange(0, 1.0, 1.0 / fs)
    s_clean = jnp.sin(2.0 * jnp.pi * 10.0 * t)
    x_hum = s_clean + 0.95 * jnp.sin(2.0 * jnp.pi * f_notch * t)
    
    # Apply sharp r = 0.97 IIR notch difference equation sample by sample (pure Python list)
    b_sharp, a_sharp = notch_coeffs(w0, 0.97)
    b0, b1, b2 = [float(v) for v in b_sharp]
    a1, a2 = float(a_sharp[1]), float(a_sharp[2])
    x_list = [float(v) for v in x_hum]
    y_list = []
    for n in range(len(x_list)):
        xn = x_list[n]
        xn1 = x_list[n - 1] if n >= 1 else 0.0
        xn2 = x_list[n - 2] if n >= 2 else 0.0
        yn1 = y_list[n - 1] if n >= 1 else 0.0
        yn2 = y_list[n - 2] if n >= 2 else 0.0
        y_list.append(b0 * xn + b1 * xn1 + b2 * xn2 - a1 * yn1 - a2 * yn2)
    y_clean = jnp.array(y_list)
    
    err_before = float(jnp.sqrt(jnp.mean((x_hum[150:] - s_clean[150:]) ** 2)))
    err_after = float(jnp.sqrt(jnp.mean((y_clean[150:] - s_clean[150:]) ** 2)))
    print(f"Steady-state RMSE vs clean 10 Hz wave -> Before notch: {err_before:.3f} | After notch: {err_after:.4f}")
    
    fig, axes = plt.subplots(1, 3, figsize=(13.2, 3.8))
    # Panel 1: Unit circle pole-zero plot
    theta = jnp.linspace(0.0, 2.0 * jnp.pi, 300)
    axes[0].plot(jnp.cos(theta), jnp.sin(theta), color="#27ae60", ls="--", lw=1.4, label="Unit Circle |z|=1")
    axes[0].scatter([jnp.cos(w0), jnp.cos(w0)], [jnp.sin(w0), -jnp.sin(w0)], s=70, facecolors="none", edgecolors="#e74c3c", lw=2.0, label="Zeros (r=1)")
    for r, col in zip(radii, colours):
        axes[0].scatter([r * jnp.cos(w0), r * jnp.cos(w0)], [r * jnp.sin(w0), -r * jnp.sin(w0)], marker="x", s=60, color=col, lw=2.0, label=f"Poles (r={r})")
    axes[0].set_aspect("equal"); axes[0].set_xlim(-1.25, 1.25); axes[0].set_ylim(-1.25, 1.25)
    axes[0].set_title("z-Plane Pole-Zero Map"); axes[0].set_xlabel("Re(z)"); axes[0].set_ylabel("Im(z)")
    axes[0].grid(alpha=0.3); axes[0].legend(fontsize=7.5)
    
    # Panel 2: Magnitude frequency responses
    for r, col in zip(radii, colours):
        b, a = notch_coeffs(w0, r)
        H = (b[0] + b[1] * z ** (-1) + b[2] * z ** (-2)) / (1.0 + a[1] * z ** (-1) + a[2] * z ** (-2))
        axes[1].plot(freqs_hz, jnp.abs(H), color=col, lw=2.0, label=f"r = {r}")
    axes[1].axvline(f_notch, color="#e74c3c", ls=":", lw=1.2)
    axes[1].set_xlim(0, 150); axes[1].set_title("Notch Magnitude Response |H(exp(jw))|")
    axes[1].set_xlabel("Frequency (Hz)"); axes[1].set_ylabel("Gain"); axes[1].legend(); axes[1].grid(alpha=0.3)
    
    # Panel 3: Time-domain 60 Hz hum removal
    sl = slice(200, 420)
    axes[2].plot(t[sl], x_hum[sl], color="#95a5a6", lw=1.1, label="10 Hz + 60 Hz Hum")
    axes[2].plot(t[sl], y_clean[sl], color="#27ae60", lw=2.0, label="Notch Output (r=0.97)")
    axes[2].plot(t[sl], s_clean[sl], color="#333", lw=1.1, ls="--", label="Clean 10 Hz Truth")
    axes[2].set_title("Mains Hum Removal"); axes[2].set_xlabel("Time (s)"); axes[2].legend(fontsize=8); axes[2].grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  2. Compare exact linear-phase windowed-sinc FIR against a second-order Butterworth IIR biquad on a sharp rectangular pulse (showing symmetric pulse preservation versus causal phase ringing), then implement a frequency-domain Wiener filter \(W(\omega) = S_{ss} / (S_{ss} + S_{vv})\) to rescue a multi-tone signal buried in coloured noise.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Part A: FIR linear phase vs IIR biquad phase distortion on a square pulse
    N_pulse = 220
    pulse = jnp.where((jnp.arange(N_pulse) >= 60) & (jnp.arange(N_pulse) < 130), 1.0, 0.0)
    
    # 41-tap symmetric windowed-sinc FIR low-pass (fc = 0.08 * fs)
    M_taps, fc = 41, 0.08
    n_idx = jnp.arange(M_taps)
    mid = (M_taps - 1) / 2.0
    h_sinc = jnp.where(n_idx == mid, 2.0 * fc, jnp.sin(2.0 * jnp.pi * fc * (n_idx - mid)) / (jnp.pi * (n_idx - mid)))
    h_fir = h_sinc * (0.54 - 0.46 * jnp.cos(2.0 * jnp.pi * n_idx / (M_taps - 1)))
    h_fir = h_fir / jnp.sum(h_fir)
    y_fir = jnp.convolve(pulse, h_fir, mode="same")  # Zero-aligned symmetric linear phase
    
    # 2nd-order Butterworth IIR biquad at exact same cutoff fc = 0.08 via bilinear transform
    K = float(jnp.tan(jnp.pi * fc))
    norm = 1.0 / (1.0 + float(jnp.sqrt(2.0)) * K + K * K)
    b0, b1, b2 = K * K * norm, 2.0 * K * K * norm, K * K * norm
    a1, a2 = 2.0 * (K * K - 1.0) * norm, (1.0 - float(jnp.sqrt(2.0)) * K + K * K) * norm
    
    p_list = [float(v) for v in pulse]
    y_iir_list = []
    for n in range(N_pulse):
        x0 = p_list[n]
        x1 = p_list[n - 1] if n >= 1 else 0.0
        x2 = p_list[n - 2] if n >= 2 else 0.0
        y1 = y_iir_list[n - 1] if n >= 1 else 0.0
        y2 = y_iir_list[n - 2] if n >= 2 else 0.0
        y_iir_list.append(b0 * x0 + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2)
    y_iir = jnp.array(y_iir_list)
    
    # Part B: Frequency-domain Wiener filter on multi-tone signal in strong coloured noise
    key = jax.random.PRNGKey(21)
    fs, N = 512.0, 512
    t = jnp.arange(N) / fs
    s_true = 0.9 * jnp.sin(2.0 * jnp.pi * 14.0 * t) + 0.6 * jnp.sin(2.0 * jnp.pi * 42.0 * t)
    # Coloured noise concentrated in mid-to-high frequencies
    raw_noise = jax.random.normal(key, shape=(N,))
    N_fft = jnp.fft.rfft(raw_noise)
    freqs = jnp.fft.rfftfreq(N, d=1.0 / fs)
    noise_shape = 0.35 + 1.4 * (freqs / (fs / 2.0))
    v_col = jnp.fft.irfft(N_fft * noise_shape, n=N)
    x_obs = s_true + v_col
    
    # Wiener gain W(w) = S_ss / (S_ss + S_vv)
    S_ss = jnp.abs(jnp.fft.rfft(s_true)) ** 2
    S_vv = (noise_shape ** 2) * N  # Expected PSD of coloured unit-variance Gaussian noise
    W_wiener = S_ss / (S_ss + S_vv + 1e-8)
    s_wiener = jnp.fft.irfft(jnp.fft.rfft(x_obs) * W_wiener, n=N)
    
    def calc_snr(clean, est):
        return float(10.0 * jnp.log10(jnp.sum(clean ** 2) / jnp.maximum(jnp.sum((clean - est) ** 2), 1e-10)))
    
    print(f"IIR causal overshoot peak: {float(jnp.max(y_iir)):.3f} vs FIR symmetric peak: {float(jnp.max(y_fir)):.3f}")
    print(f"Wiener Denoising SNR -> Observed: {calc_snr(s_true, x_obs):.2f} dB | Wiener Output: {calc_snr(s_true, s_wiener):.2f} dB")
    
    fig, axes = plt.subplots(1, 2, figsize=(12.2, 3.8))
    axes[0].plot(pulse, color="#333", lw=1.2, ls="--", label="Original Square Pulse")
    axes[0].plot(y_fir, color="#27ae60", lw=2.1, label="FIR 41-tap (Symmetric Linear Phase)")
    axes[0].plot(y_iir, color="#e74c3c", lw=2.0, label="IIR Biquad (Nonlinear Phase Ringing)")
    axes[0].set_xlim(35, 165); axes[0].set_title("FIR Linear Phase vs IIR Biquad Ringing")
    axes[0].set_xlabel("Sample n"); axes[0].set_ylabel("Amplitude"); axes[0].legend(fontsize=8); axes[0].grid(alpha=0.3)
    
    sl = slice(0, 160)
    axes[1].plot(t[sl], x_obs[sl], color="#95a5a6", lw=1.0, label=f"Noisy ({calc_snr(s_true, x_obs):.1f} dB)")
    axes[1].plot(t[sl], s_wiener[sl], color="#3498db", lw=2.1, label=f"Wiener ({calc_snr(s_true, s_wiener):.1f} dB)")
    axes[1].plot(t[sl], s_true[sl], color="#333", lw=1.2, ls="--", label="Clean Multi-Tone")
    axes[1].set_title("Frequency-Domain Wiener Optimal Denoising")
    axes[1].set_xlabel("Time (s)"); axes[1].set_ylabel("Amplitude"); axes[1].legend(fontsize=8); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  3. Build a real-time Normalised LMS (NLMS) adaptive motion-artefact canceller for a wearable smartwatch heart-rate sensor (bridging directly to chapter 24). Simulate an optical PPG heartbeat drowned out by jogging motion transmitted through an unknown skin-coupling path that shifts abruptly halfway through the run, and watch the online NLMS weights track and recover the clean heartbeat.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(33)
    k1, k2 = jax.random.split(key)
    
    fs = 100.0
    T_sec = 12.0
    N = int(fs * T_sec)
    t = jnp.arange(N) / fs
    
    # Clean optical PPG heartbeat (1.25 Hz fundamental + dicrotic notch harmonic)
    s_ppg = 0.85 * jnp.sin(2.0 * jnp.pi * 1.25 * t) + 0.35 * jnp.sin(2.0 * jnp.pi * 2.50 * t + 0.6)
    
    # Wrist accelerometer reference signal (2.6 Hz jogging stride + broadband bounce)
    x_accel = 1.6 * jnp.sin(2.0 * jnp.pi * 2.6 * t) + 0.8 * jax.random.normal(k1, shape=(N,))
    
    # Unknown hidden skin-coupling impulse response changes abruptly at t = 6.0 s (strap slip!)
    M = 10
    h_path1 = jnp.array([0.55, -0.35, 0.28, -0.18, 0.12, -0.07, 0.04, -0.02, 0.01, 0.0])
    h_path2 = jnp.array([-0.40, 0.50, -0.30, 0.22, -0.14, 0.09, -0.05, 0.03, -0.01, 0.0])
    
    v1 = jnp.convolve(x_accel, h_path1, mode="full")[:N]
    v2 = jnp.convolve(x_accel, h_path2, mode="full")[:N]
    v_motion = jnp.where(t < 6.0, v1, v2)
    d_primary = s_ppg + v_motion + 0.06 * jax.random.normal(k2, shape=(N,))
    
    # Online sample-by-sample NLMS adaptive canceller (pure JAX vectors + Python list log)
    mu = 0.22
    w = jnp.zeros(M)
    x_pad = jnp.concatenate([jnp.zeros(M - 1), x_accel])
    e_list, mse_list = [], []
    
    for n in range(N):
        x_vec = x_pad[n : n + M][::-1]
        y_hat = jnp.dot(w, x_vec)
        e = d_primary[n] - y_hat
        step = mu / (jnp.dot(x_vec, x_vec) + 1e-3)
        w = w + step * e * x_vec
        e_list.append(e)
        mse_list.append((e - s_ppg[n]) ** 2)
    
    e_clean = jnp.stack(e_list)
    err_sq = jnp.stack(mse_list)
    smooth_err = jnp.convolve(err_sq, jnp.ones(35) / 35.0, mode="same")
    
    # Compare raw PPG vs NLMS-recovered PPG after initial adaptation and after mid-run slip
    sl_late = slice(800, N)
    corr_raw = float(jnp.corrcoef(s_ppg[sl_late], d_primary[sl_late])[0, 1])
    corr_nlms = float(jnp.corrcoef(s_ppg[sl_late], e_clean[sl_late])[0, 1])
    print(f"Heartbeat correlation (t > 8 s) -> Raw Corrupted PPG: {corr_raw:.3f} | NLMS Cancelled: {corr_nlms:.3f}")
    
    fig, axes = plt.subplots(1, 3, figsize=(13.4, 3.7))
    zoom = slice(850, 1150)
    axes[0].plot(t[zoom], d_primary[zoom], color="#e74c3c", lw=1.2, label="Corrupted PPG Sensor")
    axes[0].plot(t[zoom], s_ppg[zoom], color="#333", lw=1.4, ls="--", label="Hidden Clean Heartbeat")
    axes[0].set_title(f"Primary Sensor (r = {corr_raw:.2f})"); axes[0].set_xlabel("Time (s)"); axes[0].legend(fontsize=8); axes[0].grid(alpha=0.3)
    
    axes[1].plot(t[zoom], e_clean[zoom], color="#27ae60", lw=2.0, label="NLMS Output e[n]")
    axes[1].plot(t[zoom], s_ppg[zoom], color="#333", lw=1.3, ls="--", label="True Heartbeat")
    axes[1].set_title(f"NLMS Recovered Heartbeat (r = {corr_nlms:.2f})"); axes[1].set_xlabel("Time (s)"); axes[1].legend(fontsize=8); axes[1].grid(alpha=0.3)
    
    axes[2].semilogy(t, smooth_err + 1e-5, color="#3498db", lw=2.0, label="Smoothed (e - s)^2")
    axes[2].axvline(6.0, color="#f39c12", ls="--", lw=1.6, label="Strap Slip at 6 s")
    axes[2].set_title("NLMS Learning & Re-Adaptation Curve"); axes[2].set_xlabel("Time (s)"); axes[2].set_ylabel("Error Power (log)")
    axes[2].legend(fontsize=8); axes[2].grid(alpha=0.3)
    plt.tight_layout(); plt.show()