Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Wavelet transforms

ProblemAnalyse a signal at many scales at once, with time resolution that sharpens at high frequencies; compress and denoise signals with localised features
Devised byAlfréd Haar (1910); Jean Morlet and Alex Grossmann (1984), the continuous wavelet transform; Stéphane Mallat (1989), multiresolution analysis and the fast algorithm; Ingrid Daubechies (1988), compactly supported orthogonal wavelets; David Donoho and Iain Johnstone (1994), wavelet shrinkage
AccuracyThe Daubechies filters are orthonormal to , and four-level decompositions reconstruct to (table below)
CostDiscrete transform for filters of length , all levels together; continuous transform per scale
Read firstFIR design: windows, frequency sampling and Parks-McClellan
APIWavelet (Haar, Daubechies(1..=10)), dwt, idwt, wavedec, waverec, max_level, ContinuousWavelet (Morlet, Ricker), continuous_wavelet_transform

Overview

The Fourier transform uses sinusoids that last forever, so it says which frequencies are present but not when. The STFT windows them, with one time-frequency resolution for all frequencies. Wavelets are shifted and stretched copies of one short oscillation, the mother wavelet : narrow at small scales, to locate high-frequency events precisely in time, and wide at large scales, to measure low frequencies precisely. The continuous wavelet transform correlates the signal with wavelets at every scale and shift, for analysis. The discrete wavelet transform, built from a pair of filters and downsampling by two, is an orthogonal change of basis with as many coefficients as samples. It is computed in linear time, and is the basis of JPEG 2000 compression and of wavelet denoising.

Where it is used

Wavelets analyse signals at many scales.

  • Compression. JPEG 2000 and many scientific data compressors use wavelet transforms; the FBI fingerprint standard is wavelet-based.
  • Denoising. Thresholding wavelet coefficients removes noise while keeping sharp features in ECG, seismic and image data.
  • Transient detection. Finding short events (a fault in a power line, a heartbeat anomaly, a seismic arrival).
  • Numerical analysis. Sparse representations of functions with local features.

History

Alfréd Haar (1910) constructed the first orthonormal basis of step functions. Seismologist Jean Morlet and physicist Alex Grossmann (1984) introduced the continuous wavelet transform to analyse seismic echoes, and Yves Meyer found smooth orthonormal wavelets in 1985. Stéphane Mallat (1989) connected wavelets to multiresolution analysis and to the filter banks of signal processing, giving the fast pyramid algorithm. Ingrid Daubechies (1988) constructed the compactly supported orthonormal wavelets with the most vanishing moments for their length, which the library provides. David Donoho and Iain Johnstone (1994) showed that thresholding wavelet coefficients is a nearly optimal denoiser for a wide class of signals.

The idea

Multiresolution and the filter-bank algorithm

The simplest case: Haar. Take a signal two samples at a time, and replace each pair by its scaled sum and difference,

The sums form a version of the signal at half the resolution, a local average. The differences record the detail that the averaging lost. Nothing has been thrown away: the pair is recovered as , . Where the signal is smooth, neighbouring samples are nearly equal and the details are nearly zero. Now repeat the step on the sequence of averages, and again on its averages. The signal ends up described by one overall average and details at successively coarser scales. That is a discrete wavelet transform (DWT), with the Haar wavelet.

The general case. Other wavelets replace the two-point sum and difference by longer filters. An orthogonal wavelet is defined by a scaling filter (low-pass, ) and a wavelet filter (high-pass, its quadrature mirror). One level of the DWT filters the signal with both and keeps every other sample:

For Haar, and , which reproduces the sums and differences above. As before, the approximation is a half-resolution version of the signal and the detail is what was lost. Repeating the step on gives a pyramid of details at coarser and coarser scales. Each level works on half as many samples as the one before, so the total cost is filter steps: the transform is , cheaper even than an FFT.

Invertibility comes from a condition on the filters: they are orthonormal under shifts by two, . This makes the transform an orthogonal matrix, so its inverse is its transpose, energy is preserved, and reconstruction is exact:

Table 15.12. Orthonormality and perfect reconstruction of the wavelet filters.

waveletfilter lengthlargest deviation from orthonormality Σ h[n]h[n+2s] = δ_sreconstruction error after 4 levels
Haar22.2e-161.1e-15
Daubechies 241.4e-171.2e-15
Daubechies 6123.4e-181.3e-15
Daubechies 10202.8e-171.3e-15

Vanishing moments

The Haar details vanish where the signal is constant, since sums to zero. Longer filters can do better. The Daubechies wavelet with vanishing moments, of filter length , satisfies for , which means that its detail coefficients are zero wherever the signal is locally a polynomial of degree below . Smooth stretches of a signal therefore produce small details, and only edges and singularities produce large ones. Signals that are smooth apart from a few jumps become sparse in the wavelet basis, the property behind compression and denoising. Haar is Daubechies with one moment; longer filters give smoother wavelets and more vanishing moments, at more cost and with longer edge effects.

Denoising by thresholding

White noise spreads evenly over all orthonormal coefficients, while a piecewise-smooth signal concentrates in a few large ones. Shrinking every detail coefficient towards zero by a threshold (soft thresholding, ) kills most of the noise and few of the signal’s coefficients. Donoho and Johnstone’s universal threshold is :

Figure 15.13. Wavelet denoising.

wavelet (5 levels, universal soft threshold)RMS error, noisyRMS error, denoised
Haar0.2010.107
Daubechies 40.2010.094
Daubechies 80.2010.098

The error halves while the jumps stay sharp, which a linear low-pass filter cannot achieve: smoothing the noise would also blur the edges.

The continuous wavelet transform

The CWT correlates the signal with scaled wavelets at every shift, . With the complex Morlet wavelet , the scale corresponds to the frequency cycles per sample, and is a scalogram:

Figure 15.14. Morlet scalogram.

Unlike a spectrogram, the resolution varies with frequency. The chirp’s low-frequency start is well resolved in frequency and smeared in time, and the short high-frequency burst is sharp in time and broad in frequency. The Ricker (“Mexican hat”) wavelet, the second derivative of a Gaussian, is real and suits the detection of peaks.

Algorithm

One level of the DWT, for a signal of even length and filters of length . The signal is extended periodically, so indices are taken modulo .

For : and .

One level of the inverse: start with , and for every and add to . This applies the transpose of the forward transform, which is its inverse because the transform is orthogonal.

wavedec (multi-level decomposition):

  1. apply one level to the signal, and store the detail;
  2. apply one level to the approximation just obtained, and store its detail;
  3. continue for the requested number of levels, which cannot exceed max_level, the number of times the length can be halved while staying at least the filter length;
  4. return the final approximation and all the details.

waverec reverses it: starting from the coarsest approximation and detail, apply the inverse level, and repeat with each finer detail in turn.

Denoising, as in the figure above, is a recipe built from these two functions: decompose; apply soft thresholding with to every detail coefficient; reconstruct.

CWT, for a list of scales: for each scale , sample the wavelet out to , and correlate it with the signal by FFT. Each scale gives one row of the scalogram.

Implementation

    let analyse = |f: &[f64]| -> Vec<f64> { (0..n / 2).map(|k| f.iter().enumerate().map(|(i, c)| c * x[(2 * k + i) % n]).sum()).collect() };
    Ok((analyse(&h), analyse(&g)))
  • The signal is extended periodically, so each level needs an even length and the transform is exactly orthogonal; edge coefficients mix the two ends of the signal. (PyWavelets defaults to symmetric extension, which changes the edge coefficients.)
  • The Daubechies filters are stored to double precision for .

In practice

//! Discrete and continuous wavelet transforms.

use lib_jsl_dsp::discrete::spectral::wavelet_transform::{ContinuousWavelet, Wavelet, continuous_wavelet_transform, dwt, idwt, wavedec, waverec};

fn main() {
    let x: Vec<f64> = (0..16).map(|n| if n < 8 { 1.0 } else { 0.0 } + 0.1 * n as f64).collect();
    let (a, d) = dwt(&x, Wavelet::Haar).unwrap();
    println!("Haar approximation {a:.3?}");
    println!("Haar detail        {d:.3?}");
    let back = idwt(&a, &d, Wavelet::Haar).unwrap();
    println!("reconstruction error {:.1e}", back.iter().zip(&x).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max));
    // Daubechies 2 has two vanishing moments: a linear signal leaves no detail (away from the ends).
    let ramp: Vec<f64> = (0..64).map(|n| 3.0 + 0.5 * n as f64).collect();
    let dec = wavedec(&ramp, Wavelet::Daubechies(2), 3).unwrap();
    let interior = &dec.details[2][2..28];
    println!("db2 finest details of a ramp (interior): max |d| = {:.1e}", interior.iter().fold(0.0f64, |m, v| m.max(v.abs())));
    println!("waverec error {:.1e}", waverec(&dec, Wavelet::Daubechies(2)).unwrap().iter().zip(&ramp).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max));
    // A Morlet transform locates a burst in time and frequency.
    let sig: Vec<f64> = (0..512).map(|n| if (200..260).contains(&n) { (2.0 * std::f64::consts::PI * 0.1 * n as f64).sin() } else { 0.0 }).collect();
    let morlet = ContinuousWavelet::Morlet { omega0: 6.0 };
    let freqs = [0.05, 0.1, 0.2];
    let scales: Vec<f64> = freqs.iter().map(|&f| morlet.scale_for_frequency(f)).collect();
    let w = continuous_wavelet_transform(&sig, &scales, morlet).unwrap();
    for (k, f) in freqs.iter().enumerate() {
        let (t, v) = (0..512).map(|t| (t, w[[k, t]].norm())).fold((0, 0.0), |b, c| if c.1 > b.1 { c } else { b });
        println!("|W| at {f} cycles/sample peaks at sample {t} with {v:.2}");
    }
}
Haar approximation [1.485, 1.768, 2.051, 2.333, 1.202, 1.485, 1.768, 2.051]
Haar detail        [-0.071, -0.071, -0.071, -0.071, -0.071, -0.071, -0.071, -0.071]
reconstruction error 4.4e-16
db2 finest details of a ramp (interior): max |d| = 3.6e-15
waverec error 2.1e-14
|W| at 0.05 cycles/sample peaks at sample 260 with 0.36
|W| at 0.1 cycles/sample peaks at sample 230 with 2.90
|W| at 0.2 cycles/sample peaks at sample 260 with 0.25

Haar detail coefficients of a ramp are constant; Daubechies 2, with two vanishing moments, gives zero detail for it away from the wrap-around at the ends. The Morlet transform locates the burst at samples 200–260 in the scale tuned to its frequency.

Strengths

  • Multiscale analysis with time resolution matched to frequency; sparse representations of piecewise-smooth signals.
  • Fast, exactly invertible orthogonal transform; simple nonlinear denoising.

Weaknesses

  • Coefficients depend on the alignment of the signal (the DWT is not shift-invariant) and on the extension at the edges.
  • The choice of wavelet matters, and the CWT is highly redundant.

Exercises

  1. Show that is orthogonal to under all even shifts when is.
  2. Derive the Haar filters from .
  3. Show that the Daubechies-2 wavelet filter annihilates constant and linear sequences.
  4. Show that soft thresholding is the solution of .
  5. Denoise the example signal with hard thresholding ( if , else 0) and compare the error and the visual artefacts.
Hints and answers
  1. Orthogonality conditions on are . Substitute : the sign changes and the reversal make cancel term by term.
  2. satisfies , so after normalisation; the wavelet filter is .
  3. The filter has two vanishing moments: and , so constants and linear ramps give zero output.
  4. For the objective’s derivative is , so if ; symmetrically for ; otherwise the minimum is at 0: .
  5. Hard thresholding keeps large coefficients exactly, so it has lower bias but produces visible discontinuities (spurious oscillations) near jumps that soft thresholding smooths.

Further reading

  • I. Daubechies, Ten Lectures on Wavelets, SIAM, 1992.
  • S. Mallat, A Wavelet Tour of Signal Processing, 3rd ed., Academic Press, 2009.
  • D. L. Donoho and I. M. Johnstone, “Ideal spatial adaptation by wavelet shrinkage”, Biometrika 81 (1994) 425–455.
  • C. Torrence and G. P. Compo, “A practical guide to wavelet analysis”, Bulletin of the American Meteorological Society 79 (1998) 61–78.