diff --git a/README.md b/README.md index a7c1b96e..7ae55c52 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, Feedforward/2-DOF | | [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, Median Filter | +| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, Complementary, 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 6314a0e0..9c43e759 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -28,7 +28,6 @@ Difficulty legend: | # | Component | Target module | Difficulty | |----|------------------------------------------------------|---------------------------|------------| | 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` | ★★☆☆☆ | @@ -106,12 +105,6 @@ Difficulty legend: - **Algorithm / paper:** P. Kalata, "The tracking index: A generalized parameter for α-β and α-β-γ target trackers," *IEEE Trans. AES*, 20(2), 1984. - **Reuses:** `math::LinearTimeInvariant`, `filters/active` patterns. -### 9. Complementary filter -- **What:** Frequency-domain fusion of a fast/biased sensor (gyro) with a slow/noisy one (accel/mag): `θ = a·(θ+ω·Ts) + (1−a)·θ_accel`. -- **Embedded value:** The default low-cost attitude/tilt estimator on every IMU-based project. -- **Algorithm / paper:** W. T. Higgins, "A Comparison of Complementary and Kalman Filtering," *IEEE Trans. AES*, 11(3), 1975. -- **Reuses:** `math::Geometry3D`, item 1. - ### 10. Gain-scheduled controller - **What:** Interpolates a set of precomputed controller gains across a scheduling variable (speed, load, operating point). - **Embedded value:** Extends linear controllers to mildly nonlinear plants without online redesign. diff --git a/doc/filters/active/ComplementaryFilter.md b/doc/filters/active/ComplementaryFilter.md new file mode 100644 index 00000000..119055ee --- /dev/null +++ b/doc/filters/active/ComplementaryFilter.md @@ -0,0 +1,122 @@ +# Complementary Filter + +## Overview & Motivation + +Real-time attitude and heading estimation requires fusing two fundamentally different sensor +modalities: a **gyroscope** that integrates angular rate to produce a short-term angle estimate +(fast response, low noise, but subject to drift) and an **accelerometer or magnetometer** that +reads the angle directly (accurate at rest, noisy during motion, slow dynamics). Neither sensor +alone is sufficient. The complementary filter solves the fusion problem with two multiplies +and two adds per sample, making it the default tilt estimator on virtually every IMU-based +embedded project where a full Kalman filter is unaffordable. + +## Mathematical Theory + +### Frequency-Domain Complement + +The two sensor paths are complementary in the transfer-function sense: the gyro path acts as a +**first-order high-pass filter** and the direct-angle path acts as a **first-order low-pass filter** +sharing the same crossover frequency $\omega_c = 1/\tau$. Their sum is identically unity for all +frequencies: + +$$H_{HP}(s) + H_{LP}(s) = 1$$ + +This ensures that no frequency content is amplified or attenuated by the fusion itself. + +### Discrete-Time Update Equation + +Given the fused angle $\theta_k$, gyro rate $\omega_k$, accelerometer angle $\theta_{acc,k}$, +sample period $T_s$, and blend weight $\alpha \in [0,1]$: + +$$\theta_{k+1} = \alpha\,(\theta_k + \omega_k\,T_s) + (1-\alpha)\,\theta_{acc,k}$$ + +The term $\theta_k + \omega_k T_s$ is the **high-pass path** (integration of the fast sensor), +and $\theta_{acc,k}$ is the **low-pass path** (direct measurement from the slow sensor). + +### Design Parameter + +The single tuning knob is the crossover time constant $\tau$, which maps to $\alpha$ via: + +$$\alpha = \frac{\tau}{\tau + T_s}$$ + +Below $1/\tau$ the filter trusts the accelerometer; above it, the gyroscope. Typical embedded +values are $\tau = 0.5$–$2$ s, corresponding to $\alpha \approx 0.98$ at $T_s = 10$ ms. + +### Heading Wrap (Shortest-Arc Blend) + +When the state is a heading angle in $(-\pi, \pi]$, a naive linear blend can jump by $2\pi$ near +the seam. Instead the blend is performed along the shortest arc: + +$$\delta = \mathrm{WrapToPi}(\theta_{acc} - \hat{\theta})$$ +$$\theta_{k+1} = \mathrm{WrapToPi}\!\left(\hat{\theta} + (1-\alpha)\,\delta\right)$$ + +where $\mathrm{WrapToPi}(x) = \bigl((x + \pi) \bmod 2\pi\bigr) - \pi$. + +## Complexity Analysis + +| Operation | Time | Space | Notes | +|-----------|--------|--------|--------------------------------------------| +| Update | $O(1)$ | $O(1)$ | 2 multiplies, 2 adds; 1 fmod when wrapping | +| Reset | $O(1)$ | $O(1)$ | Single state write | + +Total storage: one angle word plus two constant coefficients. + +## Step-by-Step Walkthrough + +**Setup:** $\alpha = 0.98$, $T_s = 10$ ms, initial angle $= 0$. + +**Sample 1:** gyro rate $\omega = 10$ deg/s $= 0.1745$ rad/s, accel reads $\theta_{acc} = 0.01$ rad. + +$$\hat{\theta} = 0 + 0.1745 \times 0.01 = 0.001745 \text{ rad} \quad (\text{gyro path})$$ +$$\theta_1 = 0.98 \times 0.001745 + 0.02 \times 0.01 = 0.001710 + 0.000200 = 0.001910 \text{ rad}$$ + +**After many samples with zero rate and accel $= 0.2$ rad:** the low-pass term accumulates +and $\theta \to 0.2$ rad as $(1-\alpha)^n \to 0$. + +## Pitfalls & Edge Cases + +- **Alpha at 1:** the gyro path integrates without bound; any constant bias drifts the angle + indefinitely. This is intentional (gyro-only mode) but must be avoided in production. +- **Alpha at 0:** the output equals the accelerometer reading at every step; the gyro is ignored. +- **Heading wrap:** linear blending without shortest-arc correction produces a $2\pi$ jump when + the heading crosses $\pm\pi$. Always enable the wrap mode for heading estimation. +- **Gyro bias:** the filter has no bias estimator. A constant gyro bias produces a bounded + steady-state error of approximately $\text{bias} \cdot T_s \cdot \alpha / (1-\alpha)$. + Pre-subtract a calibrated bias before calling Update. +- **Accelerometer noise during dynamics:** the accel path is unreliable when linear acceleration + is present (non-gravitational). Reduce $(1-\alpha)$ or temporarily freeze the accel correction. + +## Variants & Generalizations + +| Variant | Key Difference | +|----------------------------|-----------------------------------------------------------------------| +| **Mahony filter** | 3-D quaternion formulation with integral gyro-bias estimator | +| **Madgwick filter** | Gradient-descent quaternion fusion; no linearisation | +| **Alpha-Beta filter** | Fixed-gain tracking without a slow sensor; pure high-pass integration | +| **Kalman filter** | Optimal (minimum-variance) fusion; requires noise covariance tuning | +| **Two-step complementary** | Separate pitch/roll from heading; common on 6-DOF IMUs | + +## Applications + +- **IMU tilt estimation** — Roll and pitch from a 6-axis MEMS sensor at low computational cost. +- **Heading fusion** — Combining gyro yaw rate with magnetometer heading. +- **Servo/motor feedback** — Fusing encoder velocity with potentiometer position. +- **Altitude hold** — Mixing barometer (low-pass) with accelerometer integration (high-pass). + +## Connections to Other Algorithms + +| Algorithm | Relationship | +|----------------------------------------------------------------------|--------------------------------------------------------------------------| +| [Exponential Moving Average](../passive/ExponentialMovingAverage.md) | The low-pass path in isolation; $\alpha_{EMA} = 1-\alpha_{CF}$ | +| [Alpha-Beta Filter](AlphaBetaFilter.md) | Complementary filter without a slow-sensor reference; fixed-gain tracker | +| [AHRS Madgwick/Mahony](AhrsMadgwickMahony.md) | 3-D quaternion generalization with gyro-bias estimation | +| [Kalman Filter](KalmanFilter.md) | Statistically optimal generalization requiring $Q$ and $R$ tuning | + +## References & Further Reading + +- W. T. Higgins, "A Comparison of Complementary and Kalman Filtering," *IEEE Transactions on + Aerospace and Electronic Systems*, 11(3), pp. 321–325, 1975. +- S. Madgwick, "An Efficient Orientation Filter for Inertial and Inertial/Magnetic Sensor Arrays," + Technical Report, University of Bristol, 2010. +- R. Mahony, T. Hamel, and J.-M. Pflimlin, "Nonlinear Complementary Filters on the Special + Orthogonal Group," *IEEE Transactions on Automatic Control*, 53(5), pp. 1203–1218, 2008. diff --git a/numerical/filters/active/CMakeLists.txt b/numerical/filters/active/CMakeLists.txt index 323787f2..228aea3a 100644 --- a/numerical/filters/active/CMakeLists.txt +++ b/numerical/filters/active/CMakeLists.txt @@ -12,6 +12,7 @@ target_link_libraries(numerical.filters.active ${NUMERICAL_VISIBILITY} ) target_sources(numerical.filters.active PRIVATE + ComplementaryFilter.hpp ExtendedKalmanFilter.hpp KalmanFilter.hpp KalmanFilterBase.hpp @@ -20,6 +21,7 @@ target_sources(numerical.filters.active PRIVATE ) numerical_add_coverage_sources(numerical.filters.active + ComplementaryFilter.cpp ExtendedKalmanFilter.cpp KalmanFilter.cpp KalmanFilterBase.cpp diff --git a/numerical/filters/active/ComplementaryFilter.cpp b/numerical/filters/active/ComplementaryFilter.cpp new file mode 100644 index 00000000..a8f7d899 --- /dev/null +++ b/numerical/filters/active/ComplementaryFilter.cpp @@ -0,0 +1,6 @@ +#include "numerical/filters/active/ComplementaryFilter.hpp" + +namespace filters +{ + template class ComplementaryFilter; +} diff --git a/numerical/filters/active/ComplementaryFilter.hpp b/numerical/filters/active/ComplementaryFilter.hpp new file mode 100644 index 00000000..09ee159e --- /dev/null +++ b/numerical/filters/active/ComplementaryFilter.hpp @@ -0,0 +1,100 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include +#include +#include +#include + +namespace filters +{ + template + class ComplementaryFilter + { + static_assert(std::is_floating_point_v, "ComplementaryFilter supports floating-point types"); + + public: + explicit ComplementaryFilter(T alpha, T Ts, T initial = T{}, bool wrapAngle = false) noexcept; + + OPTIMIZE_FOR_SPEED T Update(T rate, T measuredAngle) noexcept; + void Reset(T angle = T{}) noexcept; + void SetAlpha(T alpha) noexcept; + + static T AlphaFromTau(T tau, T Ts) noexcept; + + private: + T alpha; + T Ts; + T angle; + bool wrapAngle; + + static T WrapToPi(T x) noexcept; + }; + + //// Implementation //// + + template + ComplementaryFilter::ComplementaryFilter(T alpha, T Ts, T initial, bool wrapAngle) noexcept + : alpha{ alpha } + , Ts{ Ts } + , angle{ initial } + , wrapAngle{ wrapAngle } + { + assert(alpha >= T{} && alpha <= T{ 1 }); + assert(Ts > T{}); + } + + template + OPTIMIZE_FOR_SPEED T ComplementaryFilter::Update(T rate, T measuredAngle) noexcept + { + T predicted{ angle + rate * Ts }; + if (wrapAngle) + { + T delta{ WrapToPi(measuredAngle - predicted) }; + angle = WrapToPi(predicted + (T{ 1 } - alpha) * delta); + } + else + { + angle = alpha * predicted + (T{ 1 } - alpha) * measuredAngle; + } + return angle; + } + + template + void ComplementaryFilter::Reset(T value) noexcept + { + angle = value; + } + + template + void ComplementaryFilter::SetAlpha(T newAlpha) noexcept + { + assert(newAlpha >= T{} && newAlpha <= T{ 1 }); + alpha = newAlpha; + } + + template + T ComplementaryFilter::AlphaFromTau(T tau, T Ts) noexcept + { + return tau / (tau + Ts); + } + + template + T ComplementaryFilter::WrapToPi(T x) noexcept + { + constexpr T pi{ std::numbers::pi_v }; + constexpr T twoPi{ T{ 2 } * std::numbers::pi_v }; + T wrapped{ std::fmod(x + pi, twoPi) }; + if (wrapped < T{}) + wrapped += twoPi; + return wrapped - pi; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class ComplementaryFilter; +#endif +} diff --git a/numerical/filters/active/test/CMakeLists.txt b/numerical/filters/active/test/CMakeLists.txt index 133f8e2d..2737c78e 100644 --- a/numerical/filters/active/test/CMakeLists.txt +++ b/numerical/filters/active/test/CMakeLists.txt @@ -8,6 +8,7 @@ target_link_libraries(numerical.filters.active_test PUBLIC ) target_sources(numerical.filters.active_test PRIVATE + TestComplementaryFilter.cpp TestExtendedKalmanFilter.cpp TestKalmanFilter.cpp TestKalmanSmoother.cpp diff --git a/numerical/filters/active/test/TestComplementaryFilter.cpp b/numerical/filters/active/test/TestComplementaryFilter.cpp new file mode 100644 index 00000000..5b94bad6 --- /dev/null +++ b/numerical/filters/active/test/TestComplementaryFilter.cpp @@ -0,0 +1,123 @@ +#include "numerical/filters/active/ComplementaryFilter.hpp" +#include "numerical/math/Tolerance.hpp" +#include +#include + +namespace +{ + class TestComplementaryFilter + : public ::testing::Test + { + public: + filters::ComplementaryFilter filter{ 0.98f, 0.01f }; + }; +} + +TEST_F(TestComplementaryFilter, static_measurement_converges) +{ + float output{}; + for (int i = 0; i < 500; ++i) + output = filter.Update(0.0f, 0.2f); + + EXPECT_NEAR(output, 0.2f, math::Tolerance()); +} + +TEST_F(TestComplementaryFilter, pure_rotation_follows_gyro) +{ + constexpr float w{ 1.0f }; + constexpr float Ts{ 0.01f }; + constexpr int n{ 5 }; + + float output{}; + for (int i = 0; i < n; ++i) + output = filter.Update(w, 0.0f); + + EXPECT_GT(output, 0.0f); + EXPECT_LT(output, w * Ts * static_cast(n) + math::Tolerance()); +} + +TEST_F(TestComplementaryFilter, rejects_slow_sensor_noise) +{ + constexpr int N{ 100 }; + float noisy[N]{}; + float filtered[N]{}; + + for (int i = 0; i < N; ++i) + { + noisy[i] = (i % 2 == 0) ? 0.1f : -0.1f; + filtered[i] = filter.Update(0.0f, noisy[i]); + } + + float varNoisy{}; + float varFiltered{}; + for (int i = 0; i < N; ++i) + { + varNoisy += noisy[i] * noisy[i]; + varFiltered += filtered[i] * filtered[i]; + } + + EXPECT_LT(varFiltered, varNoisy); +} + +TEST_F(TestComplementaryFilter, rejects_gyro_bias_drift) +{ + constexpr float bias{ 0.01f }; + constexpr int N{ 1000 }; + + float output{}; + for (int i = 0; i < N; ++i) + output = filter.Update(bias, 0.0f); + + EXPECT_LT(std::abs(output), 1.0f); +} + +TEST_F(TestComplementaryFilter, alpha_from_tau_matches_crossover) +{ + constexpr float tau{ 1.0f }; + constexpr float Ts{ 0.01f }; + + const float a{ filters::ComplementaryFilter::AlphaFromTau(tau, Ts) }; + + EXPECT_NEAR(a, tau / (tau + Ts), math::Tolerance()); +} + +TEST_F(TestComplementaryFilter, heading_blend_wraps_shortest_arc) +{ + constexpr float pi{ std::numbers::pi_v }; + filters::ComplementaryFilter headingFilter{ 0.98f, 0.01f, pi - 0.05f, true }; + + float output{}; + for (int i = 0; i < 10; ++i) + output = headingFilter.Update(0.0f, -pi + 0.05f); + + EXPECT_LE(std::abs(output), pi + math::Tolerance()); +} + +TEST_F(TestComplementaryFilter, reset_sets_state) +{ + for (int i = 0; i < 10; ++i) + filter.Update(1.0f, 0.5f); + + filter.Reset(0.1f); + + const float output{ filter.Update(0.0f, 0.0f) }; + EXPECT_NEAR(output, 0.98f * 0.1f, math::Tolerance()); +} + +TEST_F(TestComplementaryFilter, alpha_zero_is_pure_measurement) +{ + filters::ComplementaryFilter pureAccel{ 0.0f, 0.01f }; + + const float output{ pureAccel.Update(5.0f, 0.3f) }; + + EXPECT_NEAR(output, 0.3f, math::Tolerance()); +} + +TEST_F(TestComplementaryFilter, alpha_one_is_pure_integration) +{ + filters::ComplementaryFilter pureGyro{ 1.0f, 0.01f }; + + const float output{ pureGyro.Update(10.0f, 999.0f) }; + + EXPECT_NEAR(output, 10.0f * 0.01f, math::Tolerance()); +} diff --git a/roadmap/filters/active/ComplementaryFilter/explanation.md b/roadmap/filters/active/ComplementaryFilter/explanation.md deleted file mode 100644 index db5e27c0..00000000 --- a/roadmap/filters/active/ComplementaryFilter/explanation.md +++ /dev/null @@ -1,33 +0,0 @@ -# Complementary Filter — Overview - -## What it is -A minimal sensor-fusion filter that blends a **fast but biased** sensor (a gyroscope, integrated to -an angle) with a **slow but drift-free** sensor (an accelerometer or magnetometer that measures the -angle directly): `θ = α·(θ + ω·Ts) + (1−α)·θ_meas`. - -## Why it matters (embedded) -It is the default low-cost tilt/attitude estimator on virtually every IMU project. For two -multiplies and two adds it removes gyro drift and accelerometer noise simultaneously — no matrices, -no covariance, no tuning of a full Kalman filter. On an 8/16-bit MCU it is often the *only* -affordable fusion option. - -## How it works (intuition) -Think of it in the frequency domain: the gyro path is a **high-pass** filter (great at high -frequency, but its integrated bias drifts at DC) and the direct-angle path is a **low-pass** filter -(accurate at DC, noisy at high frequency). Choosing weights that sum to one makes the two transfer -functions **complement** each other — `HP(s) + LP(s) = 1` — so the crossover frequency `1/τ` is the -single design knob. Below it you trust the accel/mag; above it you trust the gyro. - -## Key parameters -- **α (blend weight)** `∈ [0, 1]` — how much to trust the integrated fast sensor. -- **τ (crossover time constant)** — sets the split via `α = τ/(τ+Ts)`. -- **Ts** — sample period. -- **wrap flag** — enable shortest-arc blending when the state is a heading angle. - -## Reference -W. T. Higgins, "A Comparison of Complementary and Kalman Filtering," *IEEE Trans. Aerospace and -Electronic Systems*, 11(3), 1975. - -## See also -`AhrsMadgwickMahony` (3-D quaternion generalization with bias estimation), -`ExponentialMovingAverage` (the low-pass path in isolation), `AlphaBetaFilter` (fixed-gain tracking). diff --git a/roadmap/filters/active/ComplementaryFilter/implementation.md b/roadmap/filters/active/ComplementaryFilter/implementation.md deleted file mode 100644 index 22347275..00000000 --- a/roadmap/filters/active/ComplementaryFilter/implementation.md +++ /dev/null @@ -1,72 +0,0 @@ -# Complementary Filter — Implementation Pseudocode - -> Roadmap ref: #9 (Tier 2) · Target: `numerical/filters/active` · Namespace `filters` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class ComplementaryFilter: - T alpha # blend weight in [0, 1] — trust in the integrated (fast) path - T Ts # sample period - T angle # fused estimate (state) - bool wrapAngle # true ⇒ treat state as a heading in (-pi, pi] -``` - -## Interface - -``` -ComplementaryFilter(T alpha, T Ts, T initial = 0) -T Update(T rate, T measuredAngle) # hot: rate = gyro (fast), measuredAngle = accel/mag (slow) -void Reset(T angle = 0) -void SetAlpha(T alpha) -static T AlphaFromTau(T tau, T Ts) # tau = crossover time constant -``` - -## Algorithm (pseudocode) - -``` -function Update(rate, measuredAngle): # OPTIMIZE_FOR_SPEED - predicted = angle + rate * Ts # high-pass path: integrate the fast sensor - if wrapAngle: - # blend along the shortest arc so the fusion is continuous across ±pi - delta = WrapToPi(measuredAngle - predicted) - angle = WrapToPi(predicted + (1 - alpha) * delta) - else: - # y = alpha*(angle + rate*Ts) + (1 - alpha)*measuredAngle - angle = alpha * predicted + (1 - alpha) * measuredAngle - return angle - -function AlphaFromTau(tau, Ts): - # first-order crossover: high-pass on gyro, low-pass on accel share cutoff 1/tau - return tau / (tau + Ts) -``` - -## Complexity & memory - -- Time: `O(1)` per sample — 2 multiplies, 2 adds (plus one wrap when tracking heading). -- Memory: `O(1)` — a single fused-angle state word and the coefficients. - -## Numerical / embedded notes - -- `alpha` near 1 (e.g. `0.98`) trusts the gyro over the short term while the accel/mag slowly - corrects long-term **drift**; the two paths are exact frequency-domain complements: `HP + LP = 1`. -- Design via `alpha = tau/(tau+Ts)`, where `tau` is the high-pass/low-pass crossover time constant. -- **Angle wrap**: for heading fusion, blend the *shortest* angular distance (`WrapToPi`) — a naive - linear blend jumps by `2*pi` near the ±pi seam. -- Unlike Mahony's filter it does not estimate gyro bias; pre-subtract a calibrated bias if needed. -- 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/active/ComplementaryFilter.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Update`, and - `extern template class ComplementaryFilter;` under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/filters/active/ComplementaryFilter.cpp` → - `template class ComplementaryFilter;` -- Test: `numerical/filters/active/test/TestComplementaryFilter.cpp` -- Doc: `doc/filters/active/ComplementaryFilter.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestComplementaryFilter.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. diff --git a/roadmap/filters/active/ComplementaryFilter/tests.md b/roadmap/filters/active/ComplementaryFilter/tests.md deleted file mode 100644 index 4d30440c..00000000 --- a/roadmap/filters/active/ComplementaryFilter/tests.md +++ /dev/null @@ -1,58 +0,0 @@ -# Complementary Filter — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestComplementaryFilter : public ::testing::Test: - ComplementaryFilter filter{ 0.98f, 0.01f } # alpha = 0.98, Ts = 10 ms -# each case below is a TEST_F(TestComplementaryFilter, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -static_measurement_converges: - Arrange: rate = 0, measuredAngle = 0.2 held for many samples - Act: iterate Update(0, 0.2) - Assert: angle -> 0.2 (low-pass path wins at DC) - -pure_rotation_follows_gyro: - Arrange: constant rate w, measuredAngle = 0 (unusable slow sensor) - Assert: short-term angle ≈ integral(w) = w * Ts * n - -rejects_slow_sensor_noise: - Arrange: rate = 0, measuredAngle = 0 + high-frequency noise - Assert: variance(angle) < variance(measuredAngle) - -rejects_gyro_bias_drift: - Arrange: rate = small constant bias, measuredAngle = 0 (true) - Assert: angle stays bounded (does not integrate to infinity) - -alpha_from_tau_matches_crossover: - Arrange: a = AlphaFromTau(tau, Ts) - Assert: a == tau/(tau+Ts) within tolerance - -heading_blend_wraps_shortest_arc: - Arrange: wrapAngle = true, predicted ≈ +pi-eps, measuredAngle ≈ -pi+eps - Assert: fused angle stays near ±pi, no 2*pi jump - -reset_sets_state: - Arrange: run samples, Reset(0.1) - Assert: internal angle == 0.1 - -alpha_zero_is_pure_measurement / alpha_one_is_pure_integration: - Assert: alpha=0 ⇒ output == measuredAngle; alpha=1 ⇒ output == running gyro integral -``` - -## Reference vectors - -- DC step on the slow sensor ⇒ first-order low-pass rise toward the measured angle. -- Constant gyro rate with dead slow sensor ⇒ output equals the discrete integral `w*Ts*n`. - -## Edge cases - -- Heading wrap across the ±pi seam (both directions). -- `alpha` at bounds (0 ⇒ measurement only, 1 ⇒ integration only, drift unbounded). -- Long run under constant bias ⇒ bounded steady-state error `≈ bias*Ts*alpha/(1-alpha)`.