Skip to content

Commit ed9b147

Browse files
feat: add moving average filter (#165)
* add moving average 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 bab29ac commit ed9b147

9 files changed

Lines changed: 263 additions & 2 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ resource-constrained embedded systems. Real-time, deterministic, no heap.
6060
- **`StrictMock` only** (no `NiceMock`/bare). Fixture + aliases in an anonymous namespace; macros outside it.
6161
- **No redundant tests** — implement exactly the spec's enumerated cases, one behavior per test,
6262
Arrange/Act/Assert, `EXPECT_NEAR` + `math::Tolerance<float>()`. No heap.
63+
- **Coverage ≥ 90 %** — measured by SonarQube. Every new algorithm must reach this threshold
64+
before merge; CI fails below it.
6365

6466
## CMake (numerical/ targets)
6567

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
2121
| [Controllers](doc/controllers/README.md) | PID, LQR, MPC |
2222
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |
2323
| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker (offline), Recursive Least Squares (online) |
24-
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR |
24+
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Moving Average |
2525
| [Kinematics](doc/kinematics/README.md) | Forward Kinematics |
2626
| [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, model |
2727
| [Optimization](doc/optimization/README.md) | Gradient Descent |

‎ROADMAP.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ Difficulty legend:
2727
| # | Component | Target module | Difficulty |
2828
|----|------------------------------------------------------|---------------------------|------------|
2929
| 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ |
30-
| 2 | Moving Average (running-sum boxcar) | `filters/passive` | ★☆☆☆☆ |
3130
| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ |
3231
| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ |
3332
| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ |
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Moving Average (Running-Sum Boxcar)
2+
3+
## Overview & Motivation
4+
5+
Sensor streams in embedded systems are corrupted by zero-mean white noise. The simplest way to
6+
attenuate that noise is to average consecutive samples. The moving average does this with a sliding
7+
window of length N, treating every sample inside the window equally. Its critical property for
8+
embedded use is that the recursive running-sum form requires exactly one addition, one subtraction,
9+
and one multiply per output sample — constant work regardless of how large the window is.
10+
11+
## Mathematical Theory
12+
13+
### Core Definitions
14+
15+
Let $x[n]$ be the input sequence. The length-$N$ boxcar output is:
16+
17+
$$y[n] = \frac{1}{N} \sum_{k=0}^{N-1} x[n-k]$$
18+
19+
### Recursive Form
20+
21+
Expanding $y[n]$ in terms of $y[n-1]$:
22+
23+
$$y[n] = y[n-1] + \frac{x[n] - x[n-N]}{N}$$
24+
25+
Equivalently, maintain a running sum $S[n] = \sum_{k=0}^{N-1} x[n-k]$:
26+
27+
$$S[n] = S[n-1] + x[n] - x[n-N], \qquad y[n] = \frac{S[n]}{N}$$
28+
29+
### Frequency Response
30+
31+
The discrete-time transfer function is:
32+
33+
$$H(z) = \frac{1}{N} \sum_{k=0}^{N-1} z^{-k} = \frac{1}{N} \cdot \frac{1 - z^{-N}}{1 - z^{-1}}$$
34+
35+
The magnitude response is a $\mathrm{sinc}$-shaped envelope:
36+
37+
$$|H(e^{j\omega})| = \frac{1}{N} \left| \frac{\sin(N\omega/2)}{\sin(\omega/2)} \right|$$
38+
39+
DC gain is exactly 1. Group delay is constant at $(N-1)/2$ samples — the filter is linear phase.
40+
41+
## Complexity Analysis
42+
43+
| Case | Time | Space | Notes |
44+
|------|--------|--------|--------------------------------|
45+
| All | $O(1)$ | $O(N)$ | One add, one sub, one multiply |
46+
47+
The $O(1)$ time cost is the key advantage over the naive $O(N)$ direct-form sum.
48+
49+
## Step-by-Step Walkthrough
50+
51+
Input: unit step $x[n] = 1$ for $n \ge 0$, $N = 4$, initial state all zeros.
52+
53+
| $n$ | $x[n]$ | $x[n-4]$ | $S[n]$ | $y[n]$ |
54+
|-----|--------|----------|--------|--------|
55+
| 0 | 1 | 0 | 1 | 0.25 |
56+
| 1 | 1 | 0 | 2 | 0.50 |
57+
| 2 | 1 | 0 | 3 | 0.75 |
58+
| 3 | 1 | 0 | 4 | 1.00 |
59+
| 4 | 1 | 1 | 4 | 1.00 |
60+
61+
The output ramps up linearly and then holds at 1 once the window is fully filled.
62+
63+
## Pitfalls & Edge Cases
64+
65+
- **Running-sum drift**: floating-point rounding accumulates in $S[n]$ over long constant runs.
66+
For very long sequences, periodically recompute the sum directly from the window contents.
67+
- **Startup transient**: the first $N-1$ outputs are averages of fewer than $N$ samples unless the
68+
window is pre-filled with an initial value.
69+
- **Window length 1**: reduces to pass-through — no smoothing occurs.
70+
- **Poor frequency selectivity**: sidelobes in the stopband are only $-13\,\mathrm{dB}$ below the
71+
passband; use a Biquad cascade when sharp roll-off is needed.
72+
73+
## Variants & Generalizations
74+
75+
- **Weighted moving average** (triangular, Gaussian): tap weights are no longer uniform; loses the
76+
$O(1)$ recursive property.
77+
- **Exponential moving average (EMA)**: an IIR approximation requiring only one multiply-add and no
78+
delay line; trades linear phase for lower memory cost.
79+
- **Savitzky-Golay filter**: fits a polynomial to the window, preserving peak shapes while
80+
smoothing — higher computational cost.
81+
- **CIC filter**: cascaded integrator-comb, a multi-stage generalization used for decimation.
82+
83+
## Applications
84+
85+
- ADC noise reduction on sensor streams (accelerometers, temperature, pressure).
86+
- Decimation pre-filter before down-sampling.
87+
- Smoothing control-loop feedback signals to suppress high-frequency switching artifacts.
88+
- Baseline/trend estimation when a flat passband and linear phase are required.
89+
90+
## Connections to Other Algorithms
91+
92+
- The FIR filter with uniform coefficients $b_k = 1/N$ is mathematically identical; this
93+
implementation exploits the uniformity for $O(1)$ computation.
94+
- `ExponentialMovingAverage` solves the same smoothing problem with $O(1)$ memory at the cost of
95+
non-linear phase and an infinite impulse response.
96+
- `SavitzkyGolayFilter` generalizes the boxcar by fitting a polynomial, preserving higher-order
97+
signal features.
98+
99+
## References & Further Reading
100+
101+
- S. W. Smith, *The Scientist and Engineer's Guide to Digital Signal Processing*, Ch. 15 —
102+
Moving Average Filters (recursive running-sum form). Available at dspguide.com.
103+
- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., §7.5.

‎numerical/filters/passive/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,13 @@ target_link_libraries(numerical.filters.passive ${NUMERICAL_VISIBILITY}
1313
target_sources(numerical.filters.passive PRIVATE
1414
Fir.hpp
1515
Iir.hpp
16+
MovingAverage.hpp
1617
)
1718

1819
numerical_add_coverage_sources(numerical.filters.passive
1920
Fir.cpp
2021
Iir.cpp
22+
MovingAverage.cpp
2123
)
2224

2325
add_subdirectory(test)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#include "numerical/filters/passive/MovingAverage.hpp"
2+
3+
namespace filters::passive
4+
{
5+
template class MovingAverage<float, 4>;
6+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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 "numerical/math/RecursiveBuffer.hpp"
9+
10+
namespace filters::passive
11+
{
12+
template<typename T, std::size_t N>
13+
class MovingAverage
14+
{
15+
static_assert(std::is_floating_point_v<T>, "MovingAverage supports floating-point types");
16+
17+
public:
18+
explicit MovingAverage(T initial = T{}) noexcept;
19+
20+
OPTIMIZE_FOR_SPEED T Filter(T input) noexcept;
21+
void Reset(T value = T{}) noexcept;
22+
23+
private:
24+
math::RecursiveBuffer<T, N> window;
25+
T sum;
26+
T invN;
27+
28+
[[no_unique_address]] math::Index n;
29+
};
30+
31+
template<typename T, std::size_t N>
32+
MovingAverage<T, N>::MovingAverage(T initial) noexcept
33+
: sum{ initial * static_cast<T>(N) }
34+
, invN{ T{ 1 } / static_cast<T>(N) }
35+
{
36+
for (std::size_t i = 0; i < N; ++i)
37+
window.Update(initial);
38+
}
39+
40+
template<typename T, std::size_t N>
41+
OPTIMIZE_FOR_SPEED T MovingAverage<T, N>::Filter(T input) noexcept
42+
{
43+
T oldest = window[n - static_cast<int32_t>(N - 1)];
44+
sum = sum + input - oldest;
45+
window.Update(input);
46+
return sum * invN;
47+
}
48+
49+
template<typename T, std::size_t N>
50+
void MovingAverage<T, N>::Reset(T value) noexcept
51+
{
52+
window.Reset();
53+
sum = T{};
54+
if (value != T{})
55+
{
56+
for (std::size_t i = 0; i < N; ++i)
57+
window.Update(value);
58+
sum = value * static_cast<T>(N);
59+
}
60+
}
61+
62+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
63+
extern template class MovingAverage<float, 4>;
64+
#endif
65+
}

‎numerical/filters/passive/test/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ target_link_libraries(numerical.filters.passive_test PUBLIC
1212
target_sources(numerical.filters.passive_test PRIVATE
1313
TestFir.cpp
1414
TestIir.cpp
15+
TestMovingAverage.cpp
1516
)
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include "numerical/filters/passive/MovingAverage.hpp"
2+
#include "numerical/math/Tolerance.hpp"
3+
#include "gtest/gtest.h"
4+
5+
namespace
6+
{
7+
class TestMovingAverage
8+
: public ::testing::Test
9+
{
10+
public:
11+
filters::passive::MovingAverage<float, 4> ma{};
12+
};
13+
}
14+
15+
TEST_F(TestMovingAverage, warmup_fills_window)
16+
{
17+
constexpr float tol = 1e-6f;
18+
EXPECT_NEAR(ma.Filter(1.0f), 0.25f, tol);
19+
EXPECT_NEAR(ma.Filter(0.0f), 0.25f, tol);
20+
EXPECT_NEAR(ma.Filter(0.0f), 0.25f, tol);
21+
EXPECT_NEAR(ma.Filter(0.0f), 0.25f, tol);
22+
}
23+
24+
TEST_F(TestMovingAverage, constant_input_unity_gain)
25+
{
26+
constexpr float tol = 1e-6f;
27+
constexpr float c = 0.5f;
28+
for (int i = 0; i < 8; ++i)
29+
ma.Filter(c);
30+
EXPECT_NEAR(ma.Filter(c), c, tol);
31+
}
32+
33+
TEST_F(TestMovingAverage, step_response_is_linear_ramp)
34+
{
35+
constexpr float tol = 1e-6f;
36+
EXPECT_NEAR(ma.Filter(1.0f), 0.25f, tol);
37+
EXPECT_NEAR(ma.Filter(1.0f), 0.50f, tol);
38+
EXPECT_NEAR(ma.Filter(1.0f), 0.75f, tol);
39+
EXPECT_NEAR(ma.Filter(1.0f), 1.00f, tol);
40+
EXPECT_NEAR(ma.Filter(1.0f), 1.00f, tol);
41+
}
42+
43+
TEST_F(TestMovingAverage, running_sum_matches_direct_average)
44+
{
45+
constexpr float tol = 1e-6f;
46+
constexpr std::array<float, 8> seq{ 0.1f, 0.4f, 0.9f, 0.2f, 0.7f, 0.3f, 0.5f, 0.8f };
47+
std::array<float, 8> outputs{};
48+
for (std::size_t i = 0; i < seq.size(); ++i)
49+
outputs[i] = ma.Filter(seq[i]);
50+
51+
for (std::size_t i = 3; i < seq.size(); ++i)
52+
{
53+
float brute = (seq[i] + seq[i - 1] + seq[i - 2] + seq[i - 3]) * 0.25f;
54+
EXPECT_NEAR(outputs[i], brute, tol);
55+
}
56+
}
57+
58+
TEST_F(TestMovingAverage, impulse_leaves_after_N)
59+
{
60+
constexpr float tol = 1e-6f;
61+
ma.Filter(1.0f);
62+
ma.Filter(0.0f);
63+
ma.Filter(0.0f);
64+
ma.Filter(0.0f);
65+
EXPECT_NEAR(ma.Filter(0.0f), 0.0f, tol);
66+
EXPECT_NEAR(ma.Filter(0.0f), 0.0f, tol);
67+
}
68+
69+
TEST_F(TestMovingAverage, reset_clears_state)
70+
{
71+
constexpr float tol = 1e-6f;
72+
ma.Filter(1.0f);
73+
ma.Filter(1.0f);
74+
ma.Reset();
75+
EXPECT_NEAR(ma.Filter(1.0f), 0.25f, tol);
76+
}
77+
78+
TEST_F(TestMovingAverage, reset_with_value_prefills_window)
79+
{
80+
constexpr float tol = 1e-6f;
81+
ma.Reset(2.0f);
82+
EXPECT_NEAR(ma.Filter(2.0f), 2.0f, tol);
83+
}

0 commit comments

Comments
 (0)