Skip to content

Commit 7e72637

Browse files
feat: add lms adaptive filter (#182)
* add lms adaptive filter * 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 d06f6ac commit 7e72637

11 files changed

Lines changed: 500 additions & 164 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
2020
| [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus |
2121
| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, 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 |
23-
| [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Yule-Walker (offline), Recursive Least Squares (online) |
23+
| [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Yule-Walker (offline), Recursive Least Squares, LMS / NLMS Adaptive Filter (online) |
2424
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, Alpha-Beta/Alpha-Beta-Gamma, FIR, IIR, Exponential Moving Average, Moving Average, Complementary, Median Filter, CIC (Cascaded Integrator-Comb), Notch/Comb Filter |
2525
| [Kinematics](doc/kinematics/README.md) | Forward Kinematics |
2626
| [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, model |

‎ROADMAP.md‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ Difficulty legend:
2929
|----|------------------------------------------------------|---------------------------|------------|
3030
| 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ |
3131
| 20 | Integral / servo state feedback (LQI) | `controllers` | ★★★☆☆ |
32-
| 21 | LMS / NLMS adaptive filter | `estimators/online` | ★★★☆☆ |
3332
| 22 | Savitzky-Golay filter | `filters/passive` | ★★★☆☆ |
3433
| 23 | CORDIC | `math` | ★★★☆☆ |
3534
| 24 | Runge-Kutta ODE integrators (RK4 + Dormand-Prince) | `solvers` | ★★★☆☆ |
@@ -165,12 +164,6 @@ Difficulty legend:
165164
- **Algorithm / paper:** B. D. O. Anderson, J. B. Moore, *Optimal Control: Linear Quadratic Methods* (1990).
166165
- **Reuses:** [Lqr.hpp](numerical/controllers/implementations/Lqr.hpp), [DARE](numerical/solvers/DiscreteAlgebraicRiccatiEquation.hpp).
167166

168-
### 21. LMS / NLMS adaptive filter
169-
- **What:** Least-Mean-Squares (and normalized) adaptive FIR with steepest-descent weight update.
170-
- **Embedded value:** Adaptive noise cancellation, echo cancellation, system identification, active vibration control — a DSP staple.
171-
- **Algorithm / paper:** B. Widrow, M. Hoff, "Adaptive switching circuits," *IRE WESCON*, 1960; S. Haykin, *Adaptive Filter Theory*.
172-
- **Reuses:** [RecursiveLeastSquares.hpp](numerical/estimators/online/RecursiveLeastSquares.hpp) patterns, `math::Vector`.
173-
174167
### 22. Savitzky-Golay filter
175168
- **What:** Convolution smoother that fits a local polynomial, preserving peak height/width and giving smoothed derivatives.
176169
- **Embedded value:** Spectroscopy, ECG/PPG, and any signal where peaks matter and moving-average distortion is unacceptable.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# LMS / NLMS Adaptive Filter
2+
3+
## Overview & Motivation
4+
5+
Real-time systems frequently need filters whose characteristics are unknown in advance or change over time. A fixed-coefficient FIR filter cannot cancel acoustic echo from an unknown loudspeaker-to-microphone path, equalize a time-varying channel, or identify the impulse response of a vibrating structure it has never seen before. The Least Mean Squares (LMS) algorithm and its normalized variant (NLMS) address this by adjusting a FIR filter's coefficients online, one sample at a time, without requiring matrix inversions or covariance storage.
6+
7+
## Mathematical Theory
8+
9+
### Prerequisites
10+
11+
Let $\mathbf{w} \in \mathbb{R}^{N}$ be the weight vector (FIR coefficients) and $\mathbf{x}_n \in \mathbb{R}^{N}$ the tapped-delay-line vector at time $n$, with $x_n$ as the newest sample and $x_{n-N+1}$ the oldest. The filter output is
12+
13+
$$y_n = \mathbf{w}_n^\top \mathbf{x}_n.$$
14+
15+
Given a desired signal $d_n$, the estimation error is
16+
17+
$$e_n = d_n - y_n.$$
18+
19+
### Core Definitions
20+
21+
The instantaneous squared error $J_n = e_n^2$ is a quadratic function of $\mathbf{w}_n$. Its gradient with respect to $\mathbf{w}$ is
22+
23+
$$\nabla J_n = -2 e_n \mathbf{x}_n.$$
24+
25+
### Derivation
26+
27+
LMS takes a noisy steepest-descent step using the instantaneous gradient:
28+
29+
$$\mathbf{w}_{n+1} = \mathbf{w}_n - \frac{\mu}{2} \nabla J_n = \mathbf{w}_n + \mu e_n \mathbf{x}_n.$$
30+
31+
NLMS divides the step by the input energy to make the effective step size input-level independent:
32+
33+
$$\mathbf{w}_{n+1} = \mathbf{w}_n + \frac{\mu}{\epsilon + \|\mathbf{x}_n\|^2} e_n \mathbf{x}_n,$$
34+
35+
where $\epsilon > 0$ is a small regularizer that prevents division by zero during silence ($\|\mathbf{x}_n\|^2 \approx 0$).
36+
37+
### Proof of Correctness
38+
39+
Under the independence assumption (successive input vectors are uncorrelated), the expected weight vector converges to the Wiener solution $\mathbf{w}^* = \mathbf{R}^{-1}\mathbf{p}$ (where $\mathbf{R}$ is the input autocorrelation matrix and $\mathbf{p}$ is the cross-correlation vector) provided
40+
41+
$$0 < \mu < \frac{2}{\lambda_{\max}(\mathbf{R})},$$
42+
43+
a sufficient condition being $\mu < 2 / (N \cdot \sigma_x^2)$. For NLMS the stability range simplifies to $0 < \mu < 2$.
44+
45+
## Complexity Analysis
46+
47+
| Case | Time | Space | Notes |
48+
|------|--------|--------|---------------------------------------------|
49+
| Any | $O(N)$ | $O(N)$ | Two dot products + one AXPY, all length $N$ |
50+
51+
No covariance matrix is stored; memory is exactly two vectors of length $N$ (weights and delay line).
52+
53+
## Step-by-Step Walkthrough
54+
55+
Consider a 2-tap system with true plant $\mathbf{w}^* = [0.5,\ 0.5]^\top$, $\mu = 0.1$, and a white input sequence.
56+
57+
| Step | Input | Delay line $\mathbf{x}$ | Output $y$ | Desired $d$ | Error $e$ | Weight update direction |
58+
|------|-------|-------------------------|------------|-------------|-----------|-----------------------------|
59+
| 1 | 1.0 | [1.0, 0.0] | 0.0 | 0.5 | 0.5 | $+0.05\mathbf{x}$ |
60+
| 2 | 0.8 | [0.8, 1.0] | 0.04 | 0.9 | 0.86 | $+0.086\mathbf{x}$ |
61+
| … | … | … | … | … | … | converges to $\mathbf{w}^*$ |
62+
63+
After many iterations the error approaches zero and the weights stabilize near $[0.5,\ 0.5]^\top$.
64+
65+
## Pitfalls & Edge Cases
66+
67+
- **Stability bound:** exceeding $\mu_{\max}$ causes exponential weight growth. For stationary white input, $\mu_{\max} = 2 / (N\sigma_x^2)$.
68+
- **Misadjustment:** even at steady state, random gradient noise keeps the weights oscillating around $\mathbf{w}^*$, adding excess mean-squared error proportional to $\mu N$.
69+
- **Slow convergence vs stability tradeoff:** small $\mu$ gives low misadjustment but slow tracking; large $\mu$ tracks fast but overshoots.
70+
- **Silent input:** $\|\mathbf{x}_n\|^2 = 0$ causes a singularity in plain NLMS; $\epsilon$ prevents this but freezes adaptation during silence.
71+
- **Non-persistent excitation:** if the input does not excite all directions, some weights may drift. Leaky-LMS ($\mathbf{w} \leftarrow (1-\rho)\mathbf{w} + \mu e \mathbf{x}$) bounds the drift.
72+
73+
## Variants & Generalizations
74+
75+
- **NLMS:** normalizes step by input energy; removes input-power dependence; recommended for signals with variable amplitude.
76+
- **Leaky LMS:** adds a forgetting term $\rho \ll 1$ to bound weight norm under insufficient excitation.
77+
- **Block LMS:** accumulates gradients over a block before updating; lower update rate but more FFT-friendly for long filters.
78+
- **Sign-LMS / Sign-Error LMS:** replaces $e$ or $\mathbf{x}$ with their signs; extremely simple hardware implementation at the cost of convergence rate.
79+
- **RLS:** replaces the stochastic gradient with the exact least-squares update; converges in $O(N)$ steps but requires $O(N^2)$ memory and time per update.
80+
81+
## Applications
82+
83+
- **Acoustic echo cancellation:** adapt the loudspeaker-to-microphone path in teleconferencing.
84+
- **Adaptive noise cancellation:** estimate and subtract a correlated noise source (e.g. engine noise on an aircraft headset).
85+
- **Channel equalization:** track a time-varying ISI channel in wireless modems.
86+
- **Active noise control / vibration control:** generate an anti-phase signal to cancel mechanical vibration.
87+
- **Online system identification:** recover the impulse response of an unknown plant in real time.
88+
89+
## Connections to Other Algorithms
90+
91+
- **RecursiveLeastSquares:** the exact-gradient counterpart; converges in far fewer samples but needs $O(N^2)$ storage and time per step. Prefer RLS for short filter lengths or fast convergence; prefer LMS/NLMS for embedded, resource-constrained paths.
92+
- **FIR (fixed-coefficient):** LMS turns a fixed FIR into a self-tuning one; the underlying convolution is identical.
93+
- **ConvolutionCorrelation:** used to compute the cross-correlation $\mathbf{p}$ in the batch Wiener solution; LMS approximates this online.
94+
95+
## References & Further Reading
96+
97+
- B. Widrow, M. E. Hoff, "Adaptive switching circuits," *IRE WESCON Convention Record*, 1960.
98+
- S. Haykin, *Adaptive Filter Theory*, 5th ed., Pearson, 2014 — chapters 5–8.
99+
- S. Sayed, *Fundamentals of Adaptive Filtering*, Wiley, 2003.
100+
- D. G. Manolakis, V. K. Ingle, S. M. Kogon, *Statistical and Adaptive Signal Processing*, Artech House, 2005.

‎numerical/estimators/online/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@ target_link_libraries(numerical.estimators.online ${NUMERICAL_VISIBILITY}
1212

1313
target_sources(numerical.estimators.online PRIVATE
1414
RecursiveLeastSquares.hpp
15+
LmsAdaptiveFilter.hpp
1516
)
1617

1718
numerical_add_coverage_sources(numerical.estimators.online
1819
RecursiveLeastSquares.cpp
20+
LmsAdaptiveFilter.cpp
1921
)
2022

2123
add_subdirectory(test)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#include "numerical/estimators/online/LmsAdaptiveFilter.hpp"
2+
3+
namespace estimators
4+
{
5+
template class LmsAdaptiveFilter<float, 4>;
6+
}
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
#pragma once
2+
3+
#if defined(__GNUC__) || defined(__clang__)
4+
#pragma GCC optimize("O3", "fast-math")
5+
#endif
6+
7+
#include "numerical/math/CompilerOptimizations.hpp"
8+
#include <array>
9+
#include <cstddef>
10+
#include <type_traits>
11+
12+
namespace estimators
13+
{
14+
template<typename T, std::size_t Taps>
15+
class LmsAdaptiveFilter
16+
{
17+
static_assert(std::is_floating_point_v<T>, "LmsAdaptiveFilter supports floating-point types only");
18+
static_assert(Taps > 0, "Taps must be greater than zero");
19+
20+
public:
21+
struct Result
22+
{
23+
T output{};
24+
T error{};
25+
};
26+
27+
explicit LmsAdaptiveFilter(T mu, bool normalized = false, T epsilon = T{ 1e-6 });
28+
29+
OPTIMIZE_FOR_SPEED Result Update(T input, T desired);
30+
const std::array<T, Taps>& Weights() const;
31+
void Reset();
32+
33+
private:
34+
std::array<T, Taps> weights{};
35+
std::array<T, Taps> delayLine{};
36+
std::size_t head{ 0 };
37+
T stepSize;
38+
bool useNlms;
39+
T regularizer;
40+
41+
T DotProduct() const;
42+
T InputEnergy() const;
43+
T GetSample(std::size_t tapIndex) const;
44+
};
45+
46+
template<typename T, std::size_t Taps>
47+
LmsAdaptiveFilter<T, Taps>::LmsAdaptiveFilter(T mu, bool normalized, T epsilon)
48+
: stepSize{ mu }
49+
, useNlms{ normalized }
50+
, regularizer{ epsilon }
51+
{
52+
}
53+
54+
template<typename T, std::size_t Taps>
55+
T LmsAdaptiveFilter<T, Taps>::GetSample(std::size_t tapIndex) const
56+
{
57+
std::size_t index{ (head + Taps - 1u - tapIndex) % Taps };
58+
return delayLine[index];
59+
}
60+
61+
template<typename T, std::size_t Taps>
62+
T LmsAdaptiveFilter<T, Taps>::DotProduct() const
63+
{
64+
T result{ T{ 0 } };
65+
for (std::size_t i{ 0 }; i < Taps; ++i)
66+
result += weights[i] * GetSample(i);
67+
return result;
68+
}
69+
70+
template<typename T, std::size_t Taps>
71+
T LmsAdaptiveFilter<T, Taps>::InputEnergy() const
72+
{
73+
T result{ T{ 0 } };
74+
for (std::size_t i{ 0 }; i < Taps; ++i)
75+
{
76+
T s{ delayLine[i] };
77+
result += s * s;
78+
}
79+
return result;
80+
}
81+
82+
template<typename T, std::size_t Taps>
83+
OPTIMIZE_FOR_SPEED typename LmsAdaptiveFilter<T, Taps>::Result LmsAdaptiveFilter<T, Taps>::Update(T input, T desired)
84+
{
85+
delayLine[head] = input;
86+
head = (head + 1) % Taps;
87+
88+
T output{ DotProduct() };
89+
T error{ desired - output };
90+
91+
T step{ stepSize };
92+
if (useNlms)
93+
step = stepSize / (regularizer + InputEnergy());
94+
95+
T scaled{ step * error };
96+
for (std::size_t i{ 0 }; i < Taps; ++i)
97+
weights[i] += scaled * GetSample(i);
98+
99+
return Result{ output, error };
100+
}
101+
102+
template<typename T, std::size_t Taps>
103+
const std::array<T, Taps>& LmsAdaptiveFilter<T, Taps>::Weights() const
104+
{
105+
return weights;
106+
}
107+
108+
template<typename T, std::size_t Taps>
109+
void LmsAdaptiveFilter<T, Taps>::Reset()
110+
{
111+
weights.fill(T{ 0 });
112+
delayLine.fill(T{ 0 });
113+
head = 0;
114+
}
115+
}
116+
117+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
118+
namespace estimators
119+
{
120+
extern template class LmsAdaptiveFilter<float, 4>;
121+
}
122+
#endif

‎numerical/estimators/online/test/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@ target_link_libraries(numerical.estimators.online_test PUBLIC
99

1010
target_sources(numerical.estimators.online_test PRIVATE
1111
TestRecursiveLeastSquares.cpp
12+
TestLmsAdaptiveFilter.cpp
1213
)

0 commit comments

Comments
 (0)