Skip to content

Commit 33bfc3e

Browse files
feat: add wavelets (#212)
* add wavelets * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent e2de49a commit 33bfc3e

12 files changed

Lines changed: 624 additions & 187 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
1616

1717
| Category | Description |
1818
|--------------------------------------------------------------------|----------------------------------------------------------------------|
19-
| [Analysis](doc/analysis/README.md) | FFT, Real-Input FFT (RFFT), Power Spectral Density, DCT, Window Functions, Signal Detectors, Convolution & Correlation, Goertzel Algorithm, Decibels, Hilbert Transform / Analytic Signal |
19+
| [Analysis](doc/analysis/README.md) | FFT, Real-Input FFT (RFFT), Power Spectral Density, DCT, Discrete Wavelet Transform (Haar/Daubechies), Window Functions, Signal Detectors, Convolution & Correlation, Goertzel Algorithm, Decibels, Hilbert Transform / Analytic Signal |
2020
| [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus, Controllability/Observability Matrices & Gramians, Continuous-to-Discrete, Transfer Function ↔ State Space |
2121
| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, LQI (Integral/Servo State Feedback), MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller, Lead-Lag Compensator, Luenberger Observer |
2222
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |

ROADMAP.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ Difficulty legend:
2727

2828
| # | Component | Target module | Difficulty |
2929
|----|------------------------------------------------------|---------------------------|------------|
30-
| 38 | Discrete Wavelet Transform (Haar / Daubechies) | `analysis` | ★★★★☆ |
3130
| 39 | Square-root / Information Kalman filter | `filters/active` | ★★★★☆ |
3231
| 40 | Feedback linearization | `nonlinear_control` (new) | ★★★★☆ |
3332
| 41 | Backstepping controller | `nonlinear_control` (new) | ★★★★☆ |
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
# Discrete Wavelet Transform (Haar / Daubechies)
2+
3+
## Overview & Motivation
4+
5+
The Discrete Wavelet Transform (DWT) decomposes a finite-length signal into a hierarchy of
6+
approximation and detail coefficients at multiple scales. Unlike the DFT, which projects onto
7+
infinitely-supported sinusoids, wavelets are compactly supported: they are simultaneously
8+
localised in time and frequency. This dual localisation makes the DWT the canonical tool for
9+
detecting transients, edges, and non-stationary features — phenomena that a pure frequency
10+
representation blurs across the entire spectrum.
11+
12+
In embedded condition-monitoring and edge-ML pipelines, the DWT is valued for three properties:
13+
its $O(N)$ complexity (a factor of $\log_2 N$ faster than the FFT), its ability to concentrate
14+
signal energy in very few coefficients (sparsity), and the perfect-reconstruction guarantee that
15+
lets processed coefficients be inverted exactly.
16+
17+
## Mathematical Theory
18+
19+
### Quadrature-Mirror Filter Bank
20+
21+
A single DWT stage passes a length-$N$ sequence $x[n]$ through two complementary finite-impulse-
22+
response filters, then downsamples each output by two.
23+
24+
$$
25+
c_A[i] = \sum_{k=0}^{P-1} h[k]\, x[2i + k \bmod N], \qquad
26+
c_D[i] = \sum_{k=0}^{P-1} g[k]\, x[2i + k \bmod N], \qquad i = 0,\ldots,\tfrac{N}{2}-1
27+
$$
28+
29+
where $h$ is the scaling (low-pass) filter with $P$ taps and $g$ is the wavelet (high-pass) filter.
30+
For an orthogonal wavelet the two filters satisfy the **quadrature-mirror** relation:
31+
32+
$$g[k] = (-1)^k\, h[P - 1 - k]$$
33+
34+
This guarantees that the two sub-bands together cover the full bandwidth without overlap or gap.
35+
36+
### Multilevel Decomposition (Mallat's Algorithm)
37+
38+
The approximation $c_A$ is fed back into the same filter pair. After $L$ levels the coefficient
39+
array contains $L$ detail bands and one coarse approximation:
40+
41+
$$
42+
\text{coeffs} = [\underbrace{c_D^{(1)}}_{N/2},\; \underbrace{c_D^{(2)}}_{N/4},\; \ldots,\; \underbrace{c_D^{(L)}}_{N/2^L},\; \underbrace{c_A^{(L)}}_{N/2^L}]
43+
$$
44+
45+
The layout is critical: level $\ell$ detail starts at offset $\sum_{j=1}^{\ell-1} N/2^j$ within
46+
the coefficient buffer, and the final approximation occupies the last $N/2^L$ positions.
47+
48+
### Perfect Reconstruction
49+
50+
The synthesis (inverse) stage upsamples each sub-band by two and applies the dual filter pair
51+
$(h_r, g_r)$. For orthogonal wavelets the synthesis filters are time-reversals of the analysis
52+
filters:
53+
54+
$$h_r[k] = h[P - 1 - k], \qquad g_r[k] = g[P - 1 - k]$$
55+
56+
Combined, analysis and synthesis satisfy $H(z)H_r(z^{-1}) + G(z)G_r(z^{-1}) = 2$, the
57+
alias-cancellation and distortion-free conditions, giving exact reconstruction:
58+
59+
$$\hat{x}[n] = x[n]$$
60+
61+
to floating-point rounding.
62+
63+
### Parseval Identity (Energy Preservation)
64+
65+
For an orthogonal wavelet the DWT is a unitary transform:
66+
67+
$$\sum_{n=0}^{N-1} x[n]^2 = \sum_{n=0}^{N-1} c[n]^2$$
68+
69+
where $c$ contains all detail and approximation coefficients.
70+
71+
### Wavelet Families
72+
73+
**Haar** ($P = 2$): $h = [1,\, 1]/\sqrt{2}$. Piecewise-constant basis; discontinuous; simplest
74+
possible.
75+
76+
**Daubechies-2** ($P = 4$, denoted db2 or D4): coefficients chosen so the wavelet has two
77+
vanishing moments — it annihilates linear trends. This produces smoother reconstructions and
78+
better energy compaction for smooth signals.
79+
80+
## Complexity Analysis
81+
82+
| Case | Time | Space | Notes |
83+
|---------|--------|--------|----------------------------------------------|
84+
| Forward | $O(N)$ | $O(N)$ | Geometric series: $N + N/2 + \cdots \leq 2N$ |
85+
| Inverse | $O(N)$ | $O(N)$ | Identical pass through synthesis bank |
86+
87+
Memory is one length-$N$ coefficient buffer, two length-$N/2$ working arrays, and the static
88+
filter table of size $P$ — no heap allocation.
89+
90+
## Step-by-Step Walkthrough
91+
92+
Input: $x = [1, 2, 3, 4]$, Haar wavelet, $L = 1$.
93+
94+
**Stage 1 (analysis):**
95+
96+
| $i$ | $2i$ | $2i+1$ | $c_A[i] = (x[2i]+x[2i+1])/\sqrt{2}$ | $c_D[i] = (x[2i]-x[2i+1])/\sqrt{2}$ |
97+
|-----|------|--------|-------------------------------------|-------------------------------------|
98+
| 0 | 0 | 1 | $(1+2)/\sqrt{2} \approx 2.121$ | $(1-2)/\sqrt{2} \approx -0.707$ |
99+
| 1 | 2 | 3 | $(3+4)/\sqrt{2} \approx 4.950$ | $(3-4)/\sqrt{2} \approx -0.707$ |
100+
101+
**Coefficient buffer** (layout detail | approx):
102+
103+
$$\text{coeffs} = [-0.707,\; -0.707,\; 2.121,\; 4.950]$$
104+
105+
**Reconstruction:** upsample $c_A$ and $c_D$, apply synthesis filters, add:
106+
107+
$$\hat{x} = [1.0,\; 2.0,\; 3.0,\; 4.0] \checkmark$$
108+
109+
## Pitfalls & Edge Cases
110+
111+
- **$N$ must be divisible by $2^L$.** Odd-length or non-aligned signals at deeper levels produce
112+
fractional half-lengths and are rejected by design.
113+
- **Boundary handling must match.** Periodic (modulo) extension is used for both analysis and
114+
synthesis; mixing it with symmetric extension on the other pass destroys perfect reconstruction.
115+
- **Filter length vs. signal length.** At each level the signal halves; once it equals $P$ the
116+
periodic convolution wraps completely. Stop decomposition before the signal shorter than the
117+
filter length to avoid artefacts.
118+
- **Fast-math reordering.** With `#pragma GCC optimize("fast-math")` floating-point associativity
119+
relaxes; reconstruction residuals may reach $10^{-5}$ rather than $10^{-7}$ for 32-bit floats.
120+
121+
## Variants & Generalizations
122+
123+
- **Daubechies-$N$ family**: increasing tap count adds vanishing moments, improving energy
124+
compaction for smooth signals at the cost of longer filters and larger boundary effects.
125+
- **Biorthogonal wavelets** (e.g. CDF 9/7 used in JPEG 2000): analysis and synthesis filters
126+
differ but still give perfect reconstruction; not orthogonal, so Parseval does not hold.
127+
- **Wavelet packet transform**: decomposes both approximation and detail sub-bands at every level,
128+
forming a full binary tree of sub-bands for adaptive best-basis selection.
129+
- **Undecimated (stationary) DWT**: omits downsampling; translation-invariant but $O(N \log N)$.
130+
131+
## Applications
132+
133+
- **Denoising**: threshold small detail coefficients (hard or soft thresholding); edges and
134+
transients survive while broadband noise is suppressed.
135+
- **Compression**: retain the few large coefficients; the rest encode to zero-runs.
136+
- **Feature extraction for edge-ML**: wavelet energy per sub-band is a compact descriptor for
137+
vibration, ECG, or acoustic signals.
138+
- **Multi-rate filtering**: each level is a critically sampled octave-band filter, useful for
139+
hearing-aid and audio-codec pipelines.
140+
141+
## Connections to Other Algorithms
142+
143+
- **ConvolutionCorrelation**: the inner analysis/synthesis loops are FIR convolutions; the same
144+
periodic-indexing trick is used.
145+
- **FastFourierTransform / RealFastFourierTransform**: alternative time-frequency view; the DWT
146+
trades uniform frequency resolution for logarithmic-scale (dyadic) resolution.
147+
- **PowerDensitySpectrum**: Welch's method is an FFT-based power estimator; the DWT gives a
148+
non-uniform octave-band equivalent.
149+
- **DiscreteCosineTransform**: a block transform (fixed basis); the DWT is a multi-scale
150+
transform (variable support).
151+
152+
## References & Further Reading
153+
154+
- S. Mallat, "A Theory for Multiresolution Signal Decomposition: The Wavelet Representation,"
155+
*IEEE Trans. Pattern Analysis and Machine Intelligence*, 11(7), 674–693, 1989.
156+
- I. Daubechies, *Ten Lectures on Wavelets*, SIAM, 1992.
157+
- G. Strang and T. Nguyen, *Wavelets and Filter Banks*, Wellesley-Cambridge Press, 1996.
158+
- A. V. Oppenheim and R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Ch. 11, 2010.

doc/analysis/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Signal analysis algorithms for frequency-domain decomposition and spectral estim
1313
| [Signal Detectors](SignalDetectors.md) | Peak hold, zero-crossing counter, and RMS envelope detectors for real-time signal monitoring |
1414
| [Decibels](Decibels.md) | `ToDecibels` / `FromDecibels` conversion helpers with zero-floor guard, plus attenuation and ripple utilities |
1515
| [Goertzel Algorithm](GoertzelAlgorithm.md) | Single-bin DFT via a second-order recurrence for O(N) tone detection with O(1) memory |
16+
| [Discrete Wavelet Transform](DiscreteWaveletTransform.md) | Multilevel Haar / Daubechies filter bank for O(N) time-frequency decomposition with perfect reconstruction |
1617
| [Hilbert Transform](HilbertTransform.md) | Analytic signal and instantaneous amplitude/phase/frequency via FFT one-sided spectrum or FIR approximation |
1718

1819
## Sub-domains

numerical/analysis/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ target_sources(numerical.analysis PRIVATE
1515
ConvolutionCorrelation.hpp
1616
Decibels.hpp
1717
DiscreteCosineTransform.hpp
18+
DiscreteWaveletTransform.hpp
1819
FastFourierTransform.hpp
1920
FastFourierTransformRadix2Impl.hpp
2021
GoertzelAlgorithm.hpp
@@ -27,6 +28,7 @@ target_sources(numerical.analysis PRIVATE
2728
numerical_add_coverage_sources(numerical.analysis
2829
ConvolutionCorrelation.cpp
2930
DiscreteCosineTransform.cpp
31+
DiscreteWaveletTransform.cpp
3032
FastFourierTransformRadix2Impl.cpp
3133
GoertzelAlgorithm.cpp
3234
HilbertTransform.cpp
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#include "numerical/analysis/DiscreteWaveletTransform.hpp"
2+
3+
namespace analysis
4+
{
5+
template class WaveletFilters<float, 2>;
6+
template class WaveletFilters<float, 4>;
7+
template class DiscreteWaveletTransform<float, 16, 3, 2>;
8+
template class DiscreteWaveletTransform<float, 16, 3, 4>;
9+
}

0 commit comments

Comments
 (0)