diff --git a/AGENTS.md b/AGENTS.md index f4e41517..6a8d7342 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,6 +60,8 @@ resource-constrained embedded systems. Real-time, deterministic, no heap. - **`StrictMock` only** (no `NiceMock`/bare). Fixture + aliases in an anonymous namespace; macros outside it. - **No redundant tests** — implement exactly the spec's enumerated cases, one behavior per test, Arrange/Act/Assert, `EXPECT_NEAR` + `math::Tolerance()`. No heap. +- **Coverage ≥ 90 %** — measured by SonarQube. Every new algorithm must reach this threshold + before merge; CI fails below it. ## CMake (numerical/ targets) diff --git a/README.md b/README.md index 277bb241..5fa99af6 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, 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..500d6847 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -27,7 +27,6 @@ Difficulty legend: | # | Component | Target module | Difficulty | |----|------------------------------------------------------|---------------------------|------------| | 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ | -| 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` | ★☆☆☆☆ | diff --git a/doc/filters/passive/MovingAverage.md b/doc/filters/passive/MovingAverage.md new file mode 100644 index 00000000..36b981ca --- /dev/null +++ b/doc/filters/passive/MovingAverage.md @@ -0,0 +1,103 @@ +# Moving Average (Running-Sum Boxcar) + +## Overview & Motivation + +Sensor streams in embedded systems are corrupted by zero-mean white noise. The simplest way to +attenuate that noise is to average consecutive samples. The moving average does this with a sliding +window of length N, treating every sample inside the window equally. Its critical property for +embedded use is that the recursive running-sum form requires exactly one addition, one subtraction, +and one multiply per output sample — constant work regardless of how large the window is. + +## Mathematical Theory + +### Core Definitions + +Let $x[n]$ be the input sequence. The length-$N$ boxcar output is: + +$$y[n] = \frac{1}{N} \sum_{k=0}^{N-1} x[n-k]$$ + +### Recursive Form + +Expanding $y[n]$ in terms of $y[n-1]$: + +$$y[n] = y[n-1] + \frac{x[n] - x[n-N]}{N}$$ + +Equivalently, maintain a running sum $S[n] = \sum_{k=0}^{N-1} x[n-k]$: + +$$S[n] = S[n-1] + x[n] - x[n-N], \qquad y[n] = \frac{S[n]}{N}$$ + +### Frequency Response + +The discrete-time transfer function is: + +$$H(z) = \frac{1}{N} \sum_{k=0}^{N-1} z^{-k} = \frac{1}{N} \cdot \frac{1 - z^{-N}}{1 - z^{-1}}$$ + +The magnitude response is a $\mathrm{sinc}$-shaped envelope: + +$$|H(e^{j\omega})| = \frac{1}{N} \left| \frac{\sin(N\omega/2)}{\sin(\omega/2)} \right|$$ + +DC gain is exactly 1. Group delay is constant at $(N-1)/2$ samples — the filter is linear phase. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|------|--------|--------|--------------------------------| +| All | $O(1)$ | $O(N)$ | One add, one sub, one multiply | + +The $O(1)$ time cost is the key advantage over the naive $O(N)$ direct-form sum. + +## Step-by-Step Walkthrough + +Input: unit step $x[n] = 1$ for $n \ge 0$, $N = 4$, initial state all zeros. + +| $n$ | $x[n]$ | $x[n-4]$ | $S[n]$ | $y[n]$ | +|-----|--------|----------|--------|--------| +| 0 | 1 | 0 | 1 | 0.25 | +| 1 | 1 | 0 | 2 | 0.50 | +| 2 | 1 | 0 | 3 | 0.75 | +| 3 | 1 | 0 | 4 | 1.00 | +| 4 | 1 | 1 | 4 | 1.00 | + +The output ramps up linearly and then holds at 1 once the window is fully filled. + +## Pitfalls & Edge Cases + +- **Running-sum drift**: floating-point rounding accumulates in $S[n]$ over long constant runs. + For very long sequences, periodically recompute the sum directly from the window contents. +- **Startup transient**: the first $N-1$ outputs are averages of fewer than $N$ samples unless the + window is pre-filled with an initial value. +- **Window length 1**: reduces to pass-through — no smoothing occurs. +- **Poor frequency selectivity**: sidelobes in the stopband are only $-13\,\mathrm{dB}$ below the + passband; use a Biquad cascade when sharp roll-off is needed. + +## Variants & Generalizations + +- **Weighted moving average** (triangular, Gaussian): tap weights are no longer uniform; loses the + $O(1)$ recursive property. +- **Exponential moving average (EMA)**: an IIR approximation requiring only one multiply-add and no + delay line; trades linear phase for lower memory cost. +- **Savitzky-Golay filter**: fits a polynomial to the window, preserving peak shapes while + smoothing — higher computational cost. +- **CIC filter**: cascaded integrator-comb, a multi-stage generalization used for decimation. + +## Applications + +- ADC noise reduction on sensor streams (accelerometers, temperature, pressure). +- Decimation pre-filter before down-sampling. +- Smoothing control-loop feedback signals to suppress high-frequency switching artifacts. +- Baseline/trend estimation when a flat passband and linear phase are required. + +## Connections to Other Algorithms + +- The FIR filter with uniform coefficients $b_k = 1/N$ is mathematically identical; this + implementation exploits the uniformity for $O(1)$ computation. +- `ExponentialMovingAverage` solves the same smoothing problem with $O(1)$ memory at the cost of + non-linear phase and an infinite impulse response. +- `SavitzkyGolayFilter` generalizes the boxcar by fitting a polynomial, preserving higher-order + signal features. + +## References & Further Reading + +- S. W. Smith, *The Scientist and Engineer's Guide to Digital Signal Processing*, Ch. 15 — + Moving Average Filters (recursive running-sum form). Available at dspguide.com. +- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., §7.5. diff --git a/numerical/filters/passive/CMakeLists.txt b/numerical/filters/passive/CMakeLists.txt index ab608c11..cece52d3 100644 --- a/numerical/filters/passive/CMakeLists.txt +++ b/numerical/filters/passive/CMakeLists.txt @@ -13,11 +13,13 @@ target_link_libraries(numerical.filters.passive ${NUMERICAL_VISIBILITY} target_sources(numerical.filters.passive PRIVATE Fir.hpp Iir.hpp + MovingAverage.hpp ) numerical_add_coverage_sources(numerical.filters.passive Fir.cpp Iir.cpp + MovingAverage.cpp ) add_subdirectory(test) diff --git a/numerical/filters/passive/MovingAverage.cpp b/numerical/filters/passive/MovingAverage.cpp new file mode 100644 index 00000000..2e181294 --- /dev/null +++ b/numerical/filters/passive/MovingAverage.cpp @@ -0,0 +1,6 @@ +#include "numerical/filters/passive/MovingAverage.hpp" + +namespace filters::passive +{ + template class MovingAverage; +} diff --git a/numerical/filters/passive/MovingAverage.hpp b/numerical/filters/passive/MovingAverage.hpp new file mode 100644 index 00000000..6ecf607d --- /dev/null +++ b/numerical/filters/passive/MovingAverage.hpp @@ -0,0 +1,65 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/RecursiveBuffer.hpp" + +namespace filters::passive +{ + template + class MovingAverage + { + static_assert(std::is_floating_point_v, "MovingAverage supports floating-point types"); + + public: + explicit MovingAverage(T initial = T{}) noexcept; + + OPTIMIZE_FOR_SPEED T Filter(T input) noexcept; + void Reset(T value = T{}) noexcept; + + private: + math::RecursiveBuffer window; + T sum; + T invN; + + [[no_unique_address]] math::Index n; + }; + + template + MovingAverage::MovingAverage(T initial) noexcept + : sum{ initial * static_cast(N) } + , invN{ T{ 1 } / static_cast(N) } + { + for (std::size_t i = 0; i < N; ++i) + window.Update(initial); + } + + template + OPTIMIZE_FOR_SPEED T MovingAverage::Filter(T input) noexcept + { + T oldest = window[n - static_cast(N - 1)]; + sum = sum + input - oldest; + window.Update(input); + return sum * invN; + } + + template + void MovingAverage::Reset(T value) noexcept + { + window.Reset(); + sum = T{}; + if (value != T{}) + { + for (std::size_t i = 0; i < N; ++i) + window.Update(value); + sum = value * static_cast(N); + } + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class MovingAverage; +#endif +} diff --git a/numerical/filters/passive/test/CMakeLists.txt b/numerical/filters/passive/test/CMakeLists.txt index d1b7fa3d..4acdd417 100644 --- a/numerical/filters/passive/test/CMakeLists.txt +++ b/numerical/filters/passive/test/CMakeLists.txt @@ -12,4 +12,5 @@ target_link_libraries(numerical.filters.passive_test PUBLIC target_sources(numerical.filters.passive_test PRIVATE TestFir.cpp TestIir.cpp + TestMovingAverage.cpp ) diff --git a/numerical/filters/passive/test/TestMovingAverage.cpp b/numerical/filters/passive/test/TestMovingAverage.cpp new file mode 100644 index 00000000..cac422ce --- /dev/null +++ b/numerical/filters/passive/test/TestMovingAverage.cpp @@ -0,0 +1,83 @@ +#include "numerical/filters/passive/MovingAverage.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gtest/gtest.h" + +namespace +{ + class TestMovingAverage + : public ::testing::Test + { + public: + filters::passive::MovingAverage ma{}; + }; +} + +TEST_F(TestMovingAverage, warmup_fills_window) +{ + constexpr float tol = 1e-6f; + EXPECT_NEAR(ma.Filter(1.0f), 0.25f, tol); + EXPECT_NEAR(ma.Filter(0.0f), 0.25f, tol); + EXPECT_NEAR(ma.Filter(0.0f), 0.25f, tol); + EXPECT_NEAR(ma.Filter(0.0f), 0.25f, tol); +} + +TEST_F(TestMovingAverage, constant_input_unity_gain) +{ + constexpr float tol = 1e-6f; + constexpr float c = 0.5f; + for (int i = 0; i < 8; ++i) + ma.Filter(c); + EXPECT_NEAR(ma.Filter(c), c, tol); +} + +TEST_F(TestMovingAverage, step_response_is_linear_ramp) +{ + constexpr float tol = 1e-6f; + EXPECT_NEAR(ma.Filter(1.0f), 0.25f, tol); + EXPECT_NEAR(ma.Filter(1.0f), 0.50f, tol); + EXPECT_NEAR(ma.Filter(1.0f), 0.75f, tol); + EXPECT_NEAR(ma.Filter(1.0f), 1.00f, tol); + EXPECT_NEAR(ma.Filter(1.0f), 1.00f, tol); +} + +TEST_F(TestMovingAverage, running_sum_matches_direct_average) +{ + constexpr float tol = 1e-6f; + constexpr std::array seq{ 0.1f, 0.4f, 0.9f, 0.2f, 0.7f, 0.3f, 0.5f, 0.8f }; + std::array outputs{}; + for (std::size_t i = 0; i < seq.size(); ++i) + outputs[i] = ma.Filter(seq[i]); + + for (std::size_t i = 3; i < seq.size(); ++i) + { + float brute = (seq[i] + seq[i - 1] + seq[i - 2] + seq[i - 3]) * 0.25f; + EXPECT_NEAR(outputs[i], brute, tol); + } +} + +TEST_F(TestMovingAverage, impulse_leaves_after_N) +{ + constexpr float tol = 1e-6f; + ma.Filter(1.0f); + ma.Filter(0.0f); + ma.Filter(0.0f); + ma.Filter(0.0f); + EXPECT_NEAR(ma.Filter(0.0f), 0.0f, tol); + EXPECT_NEAR(ma.Filter(0.0f), 0.0f, tol); +} + +TEST_F(TestMovingAverage, reset_clears_state) +{ + constexpr float tol = 1e-6f; + ma.Filter(1.0f); + ma.Filter(1.0f); + ma.Reset(); + EXPECT_NEAR(ma.Filter(1.0f), 0.25f, tol); +} + +TEST_F(TestMovingAverage, reset_with_value_prefills_window) +{ + constexpr float tol = 1e-6f; + ma.Reset(2.0f); + EXPECT_NEAR(ma.Filter(2.0f), 2.0f, tol); +}