From 77e315dab2eaa4987a00d6489e06039d75aba55a Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sun, 26 Jul 2026 16:49:19 +0000 Subject: [PATCH 1/3] add exponential moving average filter --- README.md | 2 +- ROADMAP.md | 51 +++++++ .../passive/ExponentialMovingAverage.md | 128 ++++++++++++++++++ numerical/filters/passive/CMakeLists.txt | 2 + .../passive/ExponentialMovingAverage.cpp | 6 + .../passive/ExponentialMovingAverage.hpp | 93 +++++++++++++ numerical/filters/passive/test/CMakeLists.txt | 1 + .../test/TestExponentialMovingAverage.cpp | 74 ++++++++++ 8 files changed, 356 insertions(+), 1 deletion(-) create mode 100644 doc/filters/passive/ExponentialMovingAverage.md create mode 100644 numerical/filters/passive/ExponentialMovingAverage.cpp create mode 100644 numerical/filters/passive/ExponentialMovingAverage.hpp create mode 100644 numerical/filters/passive/test/TestExponentialMovingAverage.cpp diff --git a/README.md b/README.md index 277bb241..bbef2536 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal | [Controllers](doc/controllers/README.md) | PID, LQR, MPC | | [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA | | [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker (offline), Recursive Least Squares (online) | -| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR | +| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Exponential Moving Average | | [Kinematics](doc/kinematics/README.md) | Forward Kinematics | | [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, model | | [Optimization](doc/optimization/README.md) | Gradient Descent | diff --git a/ROADMAP.md b/ROADMAP.md index 027022b9..21e75fe6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -24,6 +24,7 @@ Difficulty legend: ## Master list (by priority) +<<<<<<< Updated upstream | # | Component | Target module | Difficulty | |----|------------------------------------------------------|---------------------------|------------| | 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ | @@ -73,6 +74,56 @@ Difficulty legend: | 45 | IIR filter design (Butterworth/Chebyshev + bilinear) | `filters/passive` | ★★★★★ | | 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ | | 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ | +======= +| # | Component | Target module | Difficulty | +|----|-----------|---------------|------------| +| 2 | Moving Average (running-sum boxcar) | `filters/passive` | ★☆☆☆☆ | +| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ | +| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ | +| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ | +| 6 | Median filter | `filters/passive` | ★★☆☆☆ | +| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ | +| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ | +| 9 | Complementary filter | `filters/active` | ★★☆☆☆ | +| 10 | Gain-scheduled controller | `controllers` | ★★☆☆☆ | +| 11 | Convolution & correlation utilities | `analysis` | ★★☆☆☆ | +| 12 | Polynomial least-squares curve fitting | `estimators/offline` | ★★☆☆☆ | +| 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ | +| 14 | CIC (Cascaded Integrator-Comb) filter | `filters/passive` | ★★☆☆☆ | +| 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ | +| 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ | +| 17 | Lead-lag compensator | `controllers` | ★★★☆☆ | +| 18 | Quaternion type | `math` | ★★★☆☆ | +| 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` | ★★★☆☆ | +| 25 | Real-input FFT (RFFT) | `analysis` | ★★★☆☆ | +| 26 | Controllability / Observability matrices & Gramians | `control_analysis` | ★★★☆☆ | +| 27 | QR decomposition (Householder / Givens) | `solvers` | ★★★★☆ | +| 28 | LU decomposition with partial pivoting | `solvers` | ★★★★☆ | +| 29 | Matrix exponential (scaling & squaring + Padé) | `math` | ★★★★☆ | +| 30 | Continuous → discrete conversion (`c2d`) | `math` | ★★★★☆ | +| 31 | Lyapunov / Sylvester equation solvers | `solvers` | ★★★★☆ | +| 32 | Transfer-function ↔ state-space conversion | `control_analysis` | ★★★★☆ | +| 33 | Madgwick / Mahony AHRS | `filters/active` | ★★★★☆ | +| 34 | Sliding Mode Control (SMC) | `robust_control` (new) | ★★★★☆ | +| 35 | Disturbance Observer (DOB) | `robust_control` (new) | ★★★★☆ | +| 36 | Active Disturbance Rejection Control (ADRC + ESO) | `robust_control` (new) | ★★★★☆ | +| 37 | Hilbert transform / analytic signal / envelope | `analysis` | ★★★★☆ | +| 38 | Discrete Wavelet Transform (Haar / Daubechies) | `analysis` | ★★★★☆ | +| 39 | Square-root / Information Kalman filter | `filters/active` | ★★★★☆ | +| 40 | Feedback linearization | `nonlinear_control` (new) | ★★★★☆ | +| 41 | Backstepping controller | `nonlinear_control` (new) | ★★★★☆ | +| 42 | Symmetric eigenvalue solver (Jacobi) | `solvers` | ★★★★★ | +| 43 | Singular Value Decomposition (Golub-Kahan) | `solvers` | ★★★★★ | +| 44 | Total Least Squares | `estimators/offline` | ★★★★★ | +| 45 | IIR filter design (Butterworth/Chebyshev + bilinear) | `filters/passive` | ★★★★★ | +| 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ | +| 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ | +>>>>>>> Stashed changes --- diff --git a/doc/filters/passive/ExponentialMovingAverage.md b/doc/filters/passive/ExponentialMovingAverage.md new file mode 100644 index 00000000..4a7f89c8 --- /dev/null +++ b/doc/filters/passive/ExponentialMovingAverage.md @@ -0,0 +1,128 @@ +# Exponential Moving Average + +## Overview & Motivation + +Sensor data in embedded systems is noisy. A full moving-average buffer costs O(N) RAM and O(N) +computation per sample. The exponential moving average (EMA), also called a one-pole recursive +low-pass filter or leaky integrator, achieves useful smoothing with a single state word and one +multiply-accumulate per sample. It is the minimal-cost filter that tracks a slowly varying DC +level while suppressing high-frequency noise. + +## Mathematical Theory + +### Core Definition + +Given a smoothing factor $\alpha \in (0, 1]$ and a discrete input sequence $x[n]$, the EMA +output $y[n]$ obeys the first-order linear recurrence: + +$$y[n] = \alpha \, x[n] + (1 - \alpha) \, y[n-1]$$ + +with $y[-1] = y_0$ (the initial state, often zero). + +### Rearranged Update Form + +Expanding the recurrence: + +$$y[n] = y[n-1] + \alpha \bigl(x[n] - y[n-1]\bigr)$$ + +This form has one subtraction and one multiply-accumulate; it avoids computing $(1-\alpha)$ +explicitly and keeps the error term $(x[n] - y[n-1])$ small, which is numerically preferable in +fixed-point arithmetic. + +### Pole Location and Stability + +The transfer function in the $z$-domain is: + +$$H(z) = \frac{\alpha}{1 - (1-\alpha)\,z^{-1}}$$ + +The single pole is at $z = 1 - \alpha$. For $\alpha \in (0, 1]$ the pole lies in $[0, 1)$, which +is strictly inside the unit circle, so the filter is unconditionally stable. + +### DC Gain + +Setting $z = 1$ (DC, $\omega = 0$): + +$$H(1) = \frac{\alpha}{1 - (1-\alpha)} = 1$$ + +Unity DC gain: a constant input converges exactly to that constant. + +### Cutoff Frequency + +Matching the EMA pole to a first-order RC low-pass filter with time constant $\tau = 1/(2\pi f_c)$ +and sample period $T_s = 1/f_s$: + +$$\alpha = \frac{T_s}{\tau + T_s} = \frac{T_s}{\frac{1}{2\pi f_c} + T_s}$$ + +### Impulse Response + +The impulse response is $h[n] = \alpha (1-\alpha)^n \, u[n]$, which decays geometrically — +hence the name "exponential" moving average. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|---------|--------|--------|-----------------------------------------| +| Best | O(1) | O(1) | Single MAC per sample, one state word | +| Average | O(1) | O(1) | Identical regardless of input | +| Worst | O(1) | O(1) | No data-dependent branches on hot path | + +## Step-by-Step Walkthrough + +Suppose $\alpha = 0.5$, $y[-1] = 0$, and the input is the unit impulse $x = [1, 0, 0, 0, \ldots]$. + +| $n$ | $x[n]$ | $x[n] - y[n-1]$ | $\alpha \cdot \Delta$ | $y[n]$ | +|-----|--------|------------------|-----------------------|---------| +| 0 | 1 | $1 - 0 = 1$ | $0.5$ | $0.5$ | +| 1 | 0 | $0 - 0.5 = -0.5$ | $-0.25$ | $0.25$ | +| 2 | 0 | $0 - 0.25 = -0.25$| $-0.125$ | $0.125$ | +| 3 | 0 | $0 - 0.125 = -0.125$| $-0.0625$ | $0.0625$| + +Each output is half the previous, confirming $h[n] = (0.5)^{n+1}$. + +## Pitfalls & Edge Cases + +- $\alpha \to 0$: The filter barely reacts; the time constant grows toward infinity. At exactly + zero the state never updates (division by zero in the cutoff formula). +- $\alpha = 1$: Pure passthrough — no smoothing at all; the output equals the input exactly. +- Initial transient: If the initial state differs significantly from the true signal level, the + output will have a startup transient lasting approximately $1/\alpha$ samples. Seeding the + state with the first sample eliminates this. +- Floating-point accumulation: Long runs of constant input may show residual drift at the level + of floating-point epsilon relative to the signal magnitude; this is negligible for float32. + +## Variants & Generalizations + +- **Double EMA (DEMA)**: Applies the EMA twice and corrects for lag: $2\,y_1[n] - y_2[n]$. + Reduces lag at the cost of one extra state word and multiply. +- **Kaufman Adaptive Moving Average (KAMA)**: Adjusts $\alpha$ dynamically based on market + efficiency ratio; the same one-pole structure with a time-varying coefficient. +- **Exponentially Weighted Moving Variance**: Tracks variance alongside the mean using a second + recurrence on the squared error. +- **Higher-order cascades**: Cascading $k$ EMA stages produces a Butterworth-like response with + $k$ poles and $-20k$ dB/decade roll-off. + +## Applications + +- Sensor de-noising (IMU, ADC, temperature) where buffer RAM is scarce. +- DC-offset tracking and removal. +- Smoothed feedback signals in PID control loops. +- Battery voltage estimation. +- Signal envelope detection. + +## Connections to Other Algorithms + +- **FIR moving average**: Linear-phase alternative; symmetric impulse response gives zero group + delay distortion but requires O(N) RAM and O(N) MACs. +- **Biquad cascade (IIR)**: Higher-order roll-off at the cost of two state words per section and + potential instability if coefficients are not quantised carefully. +- **Kalman filter (scalar)**: The steady-state scalar Kalman gain is equivalent to an EMA with + $\alpha = K$ determined by the noise ratio; EMA is the optimal estimator for a random-walk + signal in Gaussian noise. + +## References & Further Reading + +- S. W. Smith, *The Scientist and Engineer's Guide to Digital Signal Processing*, Ch. 19 + (Recursive / single-pole filters). Available free at dspguide.com. +- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Ch. 5 (IIR filter + design). +- R. G. Lyons, *Understanding Digital Signal Processing*, 3rd ed., Ch. 6 (recursive filters). diff --git a/numerical/filters/passive/CMakeLists.txt b/numerical/filters/passive/CMakeLists.txt index ab608c11..944ccb25 100644 --- a/numerical/filters/passive/CMakeLists.txt +++ b/numerical/filters/passive/CMakeLists.txt @@ -11,11 +11,13 @@ target_link_libraries(numerical.filters.passive ${NUMERICAL_VISIBILITY} ) target_sources(numerical.filters.passive PRIVATE + ExponentialMovingAverage.hpp Fir.hpp Iir.hpp ) numerical_add_coverage_sources(numerical.filters.passive + ExponentialMovingAverage.cpp Fir.cpp Iir.cpp ) diff --git a/numerical/filters/passive/ExponentialMovingAverage.cpp b/numerical/filters/passive/ExponentialMovingAverage.cpp new file mode 100644 index 00000000..0c3cc487 --- /dev/null +++ b/numerical/filters/passive/ExponentialMovingAverage.cpp @@ -0,0 +1,6 @@ +#include "numerical/filters/passive/ExponentialMovingAverage.hpp" + +namespace filters::passive +{ + template class ExponentialMovingAverage; +} diff --git a/numerical/filters/passive/ExponentialMovingAverage.hpp b/numerical/filters/passive/ExponentialMovingAverage.hpp new file mode 100644 index 00000000..8420fa1b --- /dev/null +++ b/numerical/filters/passive/ExponentialMovingAverage.hpp @@ -0,0 +1,93 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" + +#include +#include +#include +#include + +namespace filters::passive +{ + template + class ExponentialMovingAverage + { + static_assert(std::is_floating_point_v, "ExponentialMovingAverage supports floating-point types"); + + public: + explicit ExponentialMovingAverage(T alpha, T initial = T{}) noexcept; + + OPTIMIZE_FOR_SPEED T Filter(T input) noexcept; + void Reset(T value = T{}) noexcept; + void SetAlpha(T alpha) noexcept; + void Enable() noexcept; + void Disable() noexcept; + + static T AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept; + + private: + T alpha; + T state; + bool enabled{ true }; + }; + + //// Implementation //// + + template + ExponentialMovingAverage::ExponentialMovingAverage(T alpha, T initial) noexcept + : alpha{ alpha } + , state{ initial } + { + assert(alpha > T{} && alpha <= T{ 1 }); + } + + template + OPTIMIZE_FOR_SPEED T ExponentialMovingAverage::Filter(T input) noexcept + { + if (!enabled) [[unlikely]] + return input; + state = state + alpha * (input - state); + return state; + } + + template + void ExponentialMovingAverage::Reset(T value) noexcept + { + state = value; + } + + template + void ExponentialMovingAverage::SetAlpha(T newAlpha) noexcept + { + assert(newAlpha > T{} && newAlpha <= T{ 1 }); + alpha = newAlpha; + } + + template + void ExponentialMovingAverage::Enable() noexcept + { + enabled = true; + } + + template + void ExponentialMovingAverage::Disable() noexcept + { + enabled = false; + } + + template + T ExponentialMovingAverage::AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept + { + const T dt{ T{ 1 } / sampleRateHz }; + const T rc{ T{ 1 } / (T{ 2 } * std::numbers::pi_v * cutoffHz) }; + return dt / (rc + dt); + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class ExponentialMovingAverage; +#endif +} diff --git a/numerical/filters/passive/test/CMakeLists.txt b/numerical/filters/passive/test/CMakeLists.txt index d1b7fa3d..ba26e58f 100644 --- a/numerical/filters/passive/test/CMakeLists.txt +++ b/numerical/filters/passive/test/CMakeLists.txt @@ -10,6 +10,7 @@ target_link_libraries(numerical.filters.passive_test PUBLIC ) target_sources(numerical.filters.passive_test PRIVATE + TestExponentialMovingAverage.cpp TestFir.cpp TestIir.cpp ) diff --git a/numerical/filters/passive/test/TestExponentialMovingAverage.cpp b/numerical/filters/passive/test/TestExponentialMovingAverage.cpp new file mode 100644 index 00000000..18873aa0 --- /dev/null +++ b/numerical/filters/passive/test/TestExponentialMovingAverage.cpp @@ -0,0 +1,74 @@ +#include "numerical/filters/passive/ExponentialMovingAverage.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gtest/gtest.h" + +namespace +{ + class TestExponentialMovingAverage + : public ::testing::Test + { + public: + filters::passive::ExponentialMovingAverage ema{ 0.5f }; + }; +} + +TEST_F(TestExponentialMovingAverage, impulse_decays_geometrically) +{ + const float inputs[]{ 1.0f, 0.0f, 0.0f, 0.0f }; + const float expected[]{ 0.5f, 0.25f, 0.125f, 0.0625f }; + + for (int i = 0; i < 4; ++i) + EXPECT_NEAR(ema.Filter(inputs[i]), expected[i], 1e-6f); +} + +TEST_F(TestExponentialMovingAverage, constant_input_converges_to_dc) +{ + filters::passive::ExponentialMovingAverage filter{ 0.25f }; + const float c{ 0.8f }; + + float output{}; + for (int i = 0; i < 50; ++i) + output = filter.Filter(c); + + EXPECT_NEAR(output, c, math::Tolerance()); +} + +TEST_F(TestExponentialMovingAverage, alpha_one_is_passthrough) +{ + filters::passive::ExponentialMovingAverage filter{ 1.0f }; + const float inputs[]{ 0.3f, -0.7f, 1.0f, 0.0f }; + + for (const float x : inputs) + EXPECT_NEAR(filter.Filter(x), x, 1e-6f); +} + +TEST_F(TestExponentialMovingAverage, step_response_matches_time_constant) +{ + filters::passive::ExponentialMovingAverage filter{ 0.1f }; + + float output{}; + for (int i = 0; i < 10; ++i) + output = filter.Filter(1.0f); + + EXPECT_NEAR(output, 0.6513f, 1e-3f); +} + +TEST_F(TestExponentialMovingAverage, reset_clears_state) +{ + ema.Filter(1.0f); + ema.Filter(1.0f); + ema.Reset(0.0f); + + const float nextInput{ 0.6f }; + EXPECT_NEAR(ema.Filter(nextInput), 0.5f * nextInput, 1e-6f); +} + +TEST_F(TestExponentialMovingAverage, disabled_passes_through) +{ + ema.Filter(1.0f); + ema.Disable(); + + const float input{ 0.4f }; + EXPECT_NEAR(ema.Filter(input), input, 1e-6f); + EXPECT_NEAR(ema.Filter(0.9f), 0.9f, 1e-6f); +} From 7dffeeeafaef20e7d4d5c1393cda309f8d8071a6 Mon Sep 17 00:00:00 2001 From: gfs Date: Sun, 26 Jul 2026 19:06:07 +0200 Subject: [PATCH 2/3] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- ROADMAP.md | 98 ++++++++++--------- .../passive/ExponentialMovingAverage.md | 22 ++--- .../passive/ExponentialMovingAverage.hpp | 1 - 3 files changed, 61 insertions(+), 60 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 21e75fe6..7fc379f4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -25,6 +25,7 @@ Difficulty legend: ## Master list (by priority) <<<<<<< Updated upstream + | # | Component | Target module | Difficulty | |----|------------------------------------------------------|---------------------------|------------| | 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ | @@ -75,54 +76,55 @@ Difficulty legend: | 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ | | 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ | ======= -| # | Component | Target module | Difficulty | -|----|-----------|---------------|------------| -| 2 | Moving Average (running-sum boxcar) | `filters/passive` | ★☆☆☆☆ | -| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ | -| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ | -| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ | -| 6 | Median filter | `filters/passive` | ★★☆☆☆ | -| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ | -| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ | -| 9 | Complementary filter | `filters/active` | ★★☆☆☆ | -| 10 | Gain-scheduled controller | `controllers` | ★★☆☆☆ | -| 11 | Convolution & correlation utilities | `analysis` | ★★☆☆☆ | -| 12 | Polynomial least-squares curve fitting | `estimators/offline` | ★★☆☆☆ | -| 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ | -| 14 | CIC (Cascaded Integrator-Comb) filter | `filters/passive` | ★★☆☆☆ | -| 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ | -| 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ | -| 17 | Lead-lag compensator | `controllers` | ★★★☆☆ | -| 18 | Quaternion type | `math` | ★★★☆☆ | -| 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` | ★★★☆☆ | -| 25 | Real-input FFT (RFFT) | `analysis` | ★★★☆☆ | -| 26 | Controllability / Observability matrices & Gramians | `control_analysis` | ★★★☆☆ | -| 27 | QR decomposition (Householder / Givens) | `solvers` | ★★★★☆ | -| 28 | LU decomposition with partial pivoting | `solvers` | ★★★★☆ | -| 29 | Matrix exponential (scaling & squaring + Padé) | `math` | ★★★★☆ | -| 30 | Continuous → discrete conversion (`c2d`) | `math` | ★★★★☆ | -| 31 | Lyapunov / Sylvester equation solvers | `solvers` | ★★★★☆ | -| 32 | Transfer-function ↔ state-space conversion | `control_analysis` | ★★★★☆ | -| 33 | Madgwick / Mahony AHRS | `filters/active` | ★★★★☆ | -| 34 | Sliding Mode Control (SMC) | `robust_control` (new) | ★★★★☆ | -| 35 | Disturbance Observer (DOB) | `robust_control` (new) | ★★★★☆ | -| 36 | Active Disturbance Rejection Control (ADRC + ESO) | `robust_control` (new) | ★★★★☆ | -| 37 | Hilbert transform / analytic signal / envelope | `analysis` | ★★★★☆ | -| 38 | Discrete Wavelet Transform (Haar / Daubechies) | `analysis` | ★★★★☆ | -| 39 | Square-root / Information Kalman filter | `filters/active` | ★★★★☆ | -| 40 | Feedback linearization | `nonlinear_control` (new) | ★★★★☆ | -| 41 | Backstepping controller | `nonlinear_control` (new) | ★★★★☆ | -| 42 | Symmetric eigenvalue solver (Jacobi) | `solvers` | ★★★★★ | -| 43 | Singular Value Decomposition (Golub-Kahan) | `solvers` | ★★★★★ | -| 44 | Total Least Squares | `estimators/offline` | ★★★★★ | -| 45 | IIR filter design (Butterworth/Chebyshev + bilinear) | `filters/passive` | ★★★★★ | -| 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ | -| 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ | +| # | Component | Target module | Difficulty | +|----|------------------------------------------------------|---------------------------|------------| +| 2 | Moving Average (running-sum boxcar) | `filters/passive` | ★☆☆☆☆ | +| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ | +| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ | +| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ | +| 6 | Median filter | `filters/passive` | ★★☆☆☆ | +| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ | +| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ | +| 9 | Complementary filter | `filters/active` | ★★☆☆☆ | +| 10 | Gain-scheduled controller | `controllers` | ★★☆☆☆ | +| 11 | Convolution & correlation utilities | `analysis` | ★★☆☆☆ | +| 12 | Polynomial least-squares curve fitting | `estimators/offline` | ★★☆☆☆ | +| 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ | +| 14 | CIC (Cascaded Integrator-Comb) filter | `filters/passive` | ★★☆☆☆ | +| 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ | +| 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ | +| 17 | Lead-lag compensator | `controllers` | ★★★☆☆ | +| 18 | Quaternion type | `math` | ★★★☆☆ | +| 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` | ★★★☆☆ | +| 25 | Real-input FFT (RFFT) | `analysis` | ★★★☆☆ | +| 26 | Controllability / Observability matrices & Gramians | `control_analysis` | ★★★☆☆ | +| 27 | QR decomposition (Householder / Givens) | `solvers` | ★★★★☆ | +| 28 | LU decomposition with partial pivoting | `solvers` | ★★★★☆ | +| 29 | Matrix exponential (scaling & squaring + Padé) | `math` | ★★★★☆ | +| 30 | Continuous → discrete conversion (`c2d`) | `math` | ★★★★☆ | +| 31 | Lyapunov / Sylvester equation solvers | `solvers` | ★★★★☆ | +| 32 | Transfer-function ↔ state-space conversion | `control_analysis` | ★★★★☆ | +| 33 | Madgwick / Mahony AHRS | `filters/active` | ★★★★☆ | +| 34 | Sliding Mode Control (SMC) | `robust_control` (new) | ★★★★☆ | +| 35 | Disturbance Observer (DOB) | `robust_control` (new) | ★★★★☆ | +| 36 | Active Disturbance Rejection Control (ADRC + ESO) | `robust_control` (new) | ★★★★☆ | +| 37 | Hilbert transform / analytic signal / envelope | `analysis` | ★★★★☆ | +| 38 | Discrete Wavelet Transform (Haar / Daubechies) | `analysis` | ★★★★☆ | +| 39 | Square-root / Information Kalman filter | `filters/active` | ★★★★☆ | +| 40 | Feedback linearization | `nonlinear_control` (new) | ★★★★☆ | +| 41 | Backstepping controller | `nonlinear_control` (new) | ★★★★☆ | +| 42 | Symmetric eigenvalue solver (Jacobi) | `solvers` | ★★★★★ | +| 43 | Singular Value Decomposition (Golub-Kahan) | `solvers` | ★★★★★ | +| 44 | Total Least Squares | `estimators/offline` | ★★★★★ | +| 45 | IIR filter design (Butterworth/Chebyshev + bilinear) | `filters/passive` | ★★★★★ | +| 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ | +| 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ | + >>>>>>> Stashed changes --- diff --git a/doc/filters/passive/ExponentialMovingAverage.md b/doc/filters/passive/ExponentialMovingAverage.md index 4a7f89c8..773511ce 100644 --- a/doc/filters/passive/ExponentialMovingAverage.md +++ b/doc/filters/passive/ExponentialMovingAverage.md @@ -60,22 +60,22 @@ hence the name "exponential" moving average. ## Complexity Analysis -| Case | Time | Space | Notes | -|---------|--------|--------|-----------------------------------------| -| Best | O(1) | O(1) | Single MAC per sample, one state word | -| Average | O(1) | O(1) | Identical regardless of input | -| Worst | O(1) | O(1) | No data-dependent branches on hot path | +| Case | Time | Space | Notes | +|---------|------|-------|----------------------------------------| +| Best | O(1) | O(1) | Single MAC per sample, one state word | +| Average | O(1) | O(1) | Identical regardless of input | +| Worst | O(1) | O(1) | No data-dependent branches on hot path | ## Step-by-Step Walkthrough Suppose $\alpha = 0.5$, $y[-1] = 0$, and the input is the unit impulse $x = [1, 0, 0, 0, \ldots]$. -| $n$ | $x[n]$ | $x[n] - y[n-1]$ | $\alpha \cdot \Delta$ | $y[n]$ | -|-----|--------|------------------|-----------------------|---------| -| 0 | 1 | $1 - 0 = 1$ | $0.5$ | $0.5$ | -| 1 | 0 | $0 - 0.5 = -0.5$ | $-0.25$ | $0.25$ | -| 2 | 0 | $0 - 0.25 = -0.25$| $-0.125$ | $0.125$ | -| 3 | 0 | $0 - 0.125 = -0.125$| $-0.0625$ | $0.0625$| +| $n$ | $x[n]$ | $x[n] - y[n-1]$ | $\alpha \cdot \Delta$ | $y[n]$ | +|-----|--------|----------------------|-----------------------|----------| +| 0 | 1 | $1 - 0 = 1$ | $0.5$ | $0.5$ | +| 1 | 0 | $0 - 0.5 = -0.5$ | $-0.25$ | $0.25$ | +| 2 | 0 | $0 - 0.25 = -0.25$ | $-0.125$ | $0.125$ | +| 3 | 0 | $0 - 0.125 = -0.125$ | $-0.0625$ | $0.0625$ | Each output is half the previous, confirming $h[n] = (0.5)^{n+1}$. diff --git a/numerical/filters/passive/ExponentialMovingAverage.hpp b/numerical/filters/passive/ExponentialMovingAverage.hpp index 8420fa1b..2397b6e4 100644 --- a/numerical/filters/passive/ExponentialMovingAverage.hpp +++ b/numerical/filters/passive/ExponentialMovingAverage.hpp @@ -5,7 +5,6 @@ #endif #include "numerical/math/CompilerOptimizations.hpp" - #include #include #include From 8e9a25abe73d1cd5981f5701f384907c39bf4ee7 Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sun, 26 Jul 2026 17:32:11 +0000 Subject: [PATCH 3/3] fix build --- .../passive/ExponentialMovingAverage.hpp | 18 ----- .../test/TestExponentialMovingAverage.cpp | 16 +++-- .../ExponentialMovingAverage/explanation.md | 27 -------- .../implementation.md | 66 ------------------- .../passive/ExponentialMovingAverage/tests.md | 51 -------------- 5 files changed, 11 insertions(+), 167 deletions(-) delete mode 100644 roadmap/filters/passive/ExponentialMovingAverage/explanation.md delete mode 100644 roadmap/filters/passive/ExponentialMovingAverage/implementation.md delete mode 100644 roadmap/filters/passive/ExponentialMovingAverage/tests.md diff --git a/numerical/filters/passive/ExponentialMovingAverage.hpp b/numerical/filters/passive/ExponentialMovingAverage.hpp index 8420fa1b..beeb6265 100644 --- a/numerical/filters/passive/ExponentialMovingAverage.hpp +++ b/numerical/filters/passive/ExponentialMovingAverage.hpp @@ -7,7 +7,6 @@ #include "numerical/math/CompilerOptimizations.hpp" #include -#include #include #include @@ -24,15 +23,12 @@ namespace filters::passive OPTIMIZE_FOR_SPEED T Filter(T input) noexcept; void Reset(T value = T{}) noexcept; void SetAlpha(T alpha) noexcept; - void Enable() noexcept; - void Disable() noexcept; static T AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept; private: T alpha; T state; - bool enabled{ true }; }; //// Implementation //// @@ -48,8 +44,6 @@ namespace filters::passive template OPTIMIZE_FOR_SPEED T ExponentialMovingAverage::Filter(T input) noexcept { - if (!enabled) [[unlikely]] - return input; state = state + alpha * (input - state); return state; } @@ -67,18 +61,6 @@ namespace filters::passive alpha = newAlpha; } - template - void ExponentialMovingAverage::Enable() noexcept - { - enabled = true; - } - - template - void ExponentialMovingAverage::Disable() noexcept - { - enabled = false; - } - template T ExponentialMovingAverage::AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept { diff --git a/numerical/filters/passive/test/TestExponentialMovingAverage.cpp b/numerical/filters/passive/test/TestExponentialMovingAverage.cpp index 18873aa0..7de547e1 100644 --- a/numerical/filters/passive/test/TestExponentialMovingAverage.cpp +++ b/numerical/filters/passive/test/TestExponentialMovingAverage.cpp @@ -63,12 +63,18 @@ TEST_F(TestExponentialMovingAverage, reset_clears_state) EXPECT_NEAR(ema.Filter(nextInput), 0.5f * nextInput, 1e-6f); } -TEST_F(TestExponentialMovingAverage, disabled_passes_through) +TEST_F(TestExponentialMovingAverage, set_alpha_changes_smoothing) { ema.Filter(1.0f); - ema.Disable(); + ema.SetAlpha(1.0f); - const float input{ 0.4f }; - EXPECT_NEAR(ema.Filter(input), input, 1e-6f); - EXPECT_NEAR(ema.Filter(0.9f), 0.9f, 1e-6f); + EXPECT_NEAR(ema.Filter(0.0f), 0.0f, 1e-6f); +} + +TEST_F(TestExponentialMovingAverage, alpha_from_cutoff_produces_valid_alpha) +{ + const float alpha{ filters::passive::ExponentialMovingAverage::AlphaFromCutoff(100.0f, 1000.0f) }; + EXPECT_GT(alpha, 0.0f); + EXPECT_LE(alpha, 1.0f); + EXPECT_NEAR(alpha, 0.3859f, 1e-3f); } diff --git a/roadmap/filters/passive/ExponentialMovingAverage/explanation.md b/roadmap/filters/passive/ExponentialMovingAverage/explanation.md deleted file mode 100644 index b26dcd95..00000000 --- a/roadmap/filters/passive/ExponentialMovingAverage/explanation.md +++ /dev/null @@ -1,27 +0,0 @@ -# Exponential Moving Average — Overview - -## What it is -A single-pole recursive low-pass filter (a.k.a. leaky integrator). Each output is a weighted -blend of the newest sample and the previous output: `y[n] = α·x[n] + (1−α)·y[n−1]`. - -## Why it matters (embedded) -It is the cheapest useful smoother in existence — **one multiply, one add, one state word**. -Ubiquitous for de-noising sensor readings, tracking a slowly-moving DC level, and computing -running averages where a full moving-average buffer would cost too much RAM. - -## How it works (intuition) -`α` sets the trade-off between smoothing and responsiveness. Small `α` → heavy smoothing, slow -to react; large `α` → light smoothing, fast to react. The filter has an exponentially-decaying -impulse response, hence the name. Its `−3 dB` cutoff maps directly to `α` via the first-order -RC equivalence. - -## Key parameters -- **α (smoothing factor)** ∈ (0, 1] — or equivalently a cutoff frequency via `AlphaFromCutoff`. -- **initial state** — seed value to avoid a startup transient. - -## Reference -S. W. Smith, *The Scientist and Engineer's Guide to Digital Signal Processing*, Ch. 19 -(Recursive / single-pole filters). - -## See also -`MovingAverage` (linear-phase alternative), `BiquadCascade` (higher-order roll-off). diff --git a/roadmap/filters/passive/ExponentialMovingAverage/implementation.md b/roadmap/filters/passive/ExponentialMovingAverage/implementation.md deleted file mode 100644 index e6fd7d7a..00000000 --- a/roadmap/filters/passive/ExponentialMovingAverage/implementation.md +++ /dev/null @@ -1,66 +0,0 @@ -# Exponential Moving Average (One-Pole) — Implementation Pseudocode - -> Roadmap ref: #1 (Tier 1) · Target: `numerical/filters/passive` · Namespace `filters::passive` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class ExponentialMovingAverage: - T alpha # smoothing factor in (0, 1] - T state # last output y[n-1] - bool enabled = true -``` - -## Interface - -``` -ExponentialMovingAverage(T alpha, T initial = 0) -T Filter(T input) # hot path -void Reset(T value = 0) -void SetAlpha(T alpha) -void Enable() / Disable() -static T AlphaFromCutoff(T cutoffHz, T sampleRateHz) -``` - -## Algorithm (pseudocode) - -``` -function Filter(x): # OPTIMIZE_FOR_SPEED - if not enabled: return x - # y[n] = alpha*x[n] + (1 - alpha)*y[n-1] - state = state + alpha * (x - state) # one MAC, rearranged to avoid (1-alpha) term - return state - -function AlphaFromCutoff(fc, fs): - # first-order RC equivalent - dt = 1 / fs - rc = 1 / (2*pi*fc) - return dt / (rc + dt) -``` - -## Complexity & memory - -- Time: `O(1)` per sample (1 multiply, 1 add/sub for the rearranged form). -- Memory: `O(1)` — a single state word plus the coefficient. - -## Numerical / embedded notes - -- `alpha ∈ (0,1]`; the pole `1-alpha` stays inside the unit circle ⇒ unconditionally stable. -- Rearranged update `state += alpha*(x-state)` keeps a single multiply on the hot path. -- DC gain is exactly 1 (a constant input converges to that constant). -- Float-only: `static_assert(std::is_floating_point_v)`; the generic `T` signature lets a - `Q15`/`Q31` specialisation be added later without changing call sites. - -## Deployment - -- Header: `numerical/filters/passive/ExponentialMovingAverage.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Filter`, and - `extern template class ExponentialMovingAverage;` under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/filters/passive/ExponentialMovingAverage.cpp` → - `template class ExponentialMovingAverage;` -- Test: `numerical/filters/passive/test/TestExponentialMovingAverage.cpp` -- Doc: `doc/filters/passive/ExponentialMovingAverage.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestExponentialMovingAverage.cpp` → the `_test` target. -- Generic pattern: see `roadmap/README.md` → "Deployment shape". diff --git a/roadmap/filters/passive/ExponentialMovingAverage/tests.md b/roadmap/filters/passive/ExponentialMovingAverage/tests.md deleted file mode 100644 index 1f9898c3..00000000 --- a/roadmap/filters/passive/ExponentialMovingAverage/tests.md +++ /dev/null @@ -1,51 +0,0 @@ -# Exponential Moving Average — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestExponentialMovingAverage : public ::testing::Test: - ExponentialMovingAverage ema{ 0.5f } # alpha = 0.5 default -# each case below is a TEST_F(TestExponentialMovingAverage, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -impulse_decays_geometrically: - Arrange: alpha = 0.5, input = [1, 0, 0, 0] - Act: collect y for each sample - Assert: y ≈ [0.5, 0.25, 0.125, 0.0625] (EXPECT_NEAR, tol 1e-6f) - -constant_input_converges_to_dc: - Arrange: alpha = 0.25, feed constant c = 0.8 for 50 samples - Assert: final output ≈ 0.8 (unity DC gain) - -alpha_one_is_passthrough: - Arrange: alpha = 1.0 - Assert: Filter(x) == x for a sequence - -step_response_matches_time_constant: - Arrange: alpha = 0.1, step from 0 -> 1 - Assert: after ~1 time-constant, output ≈ 0.63 (±tol) - -reset_clears_state: - Arrange: run some samples, Reset(0) - Assert: next output == alpha * next_input - -disabled_passes_through: - Arrange: Disable() - Assert: Filter(x) == x, state unchanged -``` - -## Reference vectors - -- `alpha = 0.5`, unit impulse ⇒ `y[n] = 0.5^(n+1)`. -- `alpha = 0.5`, unit step ⇒ `y[n] = 1 - 0.5^(n+1)`. - -## Edge cases - -- `alpha` at bounds (→0 very slow, =1 passthrough). -- Near-zero and unity `alpha` remain numerically stable. -- Long constant-input run converges to the DC value without drift.