From 10498e5a5db6b59d85a2ce1128a138e42ec4901d Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Sun, 26 Jul 2026 19:29:20 +0000 Subject: [PATCH 1/2] add gain scheduled controller --- README.md | 2 +- ROADMAP.md | 1 - doc/controllers/GainScheduledController.md | 100 ++++++++++++++++++ .../implementations/CMakeLists.txt | 2 + .../GainScheduledController.cpp | 8 ++ .../GainScheduledController.hpp | 96 +++++++++++++++++ .../implementations/test/CMakeLists.txt | 1 + .../test/TestGainScheduledController.cpp | 84 +++++++++++++++ .../GainScheduledController/explanation.md | 30 ------ .../GainScheduledController/implementation.md | 76 ------------- .../GainScheduledController/tests.md | 62 ----------- 11 files changed, 292 insertions(+), 170 deletions(-) create mode 100644 doc/controllers/GainScheduledController.md create mode 100644 numerical/controllers/implementations/GainScheduledController.cpp create mode 100644 numerical/controllers/implementations/GainScheduledController.hpp create mode 100644 numerical/controllers/implementations/test/TestGainScheduledController.cpp delete mode 100644 roadmap/controllers/GainScheduledController/explanation.md delete mode 100644 roadmap/controllers/GainScheduledController/implementation.md delete mode 100644 roadmap/controllers/GainScheduledController/tests.md diff --git a/README.md b/README.md index a7c1b96e..25f08460 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, Signal Detectors | | [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus | -| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF | +| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller | | [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 | diff --git a/ROADMAP.md b/ROADMAP.md index 6314a0e0..bad7f032 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -29,7 +29,6 @@ Difficulty legend: |----|------------------------------------------------------|---------------------------|------------| | 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` | ★★☆☆☆ | diff --git a/doc/controllers/GainScheduledController.md b/doc/controllers/GainScheduledController.md new file mode 100644 index 00000000..ee447f3a --- /dev/null +++ b/doc/controllers/GainScheduledController.md @@ -0,0 +1,100 @@ +# Gain-Scheduled Controller + +## Overview & Motivation + +Many physical plants behave as linear systems only near a specific operating point. A motor's electrical dynamics change with rotational speed, an aircraft's aerodynamic response shifts with altitude and Mach number, and a chemical reactor's behaviour depends on temperature. Designing a single linear controller that performs well across the entire operating envelope is often impossible or overly conservative. + +The gain-scheduled controller addresses this by pre-computing a family of linear controllers — each optimal near one operating point — and blending between them at runtime based on a measured **scheduling variable**. This extends the reach of proven linear design methods to mildly nonlinear plants at negligible runtime cost, making it the dominant approach to flight control, powertrain management, and process control on resource-constrained hardware. + +## Mathematical Theory + +### Setup + +Let $\sigma \in \mathbb{R}$ be the scheduling variable (e.g., speed, load, altitude) and let $\mathbf{g}(\sigma) \in \mathbb{R}^p$ denote the vector of $p$ controller gains as a function of $\sigma$. + +A finite set of $N$ **breakpoints** $\sigma_1 < \sigma_2 < \cdots < \sigma_N$ partitions the scheduling axis. At each breakpoint $\sigma_i$ a gain vector $\mathbf{g}_i \in \mathbb{R}^p$ is stored, pre-designed offline (e.g., by LQR at each linearised operating point). + +### Piecewise-Linear Interpolation + +For a scheduling value $\sigma$ in the interval $[\sigma_i, \sigma_{i+1}]$, the active gain vector is the linear interpolant: + +$$ +\mathbf{g}(\sigma) = \mathbf{g}_i + w \, (\mathbf{g}_{i+1} - \mathbf{g}_i), \qquad w = \frac{\sigma - \sigma_i}{\sigma_{i+1} - \sigma_i} \in [0,1]. +$$ + +Each gain component is interpolated independently. The rearranged form $a + w(b - a)$ is numerically preferable to $(1-w)a + wb$ because it avoids catastrophic cancellation near $w \approx 0$ and performs one fewer multiply. + +### Endpoint Saturation + +Outside the table range the gains are held constant at the boundary values: + +$$ +\mathbf{g}(\sigma) = \begin{cases} \mathbf{g}_1 & \sigma \leq \sigma_1 \\ \mathbf{g}_N & \sigma \geq \sigma_N \end{cases} +$$ + +Extrapolation is avoided because gain values outside the design envelope are undefined and potentially destabilising. + +### Stability Considerations + +Gain scheduling does not guarantee closed-loop stability in general. The standard sufficient conditions are: (1) the scheduling variable changes slowly relative to the closed-loop bandwidth (quasi-static assumption), and (2) each frozen-$\sigma$ system is stable. When the scheduling variable changes rapidly, a full parameter-varying analysis (LPV, $\mathcal{H}_\infty$) is required. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|------|------|-------|-------| +| Schedule (linear search) | $O(N + p)$ | $O(1)$ | $N$ interval scan, $p$ blends | +| Schedule (binary search) | $O(\log N + p)$ | $O(1)$ | Preferred for large tables | +| Construction | $O(N)$ | $O(N \cdot p)$ | Monotonicity assertion | + +All storage is stack-allocated. The table occupies $N \cdot p$ words; the active gain vector occupies $p$ words. No dynamic allocation occurs at any point. + +## Step-by-Step Walkthrough + +**Table:** $\{(0, 1), (0.5, 2), (1, 4)\}$ — three breakpoints, one gain each. + +**Query $\sigma = 0.75$:** + +1. $\sigma = 0.75 > \sigma_1 = 0$ and $\sigma = 0.75 < \sigma_3 = 1.0$, so no saturation. +2. Locate interval: $\sigma_2 = 0.5 \leq 0.75 < \sigma_3 = 1.0$, so $i = 2$. +3. Blend weight: $w = (0.75 - 0.5) / (1.0 - 0.5) = 0.5$. +4. Active gain: $g = 2.0 + 0.5 \times (4.0 - 2.0) = 3.0$. + +**Query $\sigma = -1.0$** (below table): saturate to $g = g_1 = 1.0$. + +## Pitfalls & Edge Cases + +- **Non-monotone breakpoints.** The interpolation formula divides by $\sigma_{i+1} - \sigma_i$; equal or reversed breakpoints cause division by zero or sign inversion. Strictly increasing order must be asserted at construction. +- **Rapid scheduling.** If $\dot{\sigma}$ is large relative to the closed-loop bandwidth, the quasi-static stability argument breaks down. The scheduling variable should be filtered or the breakpoint density increased near fast-varying regions. +- **Extrapolation is unsafe.** Outside the design envelope, gains are unknown quantities. Endpoint saturation is the only safe embedded policy; never extrapolate control gains. +- **Gain discontinuities.** If adjacent breakpoint gain sets differ sharply, the interpolated gains may produce a transient step in the control output when $\sigma$ crosses a breakpoint. Smooth scheduling designs (e.g., LPV synthesis) eliminate this. +- **Single-breakpoint interval.** Degenerate tables with $N = 1$ offer no interpolation; require $N \geq 2$ at compile time. + +## Variants & Generalizations + +| Variant | Key Difference | +|---------|---------------| +| **Bilinear / 2-D scheduling** | Gains indexed by two variables (e.g., speed and load); uses bilinear interpolation on a grid | +| **LPV (Linear Parameter-Varying)** | Gains are polynomial functions of $\sigma$; stability guaranteed by parameter-dependent Lyapunov functions | +| **Velocity-form scheduling** | Gains on incremental (velocity-form) controllers avoid output steps at scheduling transitions | +| **Bumpless transfer** | State initialisation at switchover prevents transients when $\sigma$ jumps discontinuously | + +## Applications + +- **Flight control** — gain sets designed at different Mach / altitude corners; $\sigma =$ dynamic pressure or Mach number. +- **Automotive powertrain** — PID gains scheduled on engine speed and load to compensate torque-speed nonlinearity. +- **Industrial process control** — reactor temperature or pH controllers scheduled on throughput or feed concentration. +- **Servo drives** — current/velocity loop gains scheduled on rotor speed to compensate back-EMF and inductance variation. + +## Connections to Other Algorithms + +| Algorithm | Relationship | +|-----------|-------------| +| [LQR](Lqr.md) | Common source of the per-breakpoint gain sets; each $\mathbf{g}_i$ is an LQR solution at the $i$-th linearised operating point | +| [Feedforward/2-DOF](Feedforward2Dof.md) | Complementary structure: the feedforward path can also be gain-scheduled to account for reference-dependent plant changes | +| [MPC](Mpc.md) | Alternative that solves an optimisation online; eliminates the need for offline scheduling but requires more computation | + +## References & Further Reading + +- W. J. Rugh, J. S. Shamma, "Research on gain scheduling," *Automatica*, 36(10), 1401–1425, 2000. +- J. S. Shamma, M. Athans, "Gain scheduling: Potential hazards and possible remedies," *IEEE Control Systems Magazine*, 12(3), 101–107, 1992. +- D. J. Leith, W. E. Leithead, "Survey of gain-scheduling analysis and design," *International Journal of Control*, 73(11), 1001–1025, 2000. diff --git a/numerical/controllers/implementations/CMakeLists.txt b/numerical/controllers/implementations/CMakeLists.txt index 6068d607..05982802 100644 --- a/numerical/controllers/implementations/CMakeLists.txt +++ b/numerical/controllers/implementations/CMakeLists.txt @@ -14,6 +14,7 @@ target_link_libraries(numerical.controllers.implementations ${NUMERICAL_VISIBILI target_sources(numerical.controllers.implementations PRIVATE BangBangHysteresis.hpp Feedforward2Dof.hpp + GainScheduledController.hpp Lqg.hpp Lqr.hpp Mpc.hpp @@ -24,6 +25,7 @@ target_sources(numerical.controllers.implementations PRIVATE numerical_add_coverage_sources(numerical.controllers.implementations BangBangHysteresis.cpp Feedforward2Dof.cpp + GainScheduledController.cpp Lqg.cpp Lqr.cpp Mpc.cpp diff --git a/numerical/controllers/implementations/GainScheduledController.cpp b/numerical/controllers/implementations/GainScheduledController.cpp new file mode 100644 index 00000000..e044e851 --- /dev/null +++ b/numerical/controllers/implementations/GainScheduledController.cpp @@ -0,0 +1,8 @@ +#include "numerical/controllers/implementations/GainScheduledController.hpp" + +namespace controllers +{ + template class GainScheduledController; + template class GainScheduledController; + template class GainScheduledController; +} diff --git a/numerical/controllers/implementations/GainScheduledController.hpp b/numerical/controllers/implementations/GainScheduledController.hpp new file mode 100644 index 00000000..6a2c33c2 --- /dev/null +++ b/numerical/controllers/implementations/GainScheduledController.hpp @@ -0,0 +1,96 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include +#include +#include +#include + +namespace controllers +{ + template + struct SchedulePoint + { + static_assert(std::is_floating_point_v, "SchedulePoint supports floating-point types"); + + T breakpoint; + std::array gains; + }; + + template + class GainScheduledController + { + public: + static_assert(std::is_floating_point_v, "GainScheduledController supports floating-point types"); + static_assert(N >= 2, "GainScheduledController requires at least 2 breakpoints"); + + explicit GainScheduledController(std::array, N> scheduleTable); + + OPTIMIZE_FOR_SPEED const std::array& Schedule(T schedulingVariable); + const std::array& ActiveGains() const; + + private: + std::array, N> table; + std::array active; + }; + + template + GainScheduledController::GainScheduledController(std::array, N> scheduleTable) + : table{ scheduleTable } + , active{} + { + for (std::size_t i{ 0 }; i < N - 1; ++i) + assert(table[i].breakpoint < table[i + 1].breakpoint); + } + + template + OPTIMIZE_FOR_SPEED const std::array& GainScheduledController::Schedule(T schedulingVariable) + { + if (schedulingVariable <= table[0].breakpoint) + { + active = table[0].gains; + return active; + } + + if (schedulingVariable >= table[N - 1].breakpoint) + { + active = table[N - 1].gains; + return active; + } + + std::size_t i{ 0 }; + for (std::size_t k{ 0 }; k < N - 1; ++k) + { + if (table[k + 1].breakpoint > schedulingVariable) + { + i = k; + break; + } + } + + T lo{ table[i].breakpoint }; + T hi{ table[i + 1].breakpoint }; + T w{ (schedulingVariable - lo) / (hi - lo) }; + + for (std::size_t k{ 0 }; k < GainSize; ++k) + active[k] = table[i].gains[k] + w * (table[i + 1].gains[k] - table[i].gains[k]); + + return active; + } + + template + const std::array& GainScheduledController::ActiveGains() const + { + return active; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class GainScheduledController; + extern template class GainScheduledController; + extern template class GainScheduledController; +#endif +} diff --git a/numerical/controllers/implementations/test/CMakeLists.txt b/numerical/controllers/implementations/test/CMakeLists.txt index 67646f43..324426b5 100644 --- a/numerical/controllers/implementations/test/CMakeLists.txt +++ b/numerical/controllers/implementations/test/CMakeLists.txt @@ -11,6 +11,7 @@ target_link_libraries(numerical.controllers_test PUBLIC target_sources(numerical.controllers_test PRIVATE TestBangBangHysteresis.cpp TestFeedforward2Dof.cpp + TestGainScheduledController.cpp TestLqg.cpp TestLqr.cpp TestMpc.cpp diff --git a/numerical/controllers/implementations/test/TestGainScheduledController.cpp b/numerical/controllers/implementations/test/TestGainScheduledController.cpp new file mode 100644 index 00000000..d3cc7655 --- /dev/null +++ b/numerical/controllers/implementations/test/TestGainScheduledController.cpp @@ -0,0 +1,84 @@ +#include "numerical/controllers/implementations/GainScheduledController.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gtest/gtest.h" +#include + +namespace +{ + class TestGainScheduledController + : public ::testing::Test + { + public: + using Point = controllers::SchedulePoint; + std::array table{ { { 0.0f, { 1.0f } }, + { 0.5f, { 2.0f } }, + { 1.0f, { 4.0f } } } }; + controllers::GainScheduledController scheduler{ table }; + }; +} + +TEST_F(TestGainScheduledController, returns_exact_gain_at_breakpoint) +{ + const auto& gains = scheduler.Schedule(0.5f); + + EXPECT_NEAR(gains[0], 2.0f, math::Tolerance()); +} + +TEST_F(TestGainScheduledController, interpolates_midway_between_points) +{ + const auto& gains = scheduler.Schedule(0.25f); + + EXPECT_NEAR(gains[0], 1.5f, math::Tolerance()); +} + +TEST_F(TestGainScheduledController, interpolates_in_second_interval) +{ + const auto& gains = scheduler.Schedule(0.75f); + + EXPECT_NEAR(gains[0], 3.0f, math::Tolerance()); +} + +TEST_F(TestGainScheduledController, saturates_below_first_breakpoint) +{ + const auto& gains = scheduler.Schedule(-1.0f); + + EXPECT_NEAR(gains[0], 1.0f, math::Tolerance()); +} + +TEST_F(TestGainScheduledController, saturates_above_last_breakpoint) +{ + const auto& gains = scheduler.Schedule(2.0f); + + EXPECT_NEAR(gains[0], 4.0f, math::Tolerance()); +} + +TEST_F(TestGainScheduledController, selects_correct_interval) +{ + const float sJustAboveHalf{ 0.5f + 1e-4f }; + const auto& gains = scheduler.Schedule(sJustAboveHalf); + + const float expected{ 2.0f + (sJustAboveHalf - 0.5f) / (1.0f - 0.5f) * (4.0f - 2.0f) }; + EXPECT_NEAR(gains[0], expected, math::Tolerance()); +} + +TEST_F(TestGainScheduledController, multi_gain_vectors_blend_componentwise) +{ + using Point2 = controllers::SchedulePoint; + std::array table2{ { { 0.0f, { 1.0f, 10.0f } }, + { 0.5f, { 2.0f, 20.0f } }, + { 1.0f, { 4.0f, 40.0f } } } }; + controllers::GainScheduledController scheduler2{ table2 }; + + const auto& gains = scheduler2.Schedule(0.25f); + + EXPECT_NEAR(gains[0], 1.5f, math::Tolerance()); + EXPECT_NEAR(gains[1], 15.0f, math::Tolerance()); +} + +TEST_F(TestGainScheduledController, active_gains_persist_between_calls) +{ + scheduler.Schedule(0.25f); + const auto& gains = scheduler.ActiveGains(); + + EXPECT_NEAR(gains[0], 1.5f, math::Tolerance()); +} diff --git a/roadmap/controllers/GainScheduledController/explanation.md b/roadmap/controllers/GainScheduledController/explanation.md deleted file mode 100644 index 32365347..00000000 --- a/roadmap/controllers/GainScheduledController/explanation.md +++ /dev/null @@ -1,30 +0,0 @@ -# Gain-Scheduled Controller — Overview - -## What it is -A controller whose gains change with an operating condition. A lookup table stores a set of -pre-designed gains at several **breakpoints** of a scheduling variable (speed, load, altitude, -temperature); at run time the block interpolates between the nearest two sets. - -## Why it matters (embedded) -Many "linear" plants are only linear near one operating point — a motor's dynamics change with -speed, an actuator's with load. Rather than redesign online (expensive, risky), engineers -pre-compute good gains at a grid of points offline and let the MCU interpolate. It extends proven -linear controllers to mildly nonlinear plants with almost no runtime cost. - -## How it works (intuition) -Think of it as a piecewise-linear surface over the scheduling axis. Given the current scheduling -value, the block finds the bracketing interval, computes a blend weight, and linearly mixes the -two gain sets. Outside the table it holds the end gains (safe clamp-and-hold) rather than -extrapolating, which could produce unstable gains. - -## Key parameters -- **breakpoints** — the scheduling-variable values where gains are defined (strictly increasing). -- **gain sets** — the controller gains stored at each breakpoint. -- **scheduling variable** — the measured operating condition selecting the gains. - -## Reference -W. J. Rugh, J. S. Shamma, "Research on gain scheduling," *Automatica*, 36(10), 2000. - -## See also -`Feedforward2Dof` (another way to handle varying operating conditions); `Lqr` (a common source of -the per-breakpoint gain sets). diff --git a/roadmap/controllers/GainScheduledController/implementation.md b/roadmap/controllers/GainScheduledController/implementation.md deleted file mode 100644 index 25fd15e9..00000000 --- a/roadmap/controllers/GainScheduledController/implementation.md +++ /dev/null @@ -1,76 +0,0 @@ -# Gain-Scheduled Controller — Implementation Pseudocode - -> Roadmap ref: #10 (Tier 2) · 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 -struct SchedulePoint: - T breakpoint # scheduling-variable value - std::array gains # controller gains at this point - -template # static_assert(std::is_floating_point_v); instantiated for float -class GainScheduledController: - std::array, N> table # sorted by breakpoint, ascending - std::array active # last interpolated gain set -``` - -## Interface - -``` -GainScheduledController(std::array, N> table) -const std::array& Schedule(T schedulingVariable) # hot path -const std::array& ActiveGains() const -``` - -## Algorithm (pseudocode) - -``` -function Schedule(s): # OPTIMIZE_FOR_SPEED - # 1. Saturate to table range (hold end gains outside the grid) - if s <= table[0].breakpoint: return (active = table[0].gains) - if s >= table[N-1].breakpoint: return (active = table[N-1].gains) - - # 2. Locate bracketing interval [i, i+1] - i = FindInterval(table, s) # linear or binary search on breakpoints - - # 3. Linear interpolation weight within the interval - lo = table[i].breakpoint; hi = table[i+1].breakpoint - w = (s - lo) / (hi - lo) # w in [0,1] - - # 4. Blend each gain component - for k in 0..GainSize-1: - active[k] = table[i].gains[k] + w * (table[i+1].gains[k] - table[i].gains[k]) - return active -``` - -## Complexity & memory - -- Time: `O(log N)` (binary search) or `O(N)` (linear scan) plus `O(GainSize)` blend per update. -- Memory: `O(N·GainSize)` for the table, `O(GainSize)` for the active gains — all static. - -## Numerical / embedded notes - -- Breakpoints must be **strictly increasing**; assert this once at construction. -- Endpoint saturation (clamp-and-hold) avoids extrapolation, which is unsafe for control gains. -- The blend uses the rearranged form `a + w·(b−a)` (one multiply) to stay accurate near `w≈0`, - mirroring the EMA update. -- Gains are only interpolated here, never used to drive dynamics — the caller applies them to its - own control law (dependency inversion keeps this block plant-agnostic). -- 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/GainScheduledController.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Schedule`, and - `extern template class GainScheduledController;` - under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/controllers/implementations/GainScheduledController.cpp` → - `template class GainScheduledController;` -- Test: `numerical/controllers/implementations/test/TestGainScheduledController.cpp` -- Doc: `doc/controllers/GainScheduledController.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestGainScheduledController.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. diff --git a/roadmap/controllers/GainScheduledController/tests.md b/roadmap/controllers/GainScheduledController/tests.md deleted file mode 100644 index daac04c8..00000000 --- a/roadmap/controllers/GainScheduledController/tests.md +++ /dev/null @@ -1,62 +0,0 @@ -# Gain-Scheduled Controller — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestGainScheduledController : public ::testing::Test: - # 3 breakpoints at 0.0, 0.5, 1.0; single gain per point - using Point = SchedulePoint - std::array table{{ {0.0f,{1.0f}}, - {0.5f,{2.0f}}, - {1.0f,{4.0f}} }} - GainScheduledController scheduler{ table } -# each case below is a TEST_F(TestGainScheduledController, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -returns_exact_gain_at_breakpoint: - Arrange: s = 0.5 - Assert: active gain == 2.0 - -interpolates_midway_between_points: - Arrange: s = 0.25 (halfway in first interval) - Assert: active gain ≈ 1.5 - -interpolates_in_second_interval: - Arrange: s = 0.75 - Assert: active gain ≈ 3.0 - -saturates_below_first_breakpoint: - Arrange: s = -1.0 - Assert: active gain == 1.0 (first point held) - -saturates_above_last_breakpoint: - Arrange: s = 2.0 - Assert: active gain == 4.0 (last point held) - -selects_correct_interval: - Arrange: s just above 0.5 - Assert: blend uses points [0.5, 1.0], not [0.0, 0.5] - -multi_gain_vectors_blend_componentwise: - Arrange: GainSize = 2, each component interpolated independently - Assert: both components match their own linear blend - -active_gains_persist_between_calls: - Arrange: Schedule(0.25) then read ActiveGains() - Assert: returns last interpolated set (≈1.5) -``` - -## Reference vectors - -- Table {(0,1),(0.5,2),(1,4)}: `s=0.25 → 1.5`, `s=0.75 → 3.0`, `s=0.5 → 2.0` exactly. -- Outside `[0,1]` the gain is held at the nearest endpoint (no extrapolation). - -## Edge cases - -- Scheduling variable exactly on a breakpoint returns the stored gain (no interpolation error). -- Two-point table degenerates to a single linear segment. From ae98b0c9418ad9076bd21e800fdc4611bed13b39 Mon Sep 17 00:00:00 2001 From: gfs Date: Sun, 26 Jul 2026 21:34:20 +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/GainScheduledController.md | 30 +++++++++++----------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/doc/controllers/GainScheduledController.md b/doc/controllers/GainScheduledController.md index ee447f3a..ae87c821 100644 --- a/doc/controllers/GainScheduledController.md +++ b/doc/controllers/GainScheduledController.md @@ -40,11 +40,11 @@ Gain scheduling does not guarantee closed-loop stability in general. The standar ## Complexity Analysis -| Case | Time | Space | Notes | -|------|------|-------|-------| -| Schedule (linear search) | $O(N + p)$ | $O(1)$ | $N$ interval scan, $p$ blends | -| Schedule (binary search) | $O(\log N + p)$ | $O(1)$ | Preferred for large tables | -| Construction | $O(N)$ | $O(N \cdot p)$ | Monotonicity assertion | +| Case | Time | Space | Notes | +|--------------------------|-----------------|----------------|-------------------------------| +| Schedule (linear search) | $O(N + p)$ | $O(1)$ | $N$ interval scan, $p$ blends | +| Schedule (binary search) | $O(\log N + p)$ | $O(1)$ | Preferred for large tables | +| Construction | $O(N)$ | $O(N \cdot p)$ | Monotonicity assertion | All storage is stack-allocated. The table occupies $N \cdot p$ words; the active gain vector occupies $p$ words. No dynamic allocation occurs at any point. @@ -71,12 +71,12 @@ All storage is stack-allocated. The table occupies $N \cdot p$ words; the active ## Variants & Generalizations -| Variant | Key Difference | -|---------|---------------| -| **Bilinear / 2-D scheduling** | Gains indexed by two variables (e.g., speed and load); uses bilinear interpolation on a grid | +| Variant | Key Difference | +|------------------------------------|------------------------------------------------------------------------------------------------------------| +| **Bilinear / 2-D scheduling** | Gains indexed by two variables (e.g., speed and load); uses bilinear interpolation on a grid | | **LPV (Linear Parameter-Varying)** | Gains are polynomial functions of $\sigma$; stability guaranteed by parameter-dependent Lyapunov functions | -| **Velocity-form scheduling** | Gains on incremental (velocity-form) controllers avoid output steps at scheduling transitions | -| **Bumpless transfer** | State initialisation at switchover prevents transients when $\sigma$ jumps discontinuously | +| **Velocity-form scheduling** | Gains on incremental (velocity-form) controllers avoid output steps at scheduling transitions | +| **Bumpless transfer** | State initialisation at switchover prevents transients when $\sigma$ jumps discontinuously | ## Applications @@ -87,11 +87,11 @@ All storage is stack-allocated. The table occupies $N \cdot p$ words; the active ## Connections to Other Algorithms -| Algorithm | Relationship | -|-----------|-------------| -| [LQR](Lqr.md) | Common source of the per-breakpoint gain sets; each $\mathbf{g}_i$ is an LQR solution at the $i$-th linearised operating point | -| [Feedforward/2-DOF](Feedforward2Dof.md) | Complementary structure: the feedforward path can also be gain-scheduled to account for reference-dependent plant changes | -| [MPC](Mpc.md) | Alternative that solves an optimisation online; eliminates the need for offline scheduling but requires more computation | +| Algorithm | Relationship | +|-----------------------------------------|--------------------------------------------------------------------------------------------------------------------------------| +| [LQR](Lqr.md) | Common source of the per-breakpoint gain sets; each $\mathbf{g}_i$ is an LQR solution at the $i$-th linearised operating point | +| [Feedforward/2-DOF](Feedforward2Dof.md) | Complementary structure: the feedforward path can also be gain-scheduled to account for reference-dependent plant changes | +| [MPC](Mpc.md) | Alternative that solves an optimisation online; eliminates the need for offline scheduling but requires more computation | ## References & Further Reading