diff --git a/README.md b/README.md index bc2ced09..f5ab85d8 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/ROADMAP.md b/ROADMAP.md index 33badcc1..5d83f72c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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` | ★★☆☆☆ | @@ -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 ★☆☆☆☆ @@ -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. diff --git a/doc/filters/passive/MedianFilter.md b/doc/filters/passive/MedianFilter.md new file mode 100644 index 00000000..0e28b995 --- /dev/null +++ b/doc/filters/passive/MedianFilter.md @@ -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 | + +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. diff --git a/numerical/filters/passive/CMakeLists.txt b/numerical/filters/passive/CMakeLists.txt index ebfc5af5..7f2e3233 100644 --- a/numerical/filters/passive/CMakeLists.txt +++ b/numerical/filters/passive/CMakeLists.txt @@ -14,6 +14,7 @@ target_sources(numerical.filters.passive PRIVATE ExponentialMovingAverage.hpp Fir.hpp Iir.hpp + MedianFilter.hpp MovingAverage.hpp ) @@ -21,6 +22,7 @@ numerical_add_coverage_sources(numerical.filters.passive ExponentialMovingAverage.cpp Fir.cpp Iir.cpp + MedianFilter.cpp MovingAverage.cpp ) diff --git a/numerical/filters/passive/MedianFilter.cpp b/numerical/filters/passive/MedianFilter.cpp new file mode 100644 index 00000000..a38244aa --- /dev/null +++ b/numerical/filters/passive/MedianFilter.cpp @@ -0,0 +1,7 @@ +#include "numerical/filters/passive/MedianFilter.hpp" + +namespace filters::passive +{ + template class MedianFilter; + template class MedianFilter; +} diff --git a/numerical/filters/passive/MedianFilter.hpp b/numerical/filters/passive/MedianFilter.hpp new file mode 100644 index 00000000..6372b131 --- /dev/null +++ b/numerical/filters/passive/MedianFilter.hpp @@ -0,0 +1,75 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include +#include +#include + +namespace filters::passive +{ + template + class MedianFilter + { + static_assert(std::is_floating_point_v, "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 window; + std::array scratch; + std::size_t head; + }; + + template + MedianFilter::MedianFilter(T initial) noexcept + : head{ 0 } + { + window.fill(initial); + scratch.fill(T{}); + } + + template + OPTIMIZE_FOR_SPEED T MedianFilter::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 + void MedianFilter::Reset(T value) noexcept + { + window.fill(value); + scratch.fill(T{}); + head = 0; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class MedianFilter; + extern template class MedianFilter; +#endif +} diff --git a/numerical/filters/passive/test/CMakeLists.txt b/numerical/filters/passive/test/CMakeLists.txt index 5b678988..9253deb2 100644 --- a/numerical/filters/passive/test/CMakeLists.txt +++ b/numerical/filters/passive/test/CMakeLists.txt @@ -13,5 +13,6 @@ target_sources(numerical.filters.passive_test PRIVATE TestExponentialMovingAverage.cpp TestFir.cpp TestIir.cpp + TestMedianFilter.cpp TestMovingAverage.cpp ) diff --git a/numerical/filters/passive/test/TestMedianFilter.cpp b/numerical/filters/passive/test/TestMedianFilter.cpp new file mode 100644 index 00000000..02534356 --- /dev/null +++ b/numerical/filters/passive/test/TestMedianFilter.cpp @@ -0,0 +1,75 @@ +#include "numerical/filters/passive/MedianFilter.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gtest/gtest.h" + +namespace +{ + class TestMedianFilter + : public ::testing::Test + { + public: + filters::passive::MedianFilter med{}; + }; +} + +TEST_F(TestMedianFilter, rejects_single_impulse) +{ + med.Filter(0.1f); + med.Filter(0.1f); + float y2 = med.Filter(0.9f); + float y3 = med.Filter(0.1f); + float y4 = med.Filter(0.1f); + EXPECT_NEAR(y2, 0.1f, 1e-6f); + EXPECT_NEAR(y3, 0.1f, 1e-6f); + EXPECT_NEAR(y4, 0.1f, 1e-6f); +} + +TEST_F(TestMedianFilter, preserves_step_edge) +{ + med.Filter(0.0f); + med.Filter(0.0f); + float y2 = med.Filter(1.0f); + float y3 = med.Filter(1.0f); + float y4 = med.Filter(1.0f); + EXPECT_NEAR(y2, 0.0f, 1e-6f); + EXPECT_NEAR(y3, 1.0f, 1e-6f); + EXPECT_NEAR(y4, 1.0f, 1e-6f); +} + +TEST_F(TestMedianFilter, constant_input_passthrough) +{ + constexpr float c = 0.7f; + med.Filter(c); + med.Filter(c); + EXPECT_NEAR(med.Filter(c), c, 1e-6f); + EXPECT_NEAR(med.Filter(c), c, 1e-6f); +} + +TEST_F(TestMedianFilter, sorted_middle_is_returned) +{ + med.Filter(0.3f); + med.Filter(0.1f); + float result = med.Filter(0.2f); + EXPECT_NEAR(result, 0.2f, 1e-6f); +} + +TEST_F(TestMedianFilter, majority_spike_passes) +{ + med.Filter(0.0f); + float y1 = med.Filter(0.9f); + float y2 = med.Filter(0.9f); + float y3 = med.Filter(0.0f); + EXPECT_NEAR(y1, 0.0f, 1e-6f); + EXPECT_NEAR(y2, 0.9f, 1e-6f); + EXPECT_NEAR(y3, 0.9f, 1e-6f); +} + +TEST_F(TestMedianFilter, reset_clears_window) +{ + med.Filter(1.0f); + med.Filter(1.0f); + med.Filter(1.0f); + med.Reset(0.0f); + EXPECT_NEAR(med.Filter(0.0f), 0.0f, 1e-6f); + EXPECT_NEAR(med.Filter(0.0f), 0.0f, 1e-6f); +} diff --git a/roadmap/filters/passive/MedianFilter/explanation.md b/roadmap/filters/passive/MedianFilter/explanation.md deleted file mode 100644 index 1fccc618..00000000 --- a/roadmap/filters/passive/MedianFilter/explanation.md +++ /dev/null @@ -1,28 +0,0 @@ -# Median Filter — Overview - -## What it is -A non-linear sliding-window filter that outputs the **median** (middle value) of the last `N` -samples instead of their average. - -## Why it matters (embedded) -Impulsive noise — dropped ADC samples, EMI clicks, salt-and-pepper glitches — is exactly the case -where a moving average fails: a single huge outlier drags the mean. The median ignores such -outliers entirely, using only comparisons (no multiplies), making it a cheap, robust front-end -clean-up for noisy sensor streams. - -## How it works (intuition) -Sort the window and take the centre element. Because a spike lands at an *end* of the sorted order, -it never reaches the middle unless it forms a majority of the window. Step edges are preserved -because the median snaps to whichever level owns the majority of the window. - -## Key parameters -- **N (window length, odd)** — larger `N` rejects wider bursts but adds `(N−1)/2` samples of lag - and rounds off narrow legitimate peaks. - -## Reference -T. Huang, G. Yang, G. Tang, "A fast two-dimensional median filtering algorithm," -*IEEE Trans. Acoustics, Speech, and Signal Processing*, 27(1), 1979. - -## See also -`MovingAverage` (linear, smears spikes), `SavitzkyGolayFilter` (peak-preserving linear), -`ExponentialMovingAverage` (cheap IIR smoother). diff --git a/roadmap/filters/passive/MedianFilter/implementation.md b/roadmap/filters/passive/MedianFilter/implementation.md deleted file mode 100644 index 3df06a38..00000000 --- a/roadmap/filters/passive/MedianFilter/implementation.md +++ /dev/null @@ -1,66 +0,0 @@ -# Median Filter (Sliding Window) — Implementation Pseudocode - -> Roadmap ref: #6 (Tier 2) · Target: `numerical/filters/passive` · Namespace `filters::passive` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class MedianFilter: # N odd - array window # last N samples in arrival order (ring) - array scratch # sort buffer (no heap) - index head = 0 # ring write position - count filled = 0 # samples seen during warm-up -``` - -## Interface - -``` -MedianFilter(T initial = 0) -T Filter(T input) # hot path -void Reset(T value = 0) -``` - -## Algorithm (pseudocode) - -``` -function Filter(x): # OPTIMIZE_FOR_SPEED - window[head] = x # overwrite oldest sample - head = (head + 1) mod N - scratch = window # copy N words - insertion_sort(scratch) # bounded, N small & fixed - return scratch[N / 2] # middle element = median -``` - -## Complexity & memory - -- Time: `O(N)` per sample for insertion sort on small fixed `N` (`O(N²)` worst case, but `N` is a - compile-time constant, typically 3–9). -- Memory: `O(N)` — one ring buffer plus one sort scratch buffer, all stack/static. - -## Numerical / embedded notes - -- Purely comparison-based: only copies and compares samples, never adds or multiplies, so there is - **no coefficient quantization and no arithmetic round-off** on the hot path. -- `N` must be odd for a unique centre element; even `N` would require averaging the two central - samples (introduces arithmetic on the two central samples). -- Non-linear: rejects isolated impulses / salt-and-pepper spikes while preserving step edges that a - linear average would smear. -- Huang et al. give an `O(1)`-update running-histogram variant; for small embedded windows the - direct insertion sort is simpler and cache-friendly. -- Warm-up: pre-fill the window with the seed value so early outputs are well defined. -- Float-only: `static_assert(std::is_floating_point_v)`; the generic `T` signature keeps a - `Q15`/`Q31` specialisation cheap to add later. - -## Deployment - -- Header: `numerical/filters/passive/MedianFilter.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Filter`, and - `extern template class MedianFilter;` under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/filters/passive/MedianFilter.cpp` → - `template class MedianFilter;` -- Test: `numerical/filters/passive/test/TestMedianFilter.cpp` -- Doc: `doc/filters/passive/MedianFilter.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestMedianFilter.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. diff --git a/roadmap/filters/passive/MedianFilter/tests.md b/roadmap/filters/passive/MedianFilter/tests.md deleted file mode 100644 index e837db48..00000000 --- a/roadmap/filters/passive/MedianFilter/tests.md +++ /dev/null @@ -1,50 +0,0 @@ -# Median Filter — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestMedianFilter : public ::testing::Test: - MedianFilter med{} # window length N = 3 -# each case below is a TEST_F(TestMedianFilter, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -rejects_single_impulse: - Arrange: N = 3, input = [0.1, 0.1, 0.9, 0.1, 0.1] (spike at index 2) - Act: collect y - Assert: spike suppressed — median output stays ≈ 0.1 - -preserves_step_edge: - Arrange: input = [0, 0, 1, 1, 1] - Assert: output steps 0 -> 1 without overshoot or smearing - -constant_input_passthrough: - Arrange: feed constant c - Assert: output == c for all samples after warm-up - -sorted_middle_is_returned: - Arrange: window = [0.3, 0.1, 0.2] - Assert: output == 0.2 (true median, not mean) - -majority_spike_passes: - Arrange: N = 3, input = [0, 0.9, 0.9, 0] (spike is a majority) - Assert: median follows the majority (0.9) — documents the N/2 rejection limit - -reset_clears_window: - Arrange: run samples, Reset(0) - Assert: window re-seeded to 0; median == 0 until new data dominates -``` - -## Reference vectors - -- `N = 3`, `[2, 80, 6]` (unsorted) ⇒ median `6`. -- `N = 5`, `[5, 5, 100, 5, 5]` ⇒ median `5` (impulse fully rejected). - -## Edge cases - -- `N = 1` ⇒ pass-through. -- Monotonic ramp input: output tracks with a fixed `(N−1)/2`-sample lag.