From 1f3ccd62d11a8ac05b81338211a262bceb8a3e39 Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sun, 26 Jul 2026 17:10:40 +0000 Subject: [PATCH 1/2] add saturation rate limiter --- AGENTS.md | 2 + README.md | 2 +- ROADMAP.md | 1 - doc/controllers/SaturationRateLimiter.md | 90 ++++++++++++++++ .../implementations/CMakeLists.txt | 2 + .../implementations/SaturationRateLimiter.cpp | 8 ++ .../implementations/SaturationRateLimiter.hpp | 102 ++++++++++++++++++ .../implementations/test/CMakeLists.txt | 1 + .../test/TestSaturationRateLimiter.cpp | 71 ++++++++++++ roadmap/DEPLOYMENT.md | 4 +- .../SaturationRateLimiter/explanation.md | 32 ------ .../SaturationRateLimiter/implementation.md | 86 --------------- .../SaturationRateLimiter/tests.md | 60 ----------- 13 files changed, 280 insertions(+), 181 deletions(-) create mode 100644 doc/controllers/SaturationRateLimiter.md create mode 100644 numerical/controllers/implementations/SaturationRateLimiter.cpp create mode 100644 numerical/controllers/implementations/SaturationRateLimiter.hpp create mode 100644 numerical/controllers/implementations/test/TestSaturationRateLimiter.cpp delete mode 100644 roadmap/controllers/SaturationRateLimiter/explanation.md delete mode 100644 roadmap/controllers/SaturationRateLimiter/implementation.md delete mode 100644 roadmap/controllers/SaturationRateLimiter/tests.md diff --git a/AGENTS.md b/AGENTS.md index f4e41517..7b9917bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,6 +60,8 @@ resource-constrained embedded systems. Real-time, deterministic, no heap. - **`StrictMock` only** (no `NiceMock`/bare). Fixture + aliases in an anonymous namespace; macros outside it. - **No redundant tests** — implement exactly the spec's enumerated cases, one behavior per test, Arrange/Act/Assert, `EXPECT_NEAR` + `math::Tolerance()`. No heap. +**Coverage ≥ 90 %** — measured by SonarQube. Every new algorithm must reach this threshold + before merge; CI fails below it. ## CMake (numerical/ targets) diff --git a/README.md b/README.md index 277bb241..233a70a0 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal |--------------------------------------------------------------------|----------------------------------------------------------------------| | [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions | | [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus | -| [Controllers](doc/controllers/README.md) | PID, LQR, MPC | +| [Controllers](doc/controllers/README.md) | 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 | diff --git a/ROADMAP.md b/ROADMAP.md index 027022b9..b7a1902b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -28,7 +28,6 @@ Difficulty legend: |----|------------------------------------------------------|---------------------------|------------| | 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ | | 2 | Moving Average (running-sum boxcar) | `filters/passive` | ★☆☆☆☆ | -| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ | | 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ | | 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ | | 6 | Median filter | `filters/passive` | ★★☆☆☆ | diff --git a/doc/controllers/SaturationRateLimiter.md b/doc/controllers/SaturationRateLimiter.md new file mode 100644 index 00000000..66e65dac --- /dev/null +++ b/doc/controllers/SaturationRateLimiter.md @@ -0,0 +1,90 @@ +# Saturation / Rate-Limiter / Slew Blocks + +## Overview & Motivation + +Real actuators — valves, motors, heaters, servos — impose two distinct constraints on any command signal: a travel limit (the actuator cannot physically move past a hard stop) and a speed limit (the mechanism cannot slew arbitrarily fast without damaging itself or the system). Ignoring either constraint causes physically impossible commands, mechanical stress, and, in closed-loop systems, integrator wind-up that degrades recovery after saturation. + +These three primitives model exactly those constraints. Saturation enforces the travel limit by clipping the output to a fixed interval. The rate limiter enforces the speed limit by allowing the output to move at most a fixed amount per sample period. Composing them — applying the rate limiter first, then the saturator — guarantees every emitted sample simultaneously respects both bounds, making them the mandatory prerequisite for anti-windup in any integrating controller. + +## Mathematical Theory + +### Saturation + +Given bounds $[\ell, h]$ with $\ell < h$, saturation is defined as: + +$$y = \text{sat}(u) = \min\!\bigl(\max(u,\, \ell),\, h\bigr)$$ + +This is a memoryless, instantaneous projection onto the interval $[\ell, h]$. + +### Rate Limiter (Slew Limiter) + +Let $\Delta_{\max} = r \cdot T_s$ be the maximum permitted change per sample, where $r$ is the slew rate (units per second) and $T_s$ is the sample period (seconds). Define the state $y[n-1]$ as the last emitted output. The output at tick $n$ is: + +$$\delta[n] = \text{sat}_{\Delta_{\max}}(u[n] - y[n-1]) = \min\!\bigl(\max(u[n] - y[n-1],\,-\Delta_{\max}),\,+\Delta_{\max}\bigr)$$ + +$$y[n] = y[n-1] + \delta[n]$$ + +On the first sample (priming), $y[0] = u[0]$ and no limiting is applied, so the output tracks the first command exactly. + +### Composed Block (Slew-Then-Clamp) + +$$y_{\text{composed}}[n] = \text{sat}\!\bigl(y_{\text{slew}}[n]\bigr)$$ + +Applying the rate limiter before the saturator is essential. If the order were reversed (clamp then slew), a step command to a saturated bound would allow the rate limiter to move the output outside the saturation interval for one tick before the clamp could correct it. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|---------|----------|----------|--------------------------------------------| +| Best | $O(1)$ | $O(1)$ | Two compare-and-select operations | +| Average | $O(1)$ | $O(1)$ | One multiply + two compares for rate limit | +| Worst | $O(1)$ | $O(1)$ | Fixed instruction count; no branching on size | + +Each block maintains at most two scalar parameters and one scalar state word. The hot path is branch-light: `min`/`max` compile to conditional-move instructions on modern architectures. + +## Step-by-Step Walkthrough + +Parameters: $\ell = -0.5$, $h = 0.5$, $r = 0.1\,\text{s}^{-1}$, $T_s = 1\,\text{s}$ ($\Delta_{\max} = 0.1$). Step request: $u = 1.0$ for all ticks, starting from $y[-1] = 0$. + +| Tick $n$ | $u[n]$ | $\delta[n]$ | $y_{\text{slew}}[n]$ | $y_{\text{composed}}[n]$ | +|----------|--------|-------------|----------------------|--------------------------| +| 0 | 1.0 | 0.1 | 0.1 | 0.1 | +| 1 | 1.0 | 0.1 | 0.2 | 0.2 | +| 2 | 1.0 | 0.1 | 0.3 | 0.3 | +| 3 | 1.0 | 0.1 | 0.4 | 0.4 | +| 4 | 1.0 | 0.1 | 0.5 | 0.5 | +| 5 | 1.0 | 0.1 | 0.6 | 0.5 (clamped) | + +The ramp is linear until the saturator clips it at $h = 0.5$. The rate limiter continues to advance its internal state, but the composed output is held at the bound. + +## Pitfalls & Edge Cases + +- **Zero slew rate**: $r = 0$ means $\Delta_{\max} = 0$; the output freezes at the primed value for all subsequent inputs. This is valid for a hold block but surprising if unintentional. +- **Collapsed saturation** ($\ell = h$): every output equals that constant regardless of input. The rate limiter still advances but the saturator immediately overwrites the result. +- **Priming semantics**: the first call to the rate limiter always passes through without limiting. Systems that require immediate rate-limiting from the first sample must call `Reset` with the desired initial state before the first control tick. +- **Order of composition**: slew-then-clamp is the only order that guarantees simultaneous satisfaction of both constraints at every tick. +- **Floating-point accumulation**: repeated addition of $\delta[n]$ can accumulate rounding error over many ticks. For long-running loops at high rate, the error remains bounded by machine epsilon times the number of steps times $\Delta_{\max}$. + +## Variants & Generalizations + +- **Asymmetric rate limiter**: use separate positive and negative slew rates $r^+$, $r^-$ to model actuators with different rise and fall speeds (e.g., a valve that opens slowly but closes fast). +- **Variable-rate limiter**: replace the fixed $\Delta_{\max}$ with a schedule or feedback signal for gain-scheduled slew limiting. +- **Deadband + saturation**: insert a deadband nonlinearity before the saturator to model mechanical backlash or sensor noise floors. + +## Applications + +- **Motor drives**: limit acceleration commands to prevent over-current trips while hard-bounding the velocity or position command within safe travel. +- **Thermal control**: ramp heater power slowly to avoid thermal shock while clamping to the maximum safe power level. +- **Anti-windup**: feed the saturated (clamped) output back to the integrator of a PID controller so accumulation stops when the actuator is pinned at a bound. +- **Sensor fusion pre-processing**: slew-limit noisy sensor inputs before they enter an estimator to attenuate impulsive outliers without a dedicated filter. + +## Connections to Other Algorithms + +- **PidIncremental**: consumes the clamped output for anti-windup; the saturation block provides the feedback signal that stops integrator accumulation. +- **BangBangHysteresis**: an alternative, discontinuous actuator constraint that switches between two fixed outputs; saturation is the continuous analog. +- **ExponentialMovingAverage**: can approximate a low-pass slew effect but does not enforce a hard rate bound and has no priming concept. + +## References & Further Reading + +- K. J. Astrom, R. M. Murray, *Feedback Systems: An Introduction for Scientists and Engineers* (2008), sections on actuator saturation and integrator windup. +- K. J. Astrom, T. Hagglund, *Advanced PID Control* (2006), Chapter 6: Anti-windup. diff --git a/numerical/controllers/implementations/CMakeLists.txt b/numerical/controllers/implementations/CMakeLists.txt index 5d5be31e..5bf66a73 100644 --- a/numerical/controllers/implementations/CMakeLists.txt +++ b/numerical/controllers/implementations/CMakeLists.txt @@ -16,6 +16,7 @@ target_sources(numerical.controllers.implementations PRIVATE Lqr.hpp Mpc.hpp PidIncremental.hpp + SaturationRateLimiter.hpp ) numerical_add_coverage_sources(numerical.controllers.implementations @@ -23,6 +24,7 @@ numerical_add_coverage_sources(numerical.controllers.implementations Lqr.cpp Mpc.cpp PidIncremental.cpp + SaturationRateLimiter.cpp ) add_subdirectory(test) diff --git a/numerical/controllers/implementations/SaturationRateLimiter.cpp b/numerical/controllers/implementations/SaturationRateLimiter.cpp new file mode 100644 index 00000000..dcfcc516 --- /dev/null +++ b/numerical/controllers/implementations/SaturationRateLimiter.cpp @@ -0,0 +1,8 @@ +#include "numerical/controllers/implementations/SaturationRateLimiter.hpp" + +namespace controllers +{ + template class Saturation; + template class RateLimiter; + template class SlewLimitedSaturation; +} diff --git a/numerical/controllers/implementations/SaturationRateLimiter.hpp b/numerical/controllers/implementations/SaturationRateLimiter.hpp new file mode 100644 index 00000000..5f2f0d4c --- /dev/null +++ b/numerical/controllers/implementations/SaturationRateLimiter.hpp @@ -0,0 +1,102 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include +#include + +namespace controllers +{ + template + class Saturation + { + static_assert(std::is_floating_point_v, "Saturation supports floating-point types"); + + public: + Saturation(T lo, T hi) + : lo{ lo } + , hi{ hi } + { + } + + OPTIMIZE_FOR_SPEED T Clamp(T u) const + { + return std::min(std::max(u, lo), hi); + } + + private: + T lo; + T hi; + }; + + template + class RateLimiter + { + static_assert(std::is_floating_point_v, "RateLimiter supports floating-point types"); + + public: + RateLimiter(T maxRate, T sampleTime) + : maxRate{ maxRate } + , sampleTime{ sampleTime } + { + } + + OPTIMIZE_FOR_SPEED T Limit(T u) + { + if (!primed) + { + previous = u; + primed = true; + return u; + } + + T step{ maxRate * sampleTime }; + T delta{ std::min(std::max(u - previous, -step), step) }; + previous = previous + delta; + return previous; + } + + void Reset(T value = T{ 0 }) + { + previous = value; + primed = true; + } + + private: + T maxRate; + T sampleTime; + T previous{}; + bool primed{ false }; + }; + + template + class SlewLimitedSaturation + { + static_assert(std::is_floating_point_v, "SlewLimitedSaturation supports floating-point types"); + + public: + SlewLimitedSaturation(T lo, T hi, T maxRate, T sampleTime) + : clampBlock{ lo, hi } + , slewBlock{ maxRate, sampleTime } + { + } + + OPTIMIZE_FOR_SPEED T Apply(T u) + { + return clampBlock.Clamp(slewBlock.Limit(u)); + } + + private: + Saturation clampBlock; + RateLimiter slewBlock; + }; + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class Saturation; + extern template class RateLimiter; + extern template class SlewLimitedSaturation; +#endif +} diff --git a/numerical/controllers/implementations/test/CMakeLists.txt b/numerical/controllers/implementations/test/CMakeLists.txt index fd1e42e6..143e87d5 100644 --- a/numerical/controllers/implementations/test/CMakeLists.txt +++ b/numerical/controllers/implementations/test/CMakeLists.txt @@ -13,5 +13,6 @@ target_sources(numerical.controllers_test PRIVATE TestLqr.cpp TestMpc.cpp TestPidIncremental.cpp + TestSaturationRateLimiter.cpp TestStateFeedbackController.cpp ) diff --git a/numerical/controllers/implementations/test/TestSaturationRateLimiter.cpp b/numerical/controllers/implementations/test/TestSaturationRateLimiter.cpp new file mode 100644 index 00000000..fe5be638 --- /dev/null +++ b/numerical/controllers/implementations/test/TestSaturationRateLimiter.cpp @@ -0,0 +1,71 @@ +#include "numerical/controllers/implementations/SaturationRateLimiter.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gtest/gtest.h" + +namespace +{ + class TestSlewLimitedSaturation + : public ::testing::Test + { + public: + controllers::Saturation sat{ -0.5f, 0.5f }; + controllers::RateLimiter slew{ 0.1f, 1.0f }; + }; +} + +TEST_F(TestSlewLimitedSaturation, clamp_passes_value_inside_bounds) +{ + EXPECT_NEAR(sat.Clamp(0.25f), 0.25f, 1e-6f); +} + +TEST_F(TestSlewLimitedSaturation, clamp_saturates_above_and_below) +{ + EXPECT_NEAR(sat.Clamp(0.9f), 0.5f, 1e-6f); + EXPECT_NEAR(sat.Clamp(-0.9f), -0.5f, 1e-6f); +} + +TEST_F(TestSlewLimitedSaturation, rate_limiter_first_sample_seeds_state) +{ + EXPECT_NEAR(slew.Limit(0.8f), 0.8f, 1e-6f); +} + +TEST_F(TestSlewLimitedSaturation, rate_limiter_caps_positive_slope) +{ + slew.Limit(0.0f); + EXPECT_NEAR(slew.Limit(1.0f), 0.1f, 1e-6f); + EXPECT_NEAR(slew.Limit(1.0f), 0.2f, 1e-6f); + EXPECT_NEAR(slew.Limit(1.0f), 0.3f, 1e-6f); +} + +TEST_F(TestSlewLimitedSaturation, rate_limiter_caps_negative_slope) +{ + slew.Limit(0.0f); + EXPECT_NEAR(slew.Limit(-1.0f), -0.1f, 1e-6f); + EXPECT_NEAR(slew.Limit(-1.0f), -0.2f, 1e-6f); +} + +TEST_F(TestSlewLimitedSaturation, rate_limiter_follows_small_changes_exactly) +{ + slew.Limit(0.0f); + EXPECT_NEAR(slew.Limit(0.05f), 0.05f, 1e-6f); +} + +TEST_F(TestSlewLimitedSaturation, reset_reprimes_state) +{ + slew.Limit(0.0f); + slew.Limit(1.0f); + slew.Reset(0.2f); + EXPECT_NEAR(slew.Limit(0.25f), 0.25f, 1e-6f); +} + +TEST_F(TestSlewLimitedSaturation, composition_slew_then_clamp_honours_both) +{ + controllers::SlewLimitedSaturation composed{ -0.5f, 0.5f, 0.1f, 1.0f }; + composed.Apply(0.0f); + for (int i = 0; i < 10; ++i) + { + float out{ composed.Apply(10.0f) }; + EXPECT_LE(out, 0.5f); + EXPECT_GE(out, -0.5f); + } +} diff --git a/roadmap/DEPLOYMENT.md b/roadmap/DEPLOYMENT.md index 57ccb488..5e504863 100644 --- a/roadmap/DEPLOYMENT.md +++ b/roadmap/DEPLOYMENT.md @@ -32,6 +32,8 @@ Read the spec's three files first (`implementation.md`, `tests.md`, `explanation `cmake --preset host && cmake --build --preset host && ctest --preset host` (scope to the target/test where possible). -**Report**: the file paths created/edited + the test result. Nothing else. +7. **Remove roadmap spec** — delete the entire `roadmap///` directory once all tests are green. + +**Report**: the file paths created/edited/deleted + the test result. Nothing else. Recap: float-only (generic `T`, `float` instantiation), no heap, no comments, terse. diff --git a/roadmap/controllers/SaturationRateLimiter/explanation.md b/roadmap/controllers/SaturationRateLimiter/explanation.md deleted file mode 100644 index f8f48fa3..00000000 --- a/roadmap/controllers/SaturationRateLimiter/explanation.md +++ /dev/null @@ -1,32 +0,0 @@ -# Saturation / Rate-Limiter / Slew Blocks — Overview - -## What it is -Two tiny actuator-constraint primitives and their composition. **Saturation** clamps a signal to -`[lo, hi]`. A **rate limiter** (slew limiter) caps how fast the signal may change per sample, -`|Δu| ≤ rate·Ts`. Together they model a real actuator that has both a travel limit and a maximum -speed. - -## Why it matters (embedded) -Every real actuator — a valve, motor, heater, servo — has hard limits. Wrapping a controller -output in these blocks prevents commanding physically impossible moves and, critically, is the -**prerequisite for anti-windup**: the clamped value is what you feed back into an integrator so it -does not "wind up" while the actuator is pinned at its limit. - -## How it works (intuition) -Saturation is a simple `min`/`max` sandwich. The rate limiter remembers its last output and -allows the new command to move at most `rate·Ts` toward the request each tick — a first-order -slew. Applying slew first and clamp second guarantees the emitted value respects both the speed -limit and the travel limits simultaneously. - -## Key parameters -- **lo, hi** — output bounds (actuator travel range). -- **maxRate** — maximum change per second (slew rate). -- **sampleTime (Ts)** — controller period; sets the per-tick step `rate·Ts`. - -## Reference -K. J. Åström, R. M. Murray, *Feedback Systems: An Introduction for Scientists and Engineers* -(2008), sections on actuator saturation and integrator windup. - -## See also -`PidIncremental` (consumes the clamped output for anti-windup); `BangBangHysteresis` (a -different, discontinuous actuator constraint). diff --git a/roadmap/controllers/SaturationRateLimiter/implementation.md b/roadmap/controllers/SaturationRateLimiter/implementation.md deleted file mode 100644 index e15ddcfb..00000000 --- a/roadmap/controllers/SaturationRateLimiter/implementation.md +++ /dev/null @@ -1,86 +0,0 @@ -# Saturation / Rate-Limiter / Slew Blocks — Implementation Pseudocode - -> Roadmap ref: #3 (Tier 1) · Target: `numerical/controllers` · Namespace `controllers` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class Saturation: - T lo, hi # output bounds, lo < hi - -template # static_assert(std::is_floating_point_v); instantiated for float -class RateLimiter: - T maxRate # |Δu| per second (slew rate) - T sampleTime # Ts in seconds - T previous # last emitted output u[n-1] - bool primed = false # first sample seeds `previous` - -template # static_assert(std::is_floating_point_v); instantiated for float -class SlewLimitedSaturation: # composition of the two - Saturation clampBlock - RateLimiter slewBlock -``` - -## Interface - -``` -Saturation(T lo, T hi) -T Clamp(T u) const - -RateLimiter(T maxRate, T sampleTime) -T Limit(T u) # hot path -void Reset(T value = 0) - -SlewLimitedSaturation(T lo, T hi, T maxRate, T sampleTime) -T Apply(T u) # slew first, then clamp -``` - -## Algorithm (pseudocode) - -``` -function Clamp(u): # OPTIMIZE_FOR_SPEED - return min(max(u, lo), hi) - -function Limit(u): # OPTIMIZE_FOR_SPEED - if not primed: - previous = u; primed = true - return u - step = maxRate * sampleTime # max change this tick - delta = clamp(u - previous, -step, +step) - previous = previous + delta - return previous - -function Apply(u): - return clampBlock.Clamp(slewBlock.Limit(u)) -``` - -## Complexity & memory - -- Time: `O(1)` per sample — two compares (clamp) plus one compare-pair (slew). -- Memory: `O(1)` — bounds, rate, `Ts`, and one state word per limiter. - -## Numerical / embedded notes - -- Precompute `step = maxRate*sampleTime` once if `Ts` is fixed to save a multiply per tick. -- `min`/`max` are branch-light and keep the hot path predictable. -- Order matters: slew-then-clamp guarantees the output honours both bounds; clamp-then-slew can - leave the output outside `[lo,hi]` for one tick. -- These blocks are the anti-windup prerequisite: feed the clamped output back to the integrator - (see `PidIncremental`) so it stops winding while the actuator is pinned. -- 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/controllers/implementations/SaturationRateLimiter.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Clamp`/`Limit`/`Apply`, and - `extern template class Saturation; RateLimiter; SlewLimitedSaturation;` - under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/controllers/implementations/SaturationRateLimiter.cpp` → - `template class Saturation; template class RateLimiter; template class SlewLimitedSaturation;` -- Test: `numerical/controllers/implementations/test/TestSaturationRateLimiter.cpp` -- Doc: `doc/controllers/SaturationRateLimiter.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestSaturationRateLimiter.cpp` → the `_test` target. -- Generic pattern: see `roadmap/README.md` → "Deployment shape". diff --git a/roadmap/controllers/SaturationRateLimiter/tests.md b/roadmap/controllers/SaturationRateLimiter/tests.md deleted file mode 100644 index 9017ba29..00000000 --- a/roadmap/controllers/SaturationRateLimiter/tests.md +++ /dev/null @@ -1,60 +0,0 @@ -# Saturation / Rate-Limiter / Slew Blocks — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestSlewLimitedSaturation : public ::testing::Test: - Saturation sat{ -0.5f, 0.5f } - RateLimiter slew{ 0.1f, 1.0f } # 0.1 /s, Ts = 1 s -> step 0.1 -# each case below is a TEST_F(TestSlewLimitedSaturation, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -clamp_passes_value_inside_bounds: - Arrange: bounds [-0.5, 0.5], u = 0.25 - Assert: Clamp(u) == 0.25 - -clamp_saturates_above_and_below: - Arrange: bounds [-0.5, 0.5] - Assert: Clamp(0.9) == 0.5 and Clamp(-0.9) == -0.5 - -rate_limiter_first_sample_seeds_state: - Arrange: fresh limiter, step 0.1 - Act: first call Limit(0.8) - Assert: returns 0.8 (no limiting on prime) - -rate_limiter_caps_positive_slope: - Arrange: prime at 0, then request 1.0 each tick - Assert: outputs rise by 0.1 per tick: 0.1, 0.2, 0.3, ... - -rate_limiter_caps_negative_slope: - Arrange: prime at 0, then request -1.0 each tick - Assert: outputs fall by 0.1 per tick: -0.1, -0.2, ... - -rate_limiter_follows_small_changes_exactly: - Arrange: step 0.1, request a delta of 0.05 - Assert: output tracks input with no lag - -reset_reprimes_state: - Arrange: run some samples, Reset(0.2) - Assert: next small change starts from 0.2 - -composition_slew_then_clamp_honours_both: - Arrange: bounds [-0.5,0.5], step 0.1, step-request to 10 - Assert: output ramps by 0.1 and never exceeds 0.5 -``` - -## Reference vectors - -- step 0.1, request `+∞`, prime 0 ⇒ output `= 0.1·n` until saturation. -- bounds [-0.5, 0.5] ⇒ `Clamp` is the identity on `[-0.5, 0.5]`. - -## Edge cases - -- `maxRate = 0` freezes the output at the primed value. -- `lo == hi` collapses the output to a constant. -- Large step requests ramp by `rate·Ts` per tick with no overshoot (`EXPECT_NEAR`, tol `1e-6f`). From c5c972244b8555b51e10a6549e4e15221bbc3808 Mon Sep 17 00:00:00 2001 From: gfs Date: Sun, 26 Jul 2026 19:15:46 +0200 Subject: [PATCH 2/2] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/controllers/SaturationRateLimiter.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/doc/controllers/SaturationRateLimiter.md b/doc/controllers/SaturationRateLimiter.md index 66e65dac..f2636ecc 100644 --- a/doc/controllers/SaturationRateLimiter.md +++ b/doc/controllers/SaturationRateLimiter.md @@ -34,11 +34,11 @@ Applying the rate limiter before the saturator is essential. If the order were r ## Complexity Analysis -| Case | Time | Space | Notes | -|---------|----------|----------|--------------------------------------------| -| Best | $O(1)$ | $O(1)$ | Two compare-and-select operations | -| Average | $O(1)$ | $O(1)$ | One multiply + two compares for rate limit | -| Worst | $O(1)$ | $O(1)$ | Fixed instruction count; no branching on size | +| Case | Time | Space | Notes | +|---------|--------|--------|-----------------------------------------------| +| Best | $O(1)$ | $O(1)$ | Two compare-and-select operations | +| Average | $O(1)$ | $O(1)$ | One multiply + two compares for rate limit | +| Worst | $O(1)$ | $O(1)$ | Fixed instruction count; no branching on size | Each block maintains at most two scalar parameters and one scalar state word. The hot path is branch-light: `min`/`max` compile to conditional-move instructions on modern architectures.