Repository navigation
feat: add moving average filter #165
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
gabrielfrasantos marked this conversation as resolved.
Resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.