diff --git a/README.md b/README.md index a9744c86..7463a666 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal | [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus | | [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 | | [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA | -| [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Yule-Walker (offline), Recursive Least Squares (online) | +| [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Yule-Walker (offline), Recursive Least Squares, LMS / NLMS Adaptive Filter (online) | | [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 | | [Kinematics](doc/kinematics/README.md) | Forward Kinematics | | [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, model | diff --git a/ROADMAP.md b/ROADMAP.md index 4fb1b0ec..62d00695 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -30,7 +30,6 @@ Difficulty legend: | 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ | | 19 | Luenberger observer + pole placement (Ackermann) | `controllers` | ★★★☆☆ | | 20 | Integral / servo state feedback (LQI) | `controllers` | ★★★☆☆ | -| 21 | LMS / NLMS adaptive filter | `estimators/online` | ★★★☆☆ | | 22 | Savitzky-Golay filter | `filters/passive` | ★★★☆☆ | | 23 | CORDIC | `math` | ★★★☆☆ | | 24 | Runge-Kutta ODE integrators (RK4 + Dormand-Prince) | `solvers` | ★★★☆☆ | @@ -166,12 +165,6 @@ Difficulty legend: - **Algorithm / paper:** B. D. O. Anderson, J. B. Moore, *Optimal Control: Linear Quadratic Methods* (1990). - **Reuses:** [Lqr.hpp](numerical/controllers/implementations/Lqr.hpp), [DARE](numerical/solvers/DiscreteAlgebraicRiccatiEquation.hpp). -### 21. LMS / NLMS adaptive filter -- **What:** Least-Mean-Squares (and normalized) adaptive FIR with steepest-descent weight update. -- **Embedded value:** Adaptive noise cancellation, echo cancellation, system identification, active vibration control — a DSP staple. -- **Algorithm / paper:** B. Widrow, M. Hoff, "Adaptive switching circuits," *IRE WESCON*, 1960; S. Haykin, *Adaptive Filter Theory*. -- **Reuses:** [RecursiveLeastSquares.hpp](numerical/estimators/online/RecursiveLeastSquares.hpp) patterns, `math::Vector`. - ### 22. Savitzky-Golay filter - **What:** Convolution smoother that fits a local polynomial, preserving peak height/width and giving smoothed derivatives. - **Embedded value:** Spectroscopy, ECG/PPG, and any signal where peaks matter and moving-average distortion is unacceptable. diff --git a/doc/estimators/LmsAdaptiveFilter.md b/doc/estimators/LmsAdaptiveFilter.md new file mode 100644 index 00000000..3938dc19 --- /dev/null +++ b/doc/estimators/LmsAdaptiveFilter.md @@ -0,0 +1,100 @@ +# LMS / NLMS Adaptive Filter + +## Overview & Motivation + +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. + +## Mathematical Theory + +### Prerequisites + +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 + +$$y_n = \mathbf{w}_n^\top \mathbf{x}_n.$$ + +Given a desired signal $d_n$, the estimation error is + +$$e_n = d_n - y_n.$$ + +### Core Definitions + +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 + +$$\nabla J_n = -2 e_n \mathbf{x}_n.$$ + +### Derivation + +LMS takes a noisy steepest-descent step using the instantaneous gradient: + +$$\mathbf{w}_{n+1} = \mathbf{w}_n - \frac{\mu}{2} \nabla J_n = \mathbf{w}_n + \mu e_n \mathbf{x}_n.$$ + +NLMS divides the step by the input energy to make the effective step size input-level independent: + +$$\mathbf{w}_{n+1} = \mathbf{w}_n + \frac{\mu}{\epsilon + \|\mathbf{x}_n\|^2} e_n \mathbf{x}_n,$$ + +where $\epsilon > 0$ is a small regularizer that prevents division by zero during silence ($\|\mathbf{x}_n\|^2 \approx 0$). + +### Proof of Correctness + +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 + +$$0 < \mu < \frac{2}{\lambda_{\max}(\mathbf{R})},$$ + +a sufficient condition being $\mu < 2 / (N \cdot \sigma_x^2)$. For NLMS the stability range simplifies to $0 < \mu < 2$. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|------|--------|--------|---------------------------------------------| +| Any | $O(N)$ | $O(N)$ | Two dot products + one AXPY, all length $N$ | + +No covariance matrix is stored; memory is exactly two vectors of length $N$ (weights and delay line). + +## Step-by-Step Walkthrough + +Consider a 2-tap system with true plant $\mathbf{w}^* = [0.5,\ 0.5]^\top$, $\mu = 0.1$, and a white input sequence. + +| Step | Input | Delay line $\mathbf{x}$ | Output $y$ | Desired $d$ | Error $e$ | Weight update direction | +|------|-------|-------------------------|------------|-------------|-----------|-----------------------------| +| 1 | 1.0 | [1.0, 0.0] | 0.0 | 0.5 | 0.5 | $+0.05\mathbf{x}$ | +| 2 | 0.8 | [0.8, 1.0] | 0.04 | 0.9 | 0.86 | $+0.086\mathbf{x}$ | +| … | … | … | … | … | … | converges to $\mathbf{w}^*$ | + +After many iterations the error approaches zero and the weights stabilize near $[0.5,\ 0.5]^\top$. + +## Pitfalls & Edge Cases + +- **Stability bound:** exceeding $\mu_{\max}$ causes exponential weight growth. For stationary white input, $\mu_{\max} = 2 / (N\sigma_x^2)$. +- **Misadjustment:** even at steady state, random gradient noise keeps the weights oscillating around $\mathbf{w}^*$, adding excess mean-squared error proportional to $\mu N$. +- **Slow convergence vs stability tradeoff:** small $\mu$ gives low misadjustment but slow tracking; large $\mu$ tracks fast but overshoots. +- **Silent input:** $\|\mathbf{x}_n\|^2 = 0$ causes a singularity in plain NLMS; $\epsilon$ prevents this but freezes adaptation during silence. +- **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. + +## Variants & Generalizations + +- **NLMS:** normalizes step by input energy; removes input-power dependence; recommended for signals with variable amplitude. +- **Leaky LMS:** adds a forgetting term $\rho \ll 1$ to bound weight norm under insufficient excitation. +- **Block LMS:** accumulates gradients over a block before updating; lower update rate but more FFT-friendly for long filters. +- **Sign-LMS / Sign-Error LMS:** replaces $e$ or $\mathbf{x}$ with their signs; extremely simple hardware implementation at the cost of convergence rate. +- **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. + +## Applications + +- **Acoustic echo cancellation:** adapt the loudspeaker-to-microphone path in teleconferencing. +- **Adaptive noise cancellation:** estimate and subtract a correlated noise source (e.g. engine noise on an aircraft headset). +- **Channel equalization:** track a time-varying ISI channel in wireless modems. +- **Active noise control / vibration control:** generate an anti-phase signal to cancel mechanical vibration. +- **Online system identification:** recover the impulse response of an unknown plant in real time. + +## Connections to Other Algorithms + +- **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. +- **FIR (fixed-coefficient):** LMS turns a fixed FIR into a self-tuning one; the underlying convolution is identical. +- **ConvolutionCorrelation:** used to compute the cross-correlation $\mathbf{p}$ in the batch Wiener solution; LMS approximates this online. + +## References & Further Reading + +- B. Widrow, M. E. Hoff, "Adaptive switching circuits," *IRE WESCON Convention Record*, 1960. +- S. Haykin, *Adaptive Filter Theory*, 5th ed., Pearson, 2014 — chapters 5–8. +- S. Sayed, *Fundamentals of Adaptive Filtering*, Wiley, 2003. +- D. G. Manolakis, V. K. Ingle, S. M. Kogon, *Statistical and Adaptive Signal Processing*, Artech House, 2005. diff --git a/numerical/estimators/online/CMakeLists.txt b/numerical/estimators/online/CMakeLists.txt index afbf95e8..3423b0fa 100644 --- a/numerical/estimators/online/CMakeLists.txt +++ b/numerical/estimators/online/CMakeLists.txt @@ -12,10 +12,12 @@ target_link_libraries(numerical.estimators.online ${NUMERICAL_VISIBILITY} target_sources(numerical.estimators.online PRIVATE RecursiveLeastSquares.hpp + LmsAdaptiveFilter.hpp ) numerical_add_coverage_sources(numerical.estimators.online RecursiveLeastSquares.cpp + LmsAdaptiveFilter.cpp ) add_subdirectory(test) diff --git a/numerical/estimators/online/LmsAdaptiveFilter.cpp b/numerical/estimators/online/LmsAdaptiveFilter.cpp new file mode 100644 index 00000000..b0bca306 --- /dev/null +++ b/numerical/estimators/online/LmsAdaptiveFilter.cpp @@ -0,0 +1,6 @@ +#include "numerical/estimators/online/LmsAdaptiveFilter.hpp" + +namespace estimators +{ + template class LmsAdaptiveFilter; +} diff --git a/numerical/estimators/online/LmsAdaptiveFilter.hpp b/numerical/estimators/online/LmsAdaptiveFilter.hpp new file mode 100644 index 00000000..6ab8398b --- /dev/null +++ b/numerical/estimators/online/LmsAdaptiveFilter.hpp @@ -0,0 +1,122 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include +#include +#include + +namespace estimators +{ + template + class LmsAdaptiveFilter + { + static_assert(std::is_floating_point_v, "LmsAdaptiveFilter supports floating-point types only"); + static_assert(Taps > 0, "Taps must be greater than zero"); + + public: + struct Result + { + T output{}; + T error{}; + }; + + explicit LmsAdaptiveFilter(T mu, bool normalized = false, T epsilon = T{ 1e-6 }); + + OPTIMIZE_FOR_SPEED Result Update(T input, T desired); + const std::array& Weights() const; + void Reset(); + + private: + std::array weights{}; + std::array delayLine{}; + std::size_t head{ 0 }; + T stepSize; + bool useNlms; + T regularizer; + + T DotProduct() const; + T InputEnergy() const; + T GetSample(std::size_t tapIndex) const; + }; + + template + LmsAdaptiveFilter::LmsAdaptiveFilter(T mu, bool normalized, T epsilon) + : stepSize{ mu } + , useNlms{ normalized } + , regularizer{ epsilon } + { + } + + template + T LmsAdaptiveFilter::GetSample(std::size_t tapIndex) const + { + std::size_t index{ (head + Taps - 1u - tapIndex) % Taps }; + return delayLine[index]; + } + + template + T LmsAdaptiveFilter::DotProduct() const + { + T result{ T{ 0 } }; + for (std::size_t i{ 0 }; i < Taps; ++i) + result += weights[i] * GetSample(i); + return result; + } + + template + T LmsAdaptiveFilter::InputEnergy() const + { + T result{ T{ 0 } }; + for (std::size_t i{ 0 }; i < Taps; ++i) + { + T s{ delayLine[i] }; + result += s * s; + } + return result; + } + + template + OPTIMIZE_FOR_SPEED typename LmsAdaptiveFilter::Result LmsAdaptiveFilter::Update(T input, T desired) + { + delayLine[head] = input; + head = (head + 1) % Taps; + + T output{ DotProduct() }; + T error{ desired - output }; + + T step{ stepSize }; + if (useNlms) + step = stepSize / (regularizer + InputEnergy()); + + T scaled{ step * error }; + for (std::size_t i{ 0 }; i < Taps; ++i) + weights[i] += scaled * GetSample(i); + + return Result{ output, error }; + } + + template + const std::array& LmsAdaptiveFilter::Weights() const + { + return weights; + } + + template + void LmsAdaptiveFilter::Reset() + { + weights.fill(T{ 0 }); + delayLine.fill(T{ 0 }); + head = 0; + } +} + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD +namespace estimators +{ + extern template class LmsAdaptiveFilter; +} +#endif diff --git a/numerical/estimators/online/test/CMakeLists.txt b/numerical/estimators/online/test/CMakeLists.txt index a8fbcce9..c1d5aca5 100644 --- a/numerical/estimators/online/test/CMakeLists.txt +++ b/numerical/estimators/online/test/CMakeLists.txt @@ -9,4 +9,5 @@ target_link_libraries(numerical.estimators.online_test PUBLIC target_sources(numerical.estimators.online_test PRIVATE TestRecursiveLeastSquares.cpp + TestLmsAdaptiveFilter.cpp ) diff --git a/numerical/estimators/online/test/TestLmsAdaptiveFilter.cpp b/numerical/estimators/online/test/TestLmsAdaptiveFilter.cpp new file mode 100644 index 00000000..f4c2352f --- /dev/null +++ b/numerical/estimators/online/test/TestLmsAdaptiveFilter.cpp @@ -0,0 +1,268 @@ +#include "numerical/estimators/online/LmsAdaptiveFilter.hpp" +#include "numerical/math/Tolerance.hpp" +#include +#include + +namespace +{ + class TestLmsAdaptiveFilter + : public ::testing::Test + { + protected: + estimators::LmsAdaptiveFilter lms{ 0.1f }; + }; +} + +TEST_F(TestLmsAdaptiveFilter, identifies_static_fir_system) +{ + constexpr std::array plant{ 0.5f, -0.25f, 0.125f, -0.0625f }; + + std::array inputHistory{}; + uint32_t seed{ 42 }; + auto nextSample = [&seed]() -> float + { + seed = seed * 1664525u + 1013904223u; + return static_cast(static_cast(seed)) / static_cast(1u << 31u); + }; + + for (int i{ 0 }; i < 4000; ++i) + { + float input{ nextSample() }; + for (int j{ 3 }; j > 0; --j) + inputHistory[j] = inputHistory[j - 1]; + inputHistory[0] = input; + + float desired{ 0.0f }; + for (std::size_t k{ 0 }; k < 4; ++k) + desired += plant[k] * inputHistory[k]; + + lms.Update(input, desired); + } + + const auto& w{ lms.Weights() }; + EXPECT_NEAR(w[0], plant[0], 0.01f); + EXPECT_NEAR(w[1], plant[1], 0.01f); + EXPECT_NEAR(w[2], plant[2], 0.01f); + EXPECT_NEAR(w[3], plant[3], 0.01f); +} + +TEST_F(TestLmsAdaptiveFilter, error_decreases_on_average) +{ + constexpr std::array plant{ 0.5f, 0.5f, 0.0f, 0.0f }; + + std::array inputHistory{}; + uint32_t seed{ 99 }; + auto nextSample = [&seed]() -> float + { + seed = seed * 1664525u + 1013904223u; + return static_cast(static_cast(seed)) / static_cast(1u << 31u); + }; + + float earlyMse{ 0.0f }; + float lateMse{ 0.0f }; + constexpr int total{ 2000 }; + constexpr int half{ total / 2 }; + + for (int i{ 0 }; i < total; ++i) + { + float input{ nextSample() }; + for (int j{ 3 }; j > 0; --j) + inputHistory[j] = inputHistory[j - 1]; + inputHistory[0] = input; + + float desired{ 0.0f }; + for (std::size_t k{ 0 }; k < 4; ++k) + desired += plant[k] * inputHistory[k]; + + auto result{ lms.Update(input, desired) }; + + if (i < half) + earlyMse += result.error * result.error; + else + lateMse += result.error * result.error; + } + + EXPECT_LT(lateMse, earlyMse); +} + +TEST_F(TestLmsAdaptiveFilter, zero_error_freezes_weights) +{ + lms.Update(1.0f, 0.0f); + lms.Update(1.0f, 0.0f); + + const std::array weightsBefore{ lms.Weights() }; + + float output{ lms.Update(1.0f, 0.0f).output }; + lms.Update(1.0f, output); + + const auto& weightsAfter{ lms.Weights() }; + for (std::size_t i{ 0 }; i < 4; ++i) + EXPECT_NEAR(weightsAfter[i], weightsBefore[i], math::Tolerance()); +} + +TEST_F(TestLmsAdaptiveFilter, nlms_converges_independent_of_input_scale) +{ + constexpr std::array plant{ 0.5f, 0.5f, 0.0f, 0.0f }; + + estimators::LmsAdaptiveFilter nlmsUnscaled{ 0.5f, true }; + estimators::LmsAdaptiveFilter nlmsScaled{ 0.5f, true }; + + std::array histNorm{}; + std::array histScaled{}; + + uint32_t seed{ 77 }; + auto nextSample = [&seed]() -> float + { + seed = seed * 1664525u + 1013904223u; + return static_cast(static_cast(seed)) / static_cast(1u << 31u); + }; + + constexpr int iterations{ 2000 }; + float errNorm{ 0.0f }; + float errScaled{ 0.0f }; + + for (int i{ 0 }; i < iterations; ++i) + { + float base{ nextSample() }; + float scaled{ base * 10.0f }; + + for (int j{ 3 }; j > 0; --j) + { + histNorm[j] = histNorm[j - 1]; + histScaled[j] = histScaled[j - 1]; + } + histNorm[0] = base; + histScaled[0] = scaled; + + float desiredNorm{ 0.0f }; + float desiredScaled{ 0.0f }; + for (std::size_t k{ 0 }; k < 4; ++k) + { + desiredNorm += plant[k] * histNorm[k]; + desiredScaled += plant[k] * histScaled[k]; + } + + auto rn{ nlmsUnscaled.Update(base, desiredNorm) }; + auto rs{ nlmsScaled.Update(scaled, desiredScaled) }; + + if (i >= iterations / 2) + { + errNorm += rn.error * rn.error; + errScaled += rs.error * rs.error; + } + } + + const auto& wn{ nlmsUnscaled.Weights() }; + const auto& ws{ nlmsScaled.Weights() }; + EXPECT_NEAR(wn[0], plant[0], 0.05f); + EXPECT_NEAR(ws[0], plant[0], 0.05f); +} + +TEST_F(TestLmsAdaptiveFilter, larger_mu_converges_faster) +{ + constexpr std::array plant{ 0.5f, 0.5f, 0.0f, 0.0f }; + + estimators::LmsAdaptiveFilter slowFilter{ 0.05f }; + estimators::LmsAdaptiveFilter fastFilter{ 0.2f }; + + std::array histSlow{}; + std::array histFast{}; + + uint32_t seed{ 123 }; + auto nextSample = [&seed]() -> float + { + seed = seed * 1664525u + 1013904223u; + return static_cast(static_cast(seed)) / static_cast(1u << 31u); + }; + + constexpr float threshold{ 0.01f }; + int slowConverged{ -1 }; + int fastConverged{ -1 }; + constexpr int maxIter{ 5000 }; + + for (int i{ 0 }; i < maxIter; ++i) + { + float input{ nextSample() }; + for (int j{ 3 }; j > 0; --j) + { + histSlow[j] = histSlow[j - 1]; + histFast[j] = histFast[j - 1]; + } + histSlow[0] = input; + histFast[0] = input; + + float desired{ 0.0f }; + for (std::size_t k{ 0 }; k < 4; ++k) + desired += plant[k] * histSlow[k]; + + auto rs{ slowFilter.Update(input, desired) }; + auto rf{ fastFilter.Update(input, desired) }; + + if (slowConverged < 0 && std::abs(rs.error) < threshold) + slowConverged = i; + if (fastConverged < 0 && std::abs(rf.error) < threshold) + fastConverged = i; + } + + EXPECT_LT(fastConverged, slowConverged); +} + +TEST_F(TestLmsAdaptiveFilter, reset_clears_weights_and_history) +{ + constexpr std::array plant{ 0.5f, 0.5f, 0.0f, 0.0f }; + std::array hist{}; + + uint32_t seed{ 11 }; + auto nextSample = [&seed]() -> float + { + seed = seed * 1664525u + 1013904223u; + return static_cast(static_cast(seed)) / static_cast(1u << 31u); + }; + + for (int i{ 0 }; i < 500; ++i) + { + float input{ nextSample() }; + for (int j{ 3 }; j > 0; --j) + hist[j] = hist[j - 1]; + hist[0] = input; + + float desired{ 0.0f }; + for (std::size_t k{ 0 }; k < 4; ++k) + desired += plant[k] * hist[k]; + + lms.Update(input, desired); + } + + lms.Reset(); + + const auto& w{ lms.Weights() }; + for (std::size_t i{ 0 }; i < 4; ++i) + EXPECT_NEAR(w[i], 0.0f, math::Tolerance()); + + float out{ lms.Update(1.0f, 0.0f).output }; + EXPECT_NEAR(out, 0.0f, math::Tolerance()); +} + +TEST_F(TestLmsAdaptiveFilter, output_equals_fir_of_weights) +{ + estimators::LmsAdaptiveFilter filter{ 0.0f }; + + filter.Update(0.0f, 0.0f); + filter.Update(0.0f, 0.0f); + filter.Update(0.0f, 0.0f); + filter.Update(0.0f, 0.0f); + + const std::array knownWeights{ 0.3f, 0.6f, 0.1f, -0.2f }; + auto& w{ const_cast&>(filter.Weights()) }; + w = knownWeights; + + float out0{ filter.Update(1.0f, 0.0f).output }; + float out1{ filter.Update(0.0f, 0.0f).output }; + float out2{ filter.Update(0.0f, 0.0f).output }; + float out3{ filter.Update(0.0f, 0.0f).output }; + + EXPECT_NEAR(out0, knownWeights[0], math::Tolerance()); + EXPECT_NEAR(out1, knownWeights[1], math::Tolerance()); + EXPECT_NEAR(out2, knownWeights[2], math::Tolerance()); + EXPECT_NEAR(out3, knownWeights[3], math::Tolerance()); +} diff --git a/roadmap/estimators/online/LmsAdaptiveFilter/explanation.md b/roadmap/estimators/online/LmsAdaptiveFilter/explanation.md deleted file mode 100644 index 1b0ab81d..00000000 --- a/roadmap/estimators/online/LmsAdaptiveFilter/explanation.md +++ /dev/null @@ -1,32 +0,0 @@ -# LMS / NLMS Adaptive Filter — Overview - -## What it is -An adaptive FIR filter that **learns its own coefficients** online. Each sample it compares its -output to a desired signal and nudges the weights down the instantaneous error gradient: -`w ← w + μ·e·x`. NLMS (Normalized LMS) divides the step by the input energy `‖x‖²` so the learning -rate no longer depends on signal level. - -## Why it matters (embedded) -It is the workhorse of real-time adaptation: **acoustic echo cancellation**, adaptive noise -cancellation, channel equalization, active vibration/noise control, and online system -identification. Compared with Recursive Least Squares it needs no covariance matrix — just two -vectors — so it fits tiny MCUs and tracks slowly changing environments in `O(Taps)` per sample. - -## How it works (intuition) -Think of gradient descent applied one sample at a time. The error `e = desired − wᵀx` measures how -wrong the current weights are; scaling the input `x` by that error points each weight in the -direction that reduces it. A small step `μ` averages out noise but adapts slowly; a large step -adapts fast but risks instability. NLMS auto-scales the step so loud and quiet signals adapt alike. - -## Key parameters -- **μ (step size / learning rate)** — the speed-vs-stability knob; bounded by input power (LMS) or ~2 (NLMS). -- **Tap count** — length of the FIR; must span the impulse response being modeled. -- **Normalization / ε** — enable NLMS for level-independent convergence; ε guards against silence. - -## Reference -B. Widrow, M. E. Hoff, "Adaptive switching circuits," *IRE WESCON Conv. Rec.*, 1960; -S. Haykin, *Adaptive Filter Theory*. - -## See also -`RecursiveLeastSquares` (faster-converging, heavier online estimator), `Fir` (fixed-coefficient -filter), `ConvolutionCorrelation`. diff --git a/roadmap/estimators/online/LmsAdaptiveFilter/implementation.md b/roadmap/estimators/online/LmsAdaptiveFilter/implementation.md deleted file mode 100644 index e504b8ed..00000000 --- a/roadmap/estimators/online/LmsAdaptiveFilter/implementation.md +++ /dev/null @@ -1,70 +0,0 @@ -# LMS / NLMS Adaptive Filter — Implementation Pseudocode - -> Roadmap ref: #21 (Tier 3) · Target: `numerical/estimators/online` · Namespace `estimators` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class LmsAdaptiveFilter: - Vector weights = 0 # adaptive FIR coefficients w - RecursiveBuffer x # tapped delay line (newest .. oldest) - T mu # step size (learning rate) - bool normalized # NLMS when true - T epsilon # NLMS regularizer (avoid /0) -``` - -## Interface - -``` -LmsAdaptiveFilter(T mu, bool normalized = false, T epsilon = small) -struct Result { T output; T error; } -Result Update(T input, T desired) # hot path -const Vector& Weights() -void Reset() -``` - -## Algorithm (pseudocode) - -``` -function Update(input, desired): # OPTIMIZE_FOR_SPEED - x.Push(input) # shift newest sample in - y = dot(weights, x) # FIR output y = wᵀx - e = desired - y # estimation error - step = mu - if normalized: # NLMS - step = mu / (epsilon + dot(x, x)) # divide by ‖x‖² - # Steepest-descent weight update w ← w + step·e·x - for i in 0 .. Taps-1: - weights[i] += step * e * x[i] - return { y, e } - -function Reset(): - weights = 0 ; x.Clear() -``` - -## Complexity & memory - -- Update: `O(Taps)` — two dot products and one AXPY, all length `Taps`. -- Memory: `O(Taps)` for weights plus the delay line; no heap, no covariance matrix (unlike RLS). - -## Numerical / embedded notes - -- **Stability bound:** plain LMS converges for `0 < mu < 2/λ_max(R)`; a safe rule of thumb is - `mu < 2/(Taps·signalPower)`. NLMS removes the input-power dependence ⇒ use `0 < mu < 2`. -- NLMS `epsilon` prevents divide-by-zero and damps updates during silence (`‖x‖² ≈ 0`). -- Leaky-LMS variant `w ← (1−ρ)·w + step·e·x` bounds weight drift under non-persistent excitation. -- Float-only: `static_assert(std::is_floating_point_v)`; the generic `T` signature keeps a - `Q15`/`Q31` specialisation cheap to add later. - -## Deployment - -- Header: `numerical/estimators/online/LmsAdaptiveFilter.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Update`, and - `extern template class LmsAdaptiveFilter;` under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/estimators/online/LmsAdaptiveFilter.cpp` → `template class LmsAdaptiveFilter;` -- Test: `numerical/estimators/online/test/TestLmsAdaptiveFilter.cpp` -- Doc: `doc/estimators/LmsAdaptiveFilter.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestLmsAdaptiveFilter.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. diff --git a/roadmap/estimators/online/LmsAdaptiveFilter/tests.md b/roadmap/estimators/online/LmsAdaptiveFilter/tests.md deleted file mode 100644 index 9a9d4d17..00000000 --- a/roadmap/estimators/online/LmsAdaptiveFilter/tests.md +++ /dev/null @@ -1,54 +0,0 @@ -# LMS / NLMS Adaptive Filter — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestLmsAdaptiveFilter : public ::testing::Test: - LmsAdaptiveFilter lms{ 0.1f } # 4 taps, mu = 0.1 -# each case below is a TEST_F(TestLmsAdaptiveFilter, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -identifies_static_fir_system: - Arrange: unknown plant w* = [0.5, -0.25, ...]; desired = w*ᵀx - Act: Update over many random inputs - Assert: weights converge to w*; error → 0 - -error_decreases_on_average: - Arrange: stationary input - Assert: moving average of e² is non-increasing - -zero_error_freezes_weights: - Arrange: desired == current output (e = 0) - Assert: weights unchanged after Update - -nlms_converges_independent_of_input_scale: - Arrange: same system, input scaled ×10, normalized = true - Assert: convergence rate ≈ unscaled case - -larger_mu_converges_faster: - Arrange: two filters mu = 0.05 vs 0.2 - Assert: higher mu reaches threshold in fewer samples - -reset_clears_weights_and_history: - Arrange: adapt, Reset() - Assert: Weights == 0; next output == 0 - -output_equals_fir_of_weights: - Arrange: set known weights, feed an impulse - Assert: output sequence == weights (FIR identity) -``` - -## Reference vectors - -- Two-tap plant `w* = [0.5, 0.5]`, white input ⇒ weights converge to `[0.5, 0.5]`. -- NLMS with `mu = 1` ⇒ one-step convergence for a single-tap noiseless system. - -## Edge cases - -- `mu` above the stability bound ⇒ divergence (assert detectable growth in a diagnostics test). -- Silent input (`‖x‖² ≈ 0`) with NLMS ⇒ `epsilon` prevents blow-up.