Skip to content

Commit d4d5912

Browse files
feat: add median filter (#169)
* add median filter * add missing section * Update doc/filters/passive/MedianFilter.md 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 fc4d550 commit d4d5912

11 files changed

Lines changed: 299 additions & 205 deletions

File tree

‎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) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation |
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, Exponential Moving Average, Moving Average |
24+
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Exponential Moving Average, Moving Average, Median Filter |
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 & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -24,61 +24,9 @@ Difficulty legend:
2424

2525
## Master list (by priority)
2626

27-
<<<<<<< Updated upstream
2827

2928
| # | Component | Target module | Difficulty |
3029
|----|------------------------------------------------------|---------------------------|------------|
31-
| 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ |
32-
| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ |
33-
| 6 | Median filter | `filters/passive` | ★★☆☆☆ |
34-
| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ |
35-
| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ |
36-
| 9 | Complementary filter | `filters/active` | ★★☆☆☆ |
37-
| 10 | Gain-scheduled controller | `controllers` | ★★☆☆☆ |
38-
| 11 | Convolution & correlation utilities | `analysis` | ★★☆☆☆ |
39-
| 12 | Polynomial least-squares curve fitting | `estimators/offline` | ★★☆☆☆ |
40-
| 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ |
41-
| 14 | CIC (Cascaded Integrator-Comb) filter | `filters/passive` | ★★☆☆☆ |
42-
| 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ |
43-
| 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ |
44-
| 17 | Lead-lag compensator | `controllers` | ★★★☆☆ |
45-
| 18 | Quaternion type | `math` | ★★★☆☆ |
46-
| 19 | Luenberger observer + pole placement (Ackermann) | `controllers` | ★★★☆☆ |
47-
| 20 | Integral / servo state feedback (LQI) | `controllers` | ★★★☆☆ |
48-
| 21 | LMS / NLMS adaptive filter | `estimators/online` | ★★★☆☆ |
49-
| 22 | Savitzky-Golay filter | `filters/passive` | ★★★☆☆ |
50-
| 23 | CORDIC | `math` | ★★★☆☆ |
51-
| 24 | Runge-Kutta ODE integrators (RK4 + Dormand-Prince) | `solvers` | ★★★☆☆ |
52-
| 25 | Real-input FFT (RFFT) | `analysis` | ★★★☆☆ |
53-
| 26 | Controllability / Observability matrices & Gramians | `control_analysis` | ★★★☆☆ |
54-
| 27 | QR decomposition (Householder / Givens) | `solvers` | ★★★★☆ |
55-
| 28 | LU decomposition with partial pivoting | `solvers` | ★★★★☆ |
56-
| 29 | Matrix exponential (scaling & squaring + Padé) | `math` | ★★★★☆ |
57-
| 30 | Continuous → discrete conversion (`c2d`) | `math` | ★★★★☆ |
58-
| 31 | Lyapunov / Sylvester equation solvers | `solvers` | ★★★★☆ |
59-
| 32 | Transfer-function ↔ state-space conversion | `control_analysis` | ★★★★☆ |
60-
| 33 | Madgwick / Mahony AHRS | `filters/active` | ★★★★☆ |
61-
| 34 | Sliding Mode Control (SMC) | `robust_control` (new) | ★★★★☆ |
62-
| 35 | Disturbance Observer (DOB) | `robust_control` (new) | ★★★★☆ |
63-
| 36 | Active Disturbance Rejection Control (ADRC + ESO) | `robust_control` (new) | ★★★★☆ |
64-
| 37 | Hilbert transform / analytic signal / envelope | `analysis` | ★★★★☆ |
65-
| 38 | Discrete Wavelet Transform (Haar / Daubechies) | `analysis` | ★★★★☆ |
66-
| 39 | Square-root / Information Kalman filter | `filters/active` | ★★★★☆ |
67-
| 40 | Feedback linearization | `nonlinear_control` (new) | ★★★★☆ |
68-
| 41 | Backstepping controller | `nonlinear_control` (new) | ★★★★☆ |
69-
| 42 | Symmetric eigenvalue solver (Jacobi) | `solvers` | ★★★★★ |
70-
| 43 | Singular Value Decomposition (Golub-Kahan) | `solvers` | ★★★★★ |
71-
| 44 | Total Least Squares | `estimators/offline` | ★★★★★ |
72-
| 45 | IIR filter design (Butterworth/Chebyshev + bilinear) | `filters/passive` | ★★★★★ |
73-
| 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ |
74-
| 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ |
75-
=======
76-
| # | Component | Target module | Difficulty |
77-
|----|------------------------------------------------------|---------------------------|------------|
78-
| 2 | Moving Average (running-sum boxcar) | `filters/passive` | ★☆☆☆☆ |
79-
| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ |
80-
| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ |
81-
| 6 | Median filter | `filters/passive` | ★★☆☆☆ |
8230
| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ |
8331
| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ |
8432
| 9 | Complementary filter | `filters/active` | ★★☆☆☆ |
@@ -121,8 +69,6 @@ Difficulty legend:
12169
| 46 | H∞ state-feedback control | `robust_control` (new) | ★★★★★ |
12270
| 47 | Model Reference Adaptive Control (MRAC) | `nonlinear_control` (new) | ★★★★★ |
12371

124-
>>>>>>> Stashed changes
125-
12672
---
12773

12874
## Tier 1 — Trivial primitives ★☆☆☆☆
@@ -155,12 +101,6 @@ Difficulty legend:
155101

156102
## Tier 2 — Easy ★★☆☆☆
157103

158-
### 6. Median filter
159-
- **What:** Sliding-window running median over a bounded window.
160-
- **Embedded value:** Non-linear rejection of impulsive/salt-and-pepper spikes that linear filters smear; ideal for noisy ADC/sensor streams.
161-
- **Algorithm / paper:** T. Huang, G. Yang, G. Tang, "A fast two-dimensional median filtering algorithm," *IEEE Trans. ASSP*, 27(1), 1979.
162-
- **Reuses:** `std::array` window with bounded insertion sort (no heap).
163-
164104
### 7. Feedforward / 2-DOF controller
165105
- **What:** Adds a reference/disturbance feedforward path to an existing feedback loop (two-degree-of-freedom structure).
166106
- **Embedded value:** Improves tracking and disturbance rejection without sacrificing feedback stability margins.
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
# Median Filter (Sliding Window)
2+
3+
## Overview & Motivation
4+
5+
Impulsive noise — EMI clicks, dropped ADC bits, salt-and-pepper sensor glitches — corrupts embedded
6+
sensor streams in a way that linear averaging amplifies rather than rejects. A single outlier sample
7+
at 100× the signal level drags a moving-average output for the entire window duration. The median
8+
filter eliminates isolated spikes completely, using only comparisons and no arithmetic on the signal
9+
values themselves, making it an ideal non-linear pre-processor for noisy ADC and sensor streams.
10+
11+
## Mathematical Theory
12+
13+
### Core Definition
14+
15+
Let $x[n]$ be the input sequence and $N$ the window length. Define the sorted window snapshot as
16+
$x_{(1)} \le x_{(2)} \le \cdots \le x_{(N)}$ (order statistics). The median filter output is:
17+
18+
$$y[n] = x_{(\lceil N/2 \rceil)}$$
19+
20+
For odd $N$ this is the unique middle order statistic. For even $N$ one common convention takes the
21+
average of the two central statistics, but this introduces arithmetic on the signal and the
22+
associated round-off.
23+
24+
### Impulse Rejection Threshold
25+
26+
A spike is suppressed if and only if it does not form a strict majority of the window, i.e., if fewer
27+
than $\lceil N/2 \rceil$ samples share the outlier level. An isolated impulse occupies exactly one
28+
slot; it is always rejected for $N \ge 3$.
29+
30+
### Step-Edge Preservation
31+
32+
A step transition from level $a$ to level $b$ causes the median to switch from $a$ to $b$ after
33+
exactly $\lfloor N/2 \rfloor$ samples of delay — without overshoot, Gibbs ringing, or smearing. This
34+
is the fundamental advantage over linear filters: the nonlinearity of the sort operation preserves
35+
edges while rejecting impulses.
36+
37+
### Lag
38+
39+
The causal sliding-window median introduces a latency of $\lfloor (N-1)/2 \rfloor$ samples, which
40+
is the same group delay as a symmetric FIR of the same length. Unlike a linear FIR, however, the
41+
delay is signal-dependent near edges.
42+
43+
## Algorithm
44+
45+
### Insertion-Sort Approach
46+
47+
For small, fixed window sizes $N$ (typically 3–9 in embedded use), copying the ring buffer into a
48+
scratch array and applying insertion sort is cache-friendly and avoids heap allocation. The
49+
comparison count is at most $N(N-1)/2$ — fully bounded by the compile-time constant $N$.
50+
51+
Insertion sort on the scratch copy:
52+
53+
$$\text{for } i = 1, \ldots, N-1: \text{ shift } \text{scratch}[0 \ldots i-1] \text{ right until sorted position for scratch}[i]$$
54+
55+
The median is then $\text{scratch}[\lfloor N/2 \rfloor]$.
56+
57+
### Huang Histogram Variant
58+
59+
Huang, Yang, and Tang (1979) describe an $O(1)$-per-sample update based on a running histogram: the
60+
departing sample decrements its histogram bin and the arriving sample increments its bin, then the
61+
median bin is walked left or right by one position. This reduces per-sample work from $O(N)$ to
62+
$O(1)$ but requires a histogram array indexed over the signal alphabet — impractical for
63+
floating-point streams on embedded targets.
64+
65+
## Complexity Analysis
66+
67+
| Variant | Time per sample | Space | Notes |
68+
|----------------------|-----------------|---------|--------------------------------------------|
69+
| Insertion sort (used) | $O(N)$ | $O(N)$ | Optimal for small fixed $N$; no heap |
70+
| Huang histogram | $O(1)$ | $O(K)$ | $K$ = alphabet size; integer signals only |
71+
72+
For $N \le 9$ the insertion-sort inner loop is unrolled by the compiler and runs in a handful of
73+
compare-and-swap operations — faster in practice than histogram maintenance.
74+
75+
## Step-by-Step Walkthrough
76+
77+
Input: $x = [0.1, 0.1, 0.9, 0.1, 0.1]$, window size $N = 3$, initial window pre-seeded with $0.0$.
78+
79+
| $n$ | $x[n]$ | Window (ring buffer) | Sorted scratch | $y[n]$ |
80+
|-----|--------|----------------------|---------------------|--------|
81+
| 0 | 0.1 | [0.0, 0.0, 0.1] | [0.0, **0.0**, 0.1] | 0.0 |
82+
| 1 | 0.1 | [0.0, 0.1, 0.1] | [0.0, **0.1**, 0.1] | 0.1 |
83+
| 2 | 0.9 | [0.1, 0.1, 0.9] | [0.1, **0.1**, 0.9] | 0.1 |
84+
| 3 | 0.1 | [0.1, 0.9, 0.1] | [0.1, **0.1**, 0.9] | 0.1 |
85+
| 4 | 0.1 | [0.9, 0.1, 0.1] | [0.1, **0.1**, 0.9] | 0.1 |
86+
87+
The bold value is the median at index $\lfloor 3/2 \rfloor = 1$. The spike at $n = 2$ ($x = 0.9$)
88+
appears in only one of the three window slots at any given time, so it is never the majority and
89+
never reaches the output.
90+
91+
## Pitfalls & Edge Cases
92+
93+
- **Even window length**: the two central order statistics may differ, requiring an average; use odd
94+
$N$ to keep the output comparison-only.
95+
- **Window width vs. pulse width**: an impulse burst wider than $\lfloor N/2 \rfloor$ samples is
96+
not rejected; $N$ must be at least $2 \times \text{burst\_width} + 1$.
97+
- **Startup / warm-up**: pre-seeding the window with an initial value prevents undefined output
98+
during the first $N-1$ samples.
99+
- **Signal plateaus**: when the signal is constant at the impulse level for more than half the
100+
window, that value becomes the majority and passes through — this is expected behaviour and
101+
documents the $\lfloor N/2 \rfloor$ rejection limit.
102+
- **Latency vs. rejection trade-off**: increasing $N$ widens the rejection band but also increases
103+
latency and rounds off narrow legitimate peaks.
104+
105+
## Variants & Generalizations
106+
107+
- **Weighted median**: assigns integer multiplicities to samples; shifts the breakdown point without
108+
changing the comparison-only property.
109+
- **Running-histogram median (Huang 1979)**: $O(1)$ update for integer signals over a bounded
110+
alphabet.
111+
- **Two-pass 2-D median**: Huang's paper targets image processing; separable row–column passes
112+
generalize to 2-D arrays.
113+
- **Recursive median**: feeds filtered output back into the window; achieves stronger smoothing at
114+
the cost of potential limit-cycle oscillations.
115+
116+
## Applications
117+
118+
- ADC spike rejection before integration or threshold detection.
119+
- Salt-and-pepper denoising in IMU/MEMS sensor streams.
120+
- Pre-filter before a PID controller to prevent derivative kick from glitches.
121+
- Image-row processing on embedded vision pipelines (1-D median per scan line).
122+
123+
## Connections to Other Algorithms
124+
125+
- `MovingAverage` is the linear equivalent; it smears both noise and edges, while the median
126+
preserves edges at the cost of being nonlinear and harder to analyse in the frequency domain.
127+
- `ExponentialMovingAverage` provides even lower memory cost but is sensitive to impulsive outliers.
128+
- `FirFilter` with optimal coefficients can achieve equiripple passband/stopband behaviour but
129+
cannot reject isolated spikes without distorting step edges.
130+
131+
## References & Further Reading
132+
133+
- T. Huang, G. Yang, G. Tang, "A fast two-dimensional median filtering algorithm," *IEEE
134+
Transactions on Acoustics, Speech, and Signal Processing*, 27(1), pp. 13–18, 1979.
135+
- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., §11.4 — Median and
136+
Order-Statistic Filters.
137+
- L. Yin, R. Yang, M. Gabbouj, Y. Neuvo, "Weighted median filters: a tutorial," *IEEE Transactions
138+
on Circuits and Systems II*, 43(3), 1996.

‎numerical/filters/passive/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,15 @@ target_sources(numerical.filters.passive PRIVATE
1414
ExponentialMovingAverage.hpp
1515
Fir.hpp
1616
Iir.hpp
17+
MedianFilter.hpp
1718
MovingAverage.hpp
1819
)
1920

2021
numerical_add_coverage_sources(numerical.filters.passive
2122
ExponentialMovingAverage.cpp
2223
Fir.cpp
2324
Iir.cpp
25+
MedianFilter.cpp
2426
MovingAverage.cpp
2527
)
2628

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#include "numerical/filters/passive/MedianFilter.hpp"
2+
3+
namespace filters::passive
4+
{
5+
template class MedianFilter<float, 3>;
6+
template class MedianFilter<float, 5>;
7+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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 <array>
9+
#include <cstddef>
10+
#include <type_traits>
11+
12+
namespace filters::passive
13+
{
14+
template<typename T, std::size_t N>
15+
class MedianFilter
16+
{
17+
static_assert(std::is_floating_point_v<T>, "MedianFilter supports floating-point types");
18+
static_assert(N > 0, "MedianFilter window size must be greater than zero");
19+
20+
public:
21+
explicit MedianFilter(T initial = T{}) noexcept;
22+
23+
OPTIMIZE_FOR_SPEED T Filter(T input) noexcept;
24+
void Reset(T value = T{}) noexcept;
25+
26+
private:
27+
std::array<T, N> window;
28+
std::array<T, N> scratch;
29+
std::size_t head;
30+
};
31+
32+
template<typename T, std::size_t N>
33+
MedianFilter<T, N>::MedianFilter(T initial) noexcept
34+
: head{ 0 }
35+
{
36+
window.fill(initial);
37+
scratch.fill(T{});
38+
}
39+
40+
template<typename T, std::size_t N>
41+
OPTIMIZE_FOR_SPEED T MedianFilter<T, N>::Filter(T input) noexcept
42+
{
43+
window[head] = input;
44+
head = (head + 1) % N;
45+
46+
scratch = window;
47+
48+
for (std::size_t i = 1; i < N; ++i)
49+
{
50+
T key = scratch[i];
51+
std::size_t j = i;
52+
while (j > 0 && scratch[j - 1] > key)
53+
{
54+
scratch[j] = scratch[j - 1];
55+
--j;
56+
}
57+
scratch[j] = key;
58+
}
59+
60+
return scratch[N / 2];
61+
}
62+
63+
template<typename T, std::size_t N>
64+
void MedianFilter<T, N>::Reset(T value) noexcept
65+
{
66+
window.fill(value);
67+
scratch.fill(T{});
68+
head = 0;
69+
}
70+
71+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
72+
extern template class MedianFilter<float, 3>;
73+
extern template class MedianFilter<float, 5>;
74+
#endif
75+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@ target_sources(numerical.filters.passive_test PRIVATE
1313
TestExponentialMovingAverage.cpp
1414
TestFir.cpp
1515
TestIir.cpp
16+
TestMedianFilter.cpp
1617
TestMovingAverage.cpp
1718
)

0 commit comments

Comments
 (0)