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

## Master list (by priority)

<<<<<<< Updated upstream

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

>>>>>>> Stashed changes

---

## Tier 1 — Trivial primitives ★☆☆☆☆
Expand Down Expand Up @@ -155,12 +101,6 @@ Difficulty legend:

## Tier 2 — Easy ★★☆☆☆

### 6. Median filter
- **What:** Sliding-window running median over a bounded window.
- **Embedded value:** Non-linear rejection of impulsive/salt-and-pepper spikes that linear filters smear; ideal for noisy ADC/sensor streams.
- **Algorithm / paper:** T. Huang, G. Yang, G. Tang, "A fast two-dimensional median filtering algorithm," *IEEE Trans. ASSP*, 27(1), 1979.
- **Reuses:** `std::array` window with bounded insertion sort (no heap).

### 7. Feedforward / 2-DOF controller
- **What:** Adds a reference/disturbance feedforward path to an existing feedback loop (two-degree-of-freedom structure).
- **Embedded value:** Improves tracking and disturbance rejection without sacrificing feedback stability margins.
Expand Down
138 changes: 138 additions & 0 deletions doc/filters/passive/MedianFilter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Median Filter (Sliding Window)

## Overview & Motivation

Impulsive noise — EMI clicks, dropped ADC bits, salt-and-pepper sensor glitches — corrupts embedded
sensor streams in a way that linear averaging amplifies rather than rejects. A single outlier sample
at 100× the signal level drags a moving-average output for the entire window duration. The median
filter eliminates isolated spikes completely, using only comparisons and no arithmetic on the signal
values themselves, making it an ideal non-linear pre-processor for noisy ADC and sensor streams.

## Mathematical Theory

### Core Definition

Let $x[n]$ be the input sequence and $N$ the window length. Define the sorted window snapshot as
$x_{(1)} \le x_{(2)} \le \cdots \le x_{(N)}$ (order statistics). The median filter output is:

$$y[n] = x_{(\lceil N/2 \rceil)}$$

For odd $N$ this is the unique middle order statistic. For even $N$ one common convention takes the
average of the two central statistics, but this introduces arithmetic on the signal and the
associated round-off.

### Impulse Rejection Threshold

A spike is suppressed if and only if it does not form a strict majority of the window, i.e., if fewer
than $\lceil N/2 \rceil$ samples share the outlier level. An isolated impulse occupies exactly one
slot; it is always rejected for $N \ge 3$.

### Step-Edge Preservation

A step transition from level $a$ to level $b$ causes the median to switch from $a$ to $b$ after
exactly $\lfloor N/2 \rfloor$ samples of delay — without overshoot, Gibbs ringing, or smearing. This
is the fundamental advantage over linear filters: the nonlinearity of the sort operation preserves
edges while rejecting impulses.

### Lag

The causal sliding-window median introduces a latency of $\lfloor (N-1)/2 \rfloor$ samples, which
is the same group delay as a symmetric FIR of the same length. Unlike a linear FIR, however, the
delay is signal-dependent near edges.

## Algorithm

### Insertion-Sort Approach

For small, fixed window sizes $N$ (typically 3–9 in embedded use), copying the ring buffer into a
scratch array and applying insertion sort is cache-friendly and avoids heap allocation. The
comparison count is at most $N(N-1)/2$ — fully bounded by the compile-time constant $N$.

Insertion sort on the scratch copy:

$$\text{for } i = 1, \ldots, N-1: \text{ shift } \text{scratch}[0 \ldots i-1] \text{ right until sorted position for scratch}[i]$$

The median is then $\text{scratch}[\lfloor N/2 \rfloor]$.

### Huang Histogram Variant

Huang, Yang, and Tang (1979) describe an $O(1)$-per-sample update based on a running histogram: the
departing sample decrements its histogram bin and the arriving sample increments its bin, then the
median bin is walked left or right by one position. This reduces per-sample work from $O(N)$ to
$O(1)$ but requires a histogram array indexed over the signal alphabet — impractical for
floating-point streams on embedded targets.

## Complexity Analysis

| Variant | Time per sample | Space | Notes |
|----------------------|-----------------|---------|--------------------------------------------|
| Insertion sort (used) | $O(N)$ | $O(N)$ | Optimal for small fixed $N$; no heap |
| Huang histogram | $O(1)$ | $O(K)$ | $K$ = alphabet size; integer signals only |
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved

For $N \le 9$ the insertion-sort inner loop is unrolled by the compiler and runs in a handful of
compare-and-swap operations — faster in practice than histogram maintenance.

## Step-by-Step Walkthrough

Input: $x = [0.1, 0.1, 0.9, 0.1, 0.1]$, window size $N = 3$, initial window pre-seeded with $0.0$.

| $n$ | $x[n]$ | Window (ring buffer) | Sorted scratch | $y[n]$ |
|-----|--------|----------------------|---------------------|--------|
| 0 | 0.1 | [0.0, 0.0, 0.1] | [0.0, **0.0**, 0.1] | 0.0 |
| 1 | 0.1 | [0.0, 0.1, 0.1] | [0.0, **0.1**, 0.1] | 0.1 |
| 2 | 0.9 | [0.1, 0.1, 0.9] | [0.1, **0.1**, 0.9] | 0.1 |
| 3 | 0.1 | [0.1, 0.9, 0.1] | [0.1, **0.1**, 0.9] | 0.1 |
| 4 | 0.1 | [0.9, 0.1, 0.1] | [0.1, **0.1**, 0.9] | 0.1 |

The bold value is the median at index $\lfloor 3/2 \rfloor = 1$. The spike at $n = 2$ ($x = 0.9$)
appears in only one of the three window slots at any given time, so it is never the majority and
never reaches the output.

## Pitfalls & Edge Cases

- **Even window length**: the two central order statistics may differ, requiring an average; use odd
$N$ to keep the output comparison-only.
- **Window width vs. pulse width**: an impulse burst wider than $\lfloor N/2 \rfloor$ samples is
not rejected; $N$ must be at least $2 \times \text{burst\_width} + 1$.
- **Startup / warm-up**: pre-seeding the window with an initial value prevents undefined output
during the first $N-1$ samples.
- **Signal plateaus**: when the signal is constant at the impulse level for more than half the
window, that value becomes the majority and passes through — this is expected behaviour and
documents the $\lfloor N/2 \rfloor$ rejection limit.
- **Latency vs. rejection trade-off**: increasing $N$ widens the rejection band but also increases
latency and rounds off narrow legitimate peaks.

## Variants & Generalizations

- **Weighted median**: assigns integer multiplicities to samples; shifts the breakdown point without
changing the comparison-only property.
- **Running-histogram median (Huang 1979)**: $O(1)$ update for integer signals over a bounded
alphabet.
- **Two-pass 2-D median**: Huang's paper targets image processing; separable row–column passes
generalize to 2-D arrays.
- **Recursive median**: feeds filtered output back into the window; achieves stronger smoothing at
the cost of potential limit-cycle oscillations.

## Applications

- ADC spike rejection before integration or threshold detection.
- Salt-and-pepper denoising in IMU/MEMS sensor streams.
- Pre-filter before a PID controller to prevent derivative kick from glitches.
- Image-row processing on embedded vision pipelines (1-D median per scan line).

## Connections to Other Algorithms

- `MovingAverage` is the linear equivalent; it smears both noise and edges, while the median
preserves edges at the cost of being nonlinear and harder to analyse in the frequency domain.
- `ExponentialMovingAverage` provides even lower memory cost but is sensitive to impulsive outliers.
- `FirFilter` with optimal coefficients can achieve equiripple passband/stopband behaviour but
cannot reject isolated spikes without distorting step edges.

## References & Further Reading

- T. Huang, G. Yang, G. Tang, "A fast two-dimensional median filtering algorithm," *IEEE
Transactions on Acoustics, Speech, and Signal Processing*, 27(1), pp. 13–18, 1979.
- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., §11.4 — Median and
Order-Statistic Filters.
- L. Yin, R. Yang, M. Gabbouj, Y. Neuvo, "Weighted median filters: a tutorial," *IEEE Transactions
on Circuits and Systems II*, 43(3), 1996.
2 changes: 2 additions & 0 deletions numerical/filters/passive/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ target_sources(numerical.filters.passive PRIVATE
ExponentialMovingAverage.hpp
Fir.hpp
Iir.hpp
MedianFilter.hpp
MovingAverage.hpp
)

numerical_add_coverage_sources(numerical.filters.passive
ExponentialMovingAverage.cpp
Fir.cpp
Iir.cpp
MedianFilter.cpp
MovingAverage.cpp
)

Expand Down
7 changes: 7 additions & 0 deletions numerical/filters/passive/MedianFilter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#include "numerical/filters/passive/MedianFilter.hpp"

namespace filters::passive
{
template class MedianFilter<float, 3>;
template class MedianFilter<float, 5>;
}
75 changes: 75 additions & 0 deletions numerical/filters/passive/MedianFilter.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#pragma once

#if defined(__GNUC__) || defined(__clang__)
#pragma GCC optimize("O3", "fast-math")
#endif

#include "numerical/math/CompilerOptimizations.hpp"
#include <array>
#include <cstddef>
#include <type_traits>

namespace filters::passive
{
template<typename T, std::size_t N>
class MedianFilter
{
static_assert(std::is_floating_point_v<T>, "MedianFilter supports floating-point types");
static_assert(N > 0, "MedianFilter window size must be greater than zero");

public:
explicit MedianFilter(T initial = T{}) noexcept;

OPTIMIZE_FOR_SPEED T Filter(T input) noexcept;
void Reset(T value = T{}) noexcept;

private:
std::array<T, N> window;
std::array<T, N> scratch;
std::size_t head;
};

template<typename T, std::size_t N>
MedianFilter<T, N>::MedianFilter(T initial) noexcept
: head{ 0 }

Check warning on line 34 in numerical/filters/passive/MedianFilter.hpp

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Do not use the constructor's initializer list for data member "head". Use the in-class initializer instead.

See more on https://sonarcloud.io/project/issues?id=embedded-pro_embedded-dsp-control&issues=AZ-fxo8-RMcunr9Mu02H&open=AZ-fxo8-RMcunr9Mu02H&pullRequest=169
{
window.fill(initial);
scratch.fill(T{});
}

template<typename T, std::size_t N>
OPTIMIZE_FOR_SPEED T MedianFilter<T, N>::Filter(T input) noexcept
{
window[head] = input;
head = (head + 1) % N;

scratch = window;

for (std::size_t i = 1; i < N; ++i)
{
T key = scratch[i];
std::size_t j = i;
while (j > 0 && scratch[j - 1] > key)
{
scratch[j] = scratch[j - 1];
--j;
}
scratch[j] = key;
}

return scratch[N / 2];
}

template<typename T, std::size_t N>
void MedianFilter<T, N>::Reset(T value) noexcept
{
window.fill(value);
scratch.fill(T{});
head = 0;
}

#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
extern template class MedianFilter<float, 3>;
extern template class MedianFilter<float, 5>;
#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 @@ -13,5 +13,6 @@ target_sources(numerical.filters.passive_test PRIVATE
TestExponentialMovingAverage.cpp
TestFir.cpp
TestIir.cpp
TestMedianFilter.cpp
TestMovingAverage.cpp
)
Loading
Loading