Overview
A Fourier transform describes a signal with waves that last for ever, so it says which frequencies are present but not where. A wavelet is a short burst that lives in one place. The discrete wavelet transform slides a pair of small filters along the signal: one takes local averages, giving a half-length coarse version, and the other takes local differences, giving the detail that the averaging lost. Repeat on the coarse version and you get details at each scale, from fine to broad. Smooth stretches produce details near zero and sudden changes produce a few large ones. That makes wavelets good at compression and denoising: keep the large coefficients and drop the rest.
A short history
Alfred Haar described the first wavelet, a simple step function, around 1910. The modern theory began in the early 1980s when Jean Morlet, a geophysicist analysing seismic traces, worked with Alex Grossmann on analysis with short scaled waves. Ingrid Daubechies constructed smooth, compactly supported wavelets in 1988, and Stephane Mallat gave the fast multiresolution algorithm in 1989. The JPEG 2000 image standard is built on wavelets.
How it works
- Choose a wavelet. Haar is the simplest: its filters take the scaled sum and the scaled difference of neighbouring pairs. db2 and db4 use longer, smoother filters.
- Filter the signal with the low-pass filter and keep every second output. This is the approximation, half as long as the input.
- Filter with the high-pass filter and keep every second output. This is the detail, also half as long. The template wraps around at the ends of the signal.
- Apply the same two steps to the approximation, and repeat for the chosen number of levels.
- To denoise, estimate the noise level from the finest details, shrink every detail coefficient toward zero by a threshold, and leave the final approximation alone.
- Invert level by level, from coarsest to finest, to rebuild the signal.
Watch out for
- The signal length must be a multiple of for levels. Other lengths need padding or trimming first.
- The transform wraps the signal around at its ends. If the first and last values differ a lot, that false jump creates large coefficients at the boundary.
- The discrete transform is not shift-invariant. Moving the signal by one sample can change the coefficients a great deal, which matters if they are used as features.
- Soft thresholding reduces every kept coefficient by the threshold, so peaks come out slightly lower. Hard thresholding keeps their height but can leave isolated noise spikes.
- The universal threshold assumes white Gaussian noise of constant level. With correlated noise or noise that changes over time it removes too little or too much.
Use cases
When to use it
Signals with short events or sharp edges on a smooth background, such as ECG spikes, transients and images, and denoising where a low-pass filter would blur the features you want to keep.
In industry
- Image compression
- JPEG 2000, used in digital cinema and medical image archives, codes images with a wavelet transform instead of block cosine transforms.
- Biometrics
- The FBI's fingerprint compression standard, WSQ, stores fingerprint images with wavelet coefficients.
- Biomedical signals
- ECG and EEG analysis uses wavelets to remove noise and to locate short events such as the QRS complex.
- Geophysics
- Seismic processing, where the method began, uses wavelets to separate reflections at different scales.
Choosing it: what must hold
- A signal with brief or localized features, or features at several scales.
- A choice of wavelet family and number of levels suited to the feature shape.
- For the fast discrete transform, a signal length that allows repeated halving, or a padding rule.
- Acceptance that the output is indexed by scale, which maps to frequency only roughly.
When to choose something else
| If | Use instead |
|---|---|
| The signal is steady and you need exact frequencies | Fourier transforms |
| You need a uniform time and frequency grid, for example as input to a speech model | Spectral analysis with the short-time Fourier transform |
| Noise sits in a band clearly separate from the signal | Filtering |
Math foundations
One level of the transform
The approximation and the detail each have entries. The step of 2 in the index is the downsampling, and the modulo makes the signal wrap around at its end.
The high-pass filter from the low-pass
Reverse the low-pass taps and flip every second sign. This pairing, called a quadrature mirror filter, is what makes the two outputs together hold exactly the information of the input.
Haar wavelet
The simplest case, with . Each pair of samples becomes a scaled sum and a scaled difference. A flat pair gives a detail of zero.
Energy is preserved
The transform is orthogonal: a rotation of the signal into new coordinates. Nothing is lost, and noise stays the same size in every coefficient while a smooth signal concentrates into a few.
Noise level and universal threshold
The finest details are mostly noise, and their median absolute value divided by 0.6745 estimates the noise standard deviation robustly. The threshold is about the largest value pure noise is expected to reach among coefficients.
Soft thresholding
Coefficients smaller than become zero and larger ones move toward zero by . The hard version keeps the large ones unchanged.
Ricker wavelet for the continuous transform
The Mexican hat shape used by cwt, scaled to unit energy. Sliding it along the signal at several widths gives a map in which a bump of a given size responds most strongly at the matching width.
Symbols
- the signal, of length
- the approximation and detail coefficients
- the low-pass and high-pass filter taps
- the number of taps: 2 for haar, 4 for db2, 8 for db4
- the number of decomposition levels (level in the config)
- the detail coefficients of the finest level
- the estimated standard deviation of the noise
- the threshold
- the soft-thresholding function
- the Ricker wavelet of width
Worked by hand
Apply one level of the Haar transform to and check that energy is preserved.
The approximation carries 292 of the 296 units of energy in half the samples, and the details are small because neighbours are similar. That concentration is what compression and denoising exploit.
Visual example
Loading the example.
Try this
- Click Detail 1, then drag the threshold from 0 to 1: nearly every coefficient falls inside the dashed lines and is removed.
- Click Detail 3 and find the coefficients that mark the two jumps in the signal.
- Push the threshold to 3 and compare soft with hard thresholding on the jumps.
Code sample
import numpy as np
from impl import Wavelet, cwt
from config import WaveletConfig
t = np.linspace(0, 1, 1024, endpoint=False)
clean = np.sin(2 * np.pi * 3 * t)
noisy = clean + 0.3 * np.random.default_rng(0).normal(size=t.size)
w = Wavelet(WaveletConfig(wavelet="db4", level=4))
coeffs = w.wavedec(noisy) # [approx (64,), detail (64,), (128,), (256,), (512,)]
same = w.waverec(coeffs) # equals noisy
smooth = w.denoise(noisy) # much closer to clean than noisy is
scales = cwt(noisy, [2, 4, 8, 16]) # (4, 1024)Read the implementation (134 lines)
"""Wavelet transforms.
The discrete wavelet transform (DWT) splits a signal into a coarse approximation and details at several scales
using an orthogonal filter pair (Haar, Daubechies 2 or 4) with periodic boundaries, so it is exactly invertible
and preserves energy. On top of it: multi-level decomposition, reconstruction and threshold denoising.
`cwt` is a continuous wavelet transform with the Ricker (Mexican hat) wavelet.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import WaveletConfig
except ImportError: # run from the template's own folder
from config import WaveletConfig
_SQRT3 = math.sqrt(3.0)
_LOWPASS = {
"haar": np.array([1.0, 1.0]) / math.sqrt(2.0),
"db2": np.array([1.0 + _SQRT3, 3.0 + _SQRT3, 3.0 - _SQRT3, 1.0 - _SQRT3]) / (4.0 * math.sqrt(2.0)),
"db4": np.array([0.23037781330885523, 0.7148465705525415, 0.6308807679295904, -0.02798376941698385,
-0.18703481171888114, 0.030841381835986965, 0.032883011666982945, -0.010597401784997278]),
}
def ricker(points: int, width: float) -> np.ndarray:
"""Ricker (Mexican hat) wavelet sampled at `points` positions centred on zero, scaled to unit energy.
width: the scale a; the wavelet is proportional to (1 - (t / a)^2) exp(-t^2 / (2 a^2)). Returns array (points,).
"""
t = np.arange(points) - (points - 1) / 2.0
w = (1.0 - (t / width) ** 2) * np.exp(-0.5 * (t / width) ** 2)
return w / math.sqrt(float(np.sum(w**2)))
def cwt(x, widths) -> np.ndarray:
"""Continuous wavelet transform of x, array (n,), with Ricker wavelets of the given widths.
Returns array (len(widths), n): row i is x correlated with the wavelet of width widths[i]. A feature of
a given size gives its largest response in the row whose width matches it, at the feature's position.
"""
x = np.asarray(x, dtype=float).ravel()
out = np.empty((len(widths), x.size))
for i, width in enumerate(widths):
if width <= 0:
raise ValueError("widths must be positive")
points = int(min(10 * width, x.size))
points -= 1 - points % 2 # odd length keeps the wavelet centred
out[i] = np.convolve(x, ricker(max(points, 1), width), mode="same")
return out
class Wavelet:
"""Orthogonal discrete wavelet transform with periodic boundary handling."""
def __init__(self, config: WaveletConfig | None = None) -> None:
self.config = config or WaveletConfig()
self.lowpass = _LOWPASS[self.config.wavelet].copy()
n = np.arange(self.lowpass.size)
self.highpass = (-1.0) ** n * self.lowpass[::-1] # quadrature mirror of the low-pass filter
def _index(self, half: int) -> np.ndarray:
"""Positions read by each output coefficient: (2 k + n) mod N, array (half, filter length)."""
return (2 * np.arange(half)[:, None] + np.arange(self.lowpass.size)[None, :]) % (2 * half)
def dwt(self, x) -> tuple[np.ndarray, np.ndarray]:
"""One level of the transform. x: array (N,), N even.
Returns (approximation, detail), each array (N // 2,): the low-pass and high-pass filtered signal,
keeping every second sample.
"""
x = np.asarray(x, dtype=float).ravel()
if x.size < 2 or x.size % 2:
raise ValueError("the signal length must be even and at least 2")
windows = x[self._index(x.size // 2)]
return windows @ self.lowpass, windows @ self.highpass
def idwt(self, approx, detail) -> np.ndarray:
"""Inverse of `dwt`: rebuild array (N,) from approximation and detail, each array (N // 2,)."""
approx, detail = np.asarray(approx, dtype=float).ravel(), np.asarray(detail, dtype=float).ravel()
if approx.shape != detail.shape:
raise ValueError("approximation and detail must have the same length")
x = np.zeros(2 * approx.size)
contributions = approx[:, None] * self.lowpass[None, :] + detail[:, None] * self.highpass[None, :]
np.add.at(x, self._index(approx.size), contributions)
return x
def wavedec(self, x) -> list[np.ndarray]:
"""Multi-level decomposition. Returns [approx_L, detail_L, detail_L-1, ..., detail_1], coarsest first.
x: array (N,), N a multiple of 2 ** level. detail_1 holds the finest scale and has N // 2 entries.
"""
x = np.asarray(x, dtype=float).ravel()
if x.size == 0 or x.size % (2**self.config.level):
raise ValueError(f"the signal length must be a multiple of {2 ** self.config.level}")
details = []
approx = x
for _ in range(self.config.level):
approx, detail = self.dwt(approx)
details.append(detail)
return [approx] + details[::-1]
def waverec(self, coeffs) -> np.ndarray:
"""Inverse of `wavedec`: rebuild the signal from [approx_L, detail_L, ..., detail_1]."""
approx = np.asarray(coeffs[0], dtype=float)
for detail in coeffs[1:]:
approx = self.idwt(approx, detail)
return approx
def noise_sigma(self, x) -> float:
"""Robust estimate of the noise standard deviation: median |finest detail coefficient| / 0.6745."""
_, detail = self.dwt(x)
return float(np.median(np.abs(detail)) / 0.6745)
def denoise(self, x, threshold: float | None = None) -> np.ndarray:
"""Remove noise by shrinking small detail coefficients and transforming back.
threshold: coefficients below it are treated as noise. None uses the universal threshold
sigma * sqrt(2 ln N) with sigma from `noise_sigma`. The approximation is left untouched.
Returns array (N,).
"""
x = np.asarray(x, dtype=float).ravel()
coeffs = self.wavedec(x)
if threshold is None:
threshold = self.noise_sigma(x) * math.sqrt(2.0 * math.log(x.size))
shrunk = [coeffs[0]]
for detail in coeffs[1:]:
if self.config.threshold_mode == "soft":
shrunk.append(np.sign(detail) * np.maximum(np.abs(detail) - threshold, 0.0))
else:
shrunk.append(np.where(np.abs(detail) > threshold, detail, 0.0))
return self.waverec(shrunk)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Check Wavelet().dwt([4, 6, 10, 12]) against the worked example and confirm that idwt returns the input. Then build a 1024-sample signal with a slow sine and one sharp step, add Gaussian noise, and call denoise with WaveletConfig(wavelet="db4", level=4). Compare the error with the clean signal against a simple moving average, and look at what each does to the step.
Check on learning
- Why are the finest detail coefficients a good place to estimate the noise level, and when would that estimate be wrong?
A way to think about it
A smooth signal contributes almost nothing at the finest scale, so what remains is mostly noise. Then think of a signal that itself has a lot of fine structure.
- The noise estimate uses a median, not a standard deviation. What does the median protect against?
A way to think about it
A few detail coefficients are large because of real edges in the signal. Ask how much one huge value moves a median compared with a mean of squares.
- Denoising with a low-pass filter blurs a sharp step, while wavelet thresholding keeps it. What in the wavelet representation makes that possible?
A way to think about it
A step produces a few large coefficients at its location at every scale. Large coefficients survive the threshold wherever they occur.
- Shift the worked signal by one sample to . Will the detail coefficients be the same numbers in a different order?
A way to think about it
Work out the new pairs. The transform groups samples in fixed pairs, so a shift changes which neighbours are compared.
- Why does a longer filter such as db4 represent a smooth curve with fewer large coefficients than Haar?
A way to think about it
Haar details vanish only where the signal is locally constant. A wavelet with more vanishing moments also gives zero on straight lines and low-order curves.