Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -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, Moving Average |
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Exponential Moving Average, 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 |
Expand Down
53 changes: 53 additions & 0 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Difficulty legend:

## Master list (by priority)

<<<<<<< Updated upstream

| # | Component | Target module | Difficulty |
|----|------------------------------------------------------|---------------------------|------------|
| 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ |
Expand Down Expand Up @@ -72,6 +74,57 @@ 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

---

Expand Down
128 changes: 128 additions & 0 deletions doc/filters/passive/ExponentialMovingAverage.md
Original file line number Diff line number Diff line change
@@ -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).
2 changes: 2 additions & 0 deletions numerical/filters/passive/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ target_link_libraries(numerical.filters.passive ${NUMERICAL_VISIBILITY}
)

target_sources(numerical.filters.passive PRIVATE
ExponentialMovingAverage.hpp
Fir.hpp
Iir.hpp
MovingAverage.hpp
)

numerical_add_coverage_sources(numerical.filters.passive
ExponentialMovingAverage.cpp
Fir.cpp
Iir.cpp
MovingAverage.cpp
Expand Down
6 changes: 6 additions & 0 deletions numerical/filters/passive/ExponentialMovingAverage.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#include "numerical/filters/passive/ExponentialMovingAverage.hpp"

namespace filters::passive
{
template class ExponentialMovingAverage<float>;
}
74 changes: 74 additions & 0 deletions numerical/filters/passive/ExponentialMovingAverage.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#pragma once

#if defined(__GNUC__) || defined(__clang__)
#pragma GCC optimize("O3", "fast-math")
#endif

#include "numerical/math/CompilerOptimizations.hpp"
#include <cassert>
#include <numbers>
#include <type_traits>

namespace filters::passive
{
template<typename T>
class ExponentialMovingAverage
{
static_assert(std::is_floating_point_v<T>, "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;

static T AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept;

private:
T alpha;
T state;
};

//// Implementation ////

template<typename T>
ExponentialMovingAverage<T>::ExponentialMovingAverage(T alpha, T initial) noexcept
: alpha{ alpha }
, state{ initial }
{
assert(alpha > T{} && alpha <= T{ 1 });
}

template<typename T>
OPTIMIZE_FOR_SPEED T ExponentialMovingAverage<T>::Filter(T input) noexcept
{
state = state + alpha * (input - state);
return state;
}

template<typename T>
void ExponentialMovingAverage<T>::Reset(T value) noexcept
{
state = value;
}

template<typename T>
void ExponentialMovingAverage<T>::SetAlpha(T newAlpha) noexcept
{
assert(newAlpha > T{} && newAlpha <= T{ 1 });
alpha = newAlpha;
}

template<typename T>
T ExponentialMovingAverage<T>::AlphaFromCutoff(T cutoffHz, T sampleRateHz) noexcept
{
const T dt{ T{ 1 } / sampleRateHz };
const T rc{ T{ 1 } / (T{ 2 } * std::numbers::pi_v<T> * cutoffHz) };
return dt / (rc + dt);
}

#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
extern template class ExponentialMovingAverage<float>;
#endif
}
1 change: 1 addition & 0 deletions numerical/filters/passive/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
TestMovingAverage.cpp
Expand Down
80 changes: 80 additions & 0 deletions numerical/filters/passive/test/TestExponentialMovingAverage.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#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<float> 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<float> 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<float>());
}

TEST_F(TestExponentialMovingAverage, alpha_one_is_passthrough)
{
filters::passive::ExponentialMovingAverage<float> 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<float> 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, set_alpha_changes_smoothing)
{
ema.Filter(1.0f);
ema.SetAlpha(1.0f);

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<float>::AlphaFromCutoff(100.0f, 1000.0f) };
EXPECT_GT(alpha, 0.0f);
EXPECT_LE(alpha, 1.0f);
EXPECT_NEAR(alpha, 0.3859f, 1e-3f);
}
Loading
Loading