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: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<float>()`. No heap.
- **Coverage ≥ 90 %** — measured by SonarQube. Every new algorithm must reach this threshold
before merge; CI fails below it.

## CMake (numerical/ targets)

Expand Down
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 |
| [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 |
Expand Down
1 change: 0 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` | ★☆☆☆☆ |
Expand Down
103 changes: 103 additions & 0 deletions doc/filters/passive/MovingAverage.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions numerical/filters/passive/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
6 changes: 6 additions & 0 deletions numerical/filters/passive/MovingAverage.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#include "numerical/filters/passive/MovingAverage.hpp"

namespace filters::passive
{
template class MovingAverage<float, 4>;
}
65 changes: 65 additions & 0 deletions numerical/filters/passive/MovingAverage.hpp
Original file line number Diff line number Diff line change
@@ -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<typename T, std::size_t N>
class MovingAverage
{
static_assert(std::is_floating_point_v<T>, "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<T, N> window;
T sum;
T invN;

[[no_unique_address]] math::Index n;
};

template<typename T, std::size_t N>
MovingAverage<T, N>::MovingAverage(T initial) noexcept
: sum{ initial * static_cast<T>(N) }
, invN{ T{ 1 } / static_cast<T>(N) }
{
for (std::size_t i = 0; i < N; ++i)
window.Update(initial);
}

template<typename T, std::size_t N>
OPTIMIZE_FOR_SPEED T MovingAverage<T, N>::Filter(T input) noexcept
{
T oldest = window[n - static_cast<int32_t>(N - 1)];
sum = sum + input - oldest;
window.Update(input);
return sum * invN;
}

template<typename T, std::size_t N>
void MovingAverage<T, N>::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<T>(N);
}
}

#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
extern template class MovingAverage<float, 4>;
#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 @@ -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
)
83 changes: 83 additions & 0 deletions numerical/filters/passive/test/TestMovingAverage.cpp
Original file line number Diff line number Diff line change
@@ -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<float, 4> 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<float, 8> seq{ 0.1f, 0.4f, 0.9f, 0.2f, 0.7f, 0.3f, 0.5f, 0.8f };
std::array<float, 8> 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);
}
Loading