Repository navigation
feat: add saturation rate limiter #166
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
|
gabrielfrasantos marked this conversation as resolved.
Resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
8 changes: 8 additions & 0 deletions
8
numerical/controllers/implementations/SaturationRateLimiter.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| #include "numerical/controllers/implementations/SaturationRateLimiter.hpp" | ||
|
|
||
| namespace controllers | ||
| { | ||
| template class Saturation<float>; | ||
| template class RateLimiter<float>; | ||
| template class SlewLimitedSaturation<float>; | ||
| } |
102 changes: 102 additions & 0 deletions
102
numerical/controllers/implementations/SaturationRateLimiter.hpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| #pragma once | ||
|
|
||
| #if defined(__GNUC__) || defined(__clang__) | ||
| #pragma GCC optimize("O3", "fast-math") | ||
| #endif | ||
|
|
||
| #include "numerical/math/CompilerOptimizations.hpp" | ||
| #include <algorithm> | ||
| #include <type_traits> | ||
|
|
||
| namespace controllers | ||
| { | ||
| template<typename T> | ||
| class Saturation | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, "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<typename T> | ||
| class RateLimiter | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, "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<typename T> | ||
| class SlewLimitedSaturation | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, "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<T> clampBlock; | ||
| RateLimiter<T> slewBlock; | ||
| }; | ||
|
|
||
| #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD | ||
| extern template class Saturation<float>; | ||
| extern template class RateLimiter<float>; | ||
| extern template class SlewLimitedSaturation<float>; | ||
| #endif | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
71 changes: 71 additions & 0 deletions
71
numerical/controllers/implementations/test/TestSaturationRateLimiter.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<float> sat{ -0.5f, 0.5f }; | ||
| controllers::RateLimiter<float> 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<float> 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); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.