Skip to content

Commit 551547a

Browse files
feat: add saturation rate limiter (#166)
* add saturation rate limiter * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent ed9b147 commit 551547a

12 files changed

Lines changed: 278 additions & 181 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
1818
|--------------------------------------------------------------------|----------------------------------------------------------------------|
1919
| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions |
2020
| [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus |
21-
| [Controllers](doc/controllers/README.md) | PID, LQR, MPC |
21+
| [Controllers](doc/controllers/README.md) | PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation |
2222
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |
2323
| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker (offline), Recursive Least Squares (online) |
2424
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, FIR, IIR, Moving Average |

‎ROADMAP.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ Difficulty legend:
2727
| # | Component | Target module | Difficulty |
2828
|----|------------------------------------------------------|---------------------------|------------|
2929
| 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ |
30-
| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ |
3130
| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ |
3231
| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ |
3332
| 6 | Median filter | `filters/passive` | ★★☆☆☆ |
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Saturation / Rate-Limiter / Slew Blocks
2+
3+
## Overview & Motivation
4+
5+
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.
6+
7+
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.
8+
9+
## Mathematical Theory
10+
11+
### Saturation
12+
13+
Given bounds $[\ell, h]$ with $\ell < h$, saturation is defined as:
14+
15+
$$y = \text{sat}(u) = \min\!\bigl(\max(u,\, \ell),\, h\bigr)$$
16+
17+
This is a memoryless, instantaneous projection onto the interval $[\ell, h]$.
18+
19+
### Rate Limiter (Slew Limiter)
20+
21+
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:
22+
23+
$$\delta[n] = \text{sat}_{\Delta_{\max}}(u[n] - y[n-1]) = \min\!\bigl(\max(u[n] - y[n-1],\,-\Delta_{\max}),\,+\Delta_{\max}\bigr)$$
24+
25+
$$y[n] = y[n-1] + \delta[n]$$
26+
27+
On the first sample (priming), $y[0] = u[0]$ and no limiting is applied, so the output tracks the first command exactly.
28+
29+
### Composed Block (Slew-Then-Clamp)
30+
31+
$$y_{\text{composed}}[n] = \text{sat}\!\bigl(y_{\text{slew}}[n]\bigr)$$
32+
33+
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.
34+
35+
## Complexity Analysis
36+
37+
| Case | Time | Space | Notes |
38+
|---------|--------|--------|-----------------------------------------------|
39+
| Best | $O(1)$ | $O(1)$ | Two compare-and-select operations |
40+
| Average | $O(1)$ | $O(1)$ | One multiply + two compares for rate limit |
41+
| Worst | $O(1)$ | $O(1)$ | Fixed instruction count; no branching on size |
42+
43+
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.
44+
45+
## Step-by-Step Walkthrough
46+
47+
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$.
48+
49+
| Tick $n$ | $u[n]$ | $\delta[n]$ | $y_{\text{slew}}[n]$ | $y_{\text{composed}}[n]$ |
50+
|----------|--------|-------------|----------------------|--------------------------|
51+
| 0 | 1.0 | 0.1 | 0.1 | 0.1 |
52+
| 1 | 1.0 | 0.1 | 0.2 | 0.2 |
53+
| 2 | 1.0 | 0.1 | 0.3 | 0.3 |
54+
| 3 | 1.0 | 0.1 | 0.4 | 0.4 |
55+
| 4 | 1.0 | 0.1 | 0.5 | 0.5 |
56+
| 5 | 1.0 | 0.1 | 0.6 | 0.5 (clamped) |
57+
58+
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.
59+
60+
## Pitfalls & Edge Cases
61+
62+
- **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.
63+
- **Collapsed saturation** ($\ell = h$): every output equals that constant regardless of input. The rate limiter still advances but the saturator immediately overwrites the result.
64+
- **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.
65+
- **Order of composition**: slew-then-clamp is the only order that guarantees simultaneous satisfaction of both constraints at every tick.
66+
- **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}$.
67+
68+
## Variants & Generalizations
69+
70+
- **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).
71+
- **Variable-rate limiter**: replace the fixed $\Delta_{\max}$ with a schedule or feedback signal for gain-scheduled slew limiting.
72+
- **Deadband + saturation**: insert a deadband nonlinearity before the saturator to model mechanical backlash or sensor noise floors.
73+
74+
## Applications
75+
76+
- **Motor drives**: limit acceleration commands to prevent over-current trips while hard-bounding the velocity or position command within safe travel.
77+
- **Thermal control**: ramp heater power slowly to avoid thermal shock while clamping to the maximum safe power level.
78+
- **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.
79+
- **Sensor fusion pre-processing**: slew-limit noisy sensor inputs before they enter an estimator to attenuate impulsive outliers without a dedicated filter.
80+
81+
## Connections to Other Algorithms
82+
83+
- **PidIncremental**: consumes the clamped output for anti-windup; the saturation block provides the feedback signal that stops integrator accumulation.
84+
- **BangBangHysteresis**: an alternative, discontinuous actuator constraint that switches between two fixed outputs; saturation is the continuous analog.
85+
- **ExponentialMovingAverage**: can approximate a low-pass slew effect but does not enforce a hard rate bound and has no priming concept.
86+
87+
## References & Further Reading
88+
89+
- K. J. Astrom, R. M. Murray, *Feedback Systems: An Introduction for Scientists and Engineers* (2008), sections on actuator saturation and integrator windup.
90+
- K. J. Astrom, T. Hagglund, *Advanced PID Control* (2006), Chapter 6: Anti-windup.

‎numerical/controllers/implementations/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@ target_sources(numerical.controllers.implementations PRIVATE
1616
Lqr.hpp
1717
Mpc.hpp
1818
PidIncremental.hpp
19+
SaturationRateLimiter.hpp
1920
)
2021

2122
numerical_add_coverage_sources(numerical.controllers.implementations
2223
Lqg.cpp
2324
Lqr.cpp
2425
Mpc.cpp
2526
PidIncremental.cpp
27+
SaturationRateLimiter.cpp
2628
)
2729

2830
add_subdirectory(test)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#include "numerical/controllers/implementations/SaturationRateLimiter.hpp"
2+
3+
namespace controllers
4+
{
5+
template class Saturation<float>;
6+
template class RateLimiter<float>;
7+
template class SlewLimitedSaturation<float>;
8+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
#pragma once
2+
3+
#if defined(__GNUC__) || defined(__clang__)
4+
#pragma GCC optimize("O3", "fast-math")
5+
#endif
6+
7+
#include "numerical/math/CompilerOptimizations.hpp"
8+
#include <algorithm>
9+
#include <type_traits>
10+
11+
namespace controllers
12+
{
13+
template<typename T>
14+
class Saturation
15+
{
16+
static_assert(std::is_floating_point_v<T>, "Saturation supports floating-point types");
17+
18+
public:
19+
Saturation(T lo, T hi)
20+
: lo{ lo }
21+
, hi{ hi }
22+
{
23+
}
24+
25+
OPTIMIZE_FOR_SPEED T Clamp(T u) const
26+
{
27+
return std::min(std::max(u, lo), hi);
28+
}
29+
30+
private:
31+
T lo;
32+
T hi;
33+
};
34+
35+
template<typename T>
36+
class RateLimiter
37+
{
38+
static_assert(std::is_floating_point_v<T>, "RateLimiter supports floating-point types");
39+
40+
public:
41+
RateLimiter(T maxRate, T sampleTime)
42+
: maxRate{ maxRate }
43+
, sampleTime{ sampleTime }
44+
{
45+
}
46+
47+
OPTIMIZE_FOR_SPEED T Limit(T u)
48+
{
49+
if (!primed)
50+
{
51+
previous = u;
52+
primed = true;
53+
return u;
54+
}
55+
56+
T step{ maxRate * sampleTime };
57+
T delta{ std::min(std::max(u - previous, -step), step) };
58+
previous = previous + delta;
59+
return previous;
60+
}
61+
62+
void Reset(T value = T{ 0 })
63+
{
64+
previous = value;
65+
primed = true;
66+
}
67+
68+
private:
69+
T maxRate;
70+
T sampleTime;
71+
T previous{};
72+
bool primed{ false };
73+
};
74+
75+
template<typename T>
76+
class SlewLimitedSaturation
77+
{
78+
static_assert(std::is_floating_point_v<T>, "SlewLimitedSaturation supports floating-point types");
79+
80+
public:
81+
SlewLimitedSaturation(T lo, T hi, T maxRate, T sampleTime)
82+
: clampBlock{ lo, hi }
83+
, slewBlock{ maxRate, sampleTime }
84+
{
85+
}
86+
87+
OPTIMIZE_FOR_SPEED T Apply(T u)
88+
{
89+
return clampBlock.Clamp(slewBlock.Limit(u));
90+
}
91+
92+
private:
93+
Saturation<T> clampBlock;
94+
RateLimiter<T> slewBlock;
95+
};
96+
97+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
98+
extern template class Saturation<float>;
99+
extern template class RateLimiter<float>;
100+
extern template class SlewLimitedSaturation<float>;
101+
#endif
102+
}

‎numerical/controllers/implementations/test/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@ target_sources(numerical.controllers_test PRIVATE
1313
TestLqr.cpp
1414
TestMpc.cpp
1515
TestPidIncremental.cpp
16+
TestSaturationRateLimiter.cpp
1617
TestStateFeedbackController.cpp
1718
)
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include "numerical/controllers/implementations/SaturationRateLimiter.hpp"
2+
#include "numerical/math/Tolerance.hpp"
3+
#include "gtest/gtest.h"
4+
5+
namespace
6+
{
7+
class TestSlewLimitedSaturation
8+
: public ::testing::Test
9+
{
10+
public:
11+
controllers::Saturation<float> sat{ -0.5f, 0.5f };
12+
controllers::RateLimiter<float> slew{ 0.1f, 1.0f };
13+
};
14+
}
15+
16+
TEST_F(TestSlewLimitedSaturation, clamp_passes_value_inside_bounds)
17+
{
18+
EXPECT_NEAR(sat.Clamp(0.25f), 0.25f, 1e-6f);
19+
}
20+
21+
TEST_F(TestSlewLimitedSaturation, clamp_saturates_above_and_below)
22+
{
23+
EXPECT_NEAR(sat.Clamp(0.9f), 0.5f, 1e-6f);
24+
EXPECT_NEAR(sat.Clamp(-0.9f), -0.5f, 1e-6f);
25+
}
26+
27+
TEST_F(TestSlewLimitedSaturation, rate_limiter_first_sample_seeds_state)
28+
{
29+
EXPECT_NEAR(slew.Limit(0.8f), 0.8f, 1e-6f);
30+
}
31+
32+
TEST_F(TestSlewLimitedSaturation, rate_limiter_caps_positive_slope)
33+
{
34+
slew.Limit(0.0f);
35+
EXPECT_NEAR(slew.Limit(1.0f), 0.1f, 1e-6f);
36+
EXPECT_NEAR(slew.Limit(1.0f), 0.2f, 1e-6f);
37+
EXPECT_NEAR(slew.Limit(1.0f), 0.3f, 1e-6f);
38+
}
39+
40+
TEST_F(TestSlewLimitedSaturation, rate_limiter_caps_negative_slope)
41+
{
42+
slew.Limit(0.0f);
43+
EXPECT_NEAR(slew.Limit(-1.0f), -0.1f, 1e-6f);
44+
EXPECT_NEAR(slew.Limit(-1.0f), -0.2f, 1e-6f);
45+
}
46+
47+
TEST_F(TestSlewLimitedSaturation, rate_limiter_follows_small_changes_exactly)
48+
{
49+
slew.Limit(0.0f);
50+
EXPECT_NEAR(slew.Limit(0.05f), 0.05f, 1e-6f);
51+
}
52+
53+
TEST_F(TestSlewLimitedSaturation, reset_reprimes_state)
54+
{
55+
slew.Limit(0.0f);
56+
slew.Limit(1.0f);
57+
slew.Reset(0.2f);
58+
EXPECT_NEAR(slew.Limit(0.25f), 0.25f, 1e-6f);
59+
}
60+
61+
TEST_F(TestSlewLimitedSaturation, composition_slew_then_clamp_honours_both)
62+
{
63+
controllers::SlewLimitedSaturation<float> composed{ -0.5f, 0.5f, 0.1f, 1.0f };
64+
composed.Apply(0.0f);
65+
for (int i = 0; i < 10; ++i)
66+
{
67+
float out{ composed.Apply(10.0f) };
68+
EXPECT_LE(out, 0.5f);
69+
EXPECT_GE(out, -0.5f);
70+
}
71+
}

‎roadmap/DEPLOYMENT.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ Read the spec's three files first (`implementation.md`, `tests.md`, `explanation
3232
`cmake --preset host && cmake --build --preset host && ctest --preset host`
3333
(scope to the target/test where possible).
3434

35-
**Report**: the file paths created/edited + the test result. Nothing else.
35+
7. **Remove roadmap spec** — delete the entire `roadmap/<domain>/<Name>/` directory once all tests are green.
36+
37+
**Report**: the file paths created/edited/deleted + the test result. Nothing else.
3638

3739
Recap: float-only (generic `T`, `float` instantiation), no heap, no comments, terse.

‎roadmap/controllers/SaturationRateLimiter/explanation.md‎

Lines changed: 0 additions & 32 deletions
This file was deleted.

0 commit comments

Comments
 (0)