Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -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, Complementary, FIR, IIR, Exponential Moving Average, Moving Average, Median Filter |
Expand Down
1 change: 0 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ Difficulty legend:

| # | Component | Target module | Difficulty |
|----|------------------------------------------------------|---------------------------|------------|
| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ |
| 10 | Gain-scheduled controller | `controllers` | ★★☆☆☆ |
| 11 | Convolution & correlation utilities | `analysis` | ★★☆☆☆ |
| 12 | Polynomial least-squares curve fitting | `estimators/offline` | ★★☆☆☆ |
Expand Down
100 changes: 100 additions & 0 deletions doc/controllers/GainScheduledController.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions numerical/controllers/implementations/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#include "numerical/controllers/implementations/GainScheduledController.hpp"

namespace controllers
{
template class GainScheduledController<float, 2, 1>;
template class GainScheduledController<float, 3, 1>;
template class GainScheduledController<float, 3, 2>;
}
96 changes: 96 additions & 0 deletions numerical/controllers/implementations/GainScheduledController.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#pragma once

#if defined(__GNUC__) || defined(__clang__)
#pragma GCC optimize("O3", "fast-math")
#endif

#include "numerical/math/CompilerOptimizations.hpp"
#include <array>
#include <cassert>
#include <cstddef>
#include <type_traits>

namespace controllers
{
template<typename T, std::size_t GainSize>
struct SchedulePoint
{
static_assert(std::is_floating_point_v<T>, "SchedulePoint supports floating-point types");

T breakpoint;
std::array<T, GainSize> gains;
};

template<typename T, std::size_t N, std::size_t GainSize>
class GainScheduledController
{
public:
static_assert(std::is_floating_point_v<T>, "GainScheduledController supports floating-point types");
static_assert(N >= 2, "GainScheduledController requires at least 2 breakpoints");

explicit GainScheduledController(std::array<SchedulePoint<T, GainSize>, N> scheduleTable);

OPTIMIZE_FOR_SPEED const std::array<T, GainSize>& Schedule(T schedulingVariable);
const std::array<T, GainSize>& ActiveGains() const;

private:
std::array<SchedulePoint<T, GainSize>, N> table;
std::array<T, GainSize> active;
};

template<typename T, std::size_t N, std::size_t GainSize>
GainScheduledController<T, N, GainSize>::GainScheduledController(std::array<SchedulePoint<T, GainSize>, N> scheduleTable)
: table{ scheduleTable }
, active{}

Check warning on line 44 in numerical/controllers/implementations/GainScheduledController.hpp

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Do not use the constructor's initializer list for data member "active". Use the in-class initializer instead.

See more on https://sonarcloud.io/project/issues?id=embedded-pro_embedded-dsp-control&issues=AZ-f6hPMyIH_nJ2fO9i0&open=AZ-f6hPMyIH_nJ2fO9i0&pullRequest=173
{
for (std::size_t i{ 0 }; i < N - 1; ++i)
assert(table[i].breakpoint < table[i + 1].breakpoint);
}

template<typename T, std::size_t N, std::size_t GainSize>
OPTIMIZE_FOR_SPEED const std::array<T, GainSize>& GainScheduledController<T, N, GainSize>::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<typename T, std::size_t N, std::size_t GainSize>
const std::array<T, GainSize>& GainScheduledController<T, N, GainSize>::ActiveGains() const
{
return active;
}

#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
extern template class GainScheduledController<float, 2, 1>;
extern template class GainScheduledController<float, 3, 1>;
extern template class GainScheduledController<float, 3, 2>;
#endif
}
1 change: 1 addition & 0 deletions numerical/controllers/implementations/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#include "numerical/controllers/implementations/GainScheduledController.hpp"
#include "numerical/math/Tolerance.hpp"
#include "gtest/gtest.h"
#include <array>

namespace
{
class TestGainScheduledController
: public ::testing::Test
{
public:
using Point = controllers::SchedulePoint<float, 1>;
std::array<Point, 3> table{ { { 0.0f, { 1.0f } },
{ 0.5f, { 2.0f } },
{ 1.0f, { 4.0f } } } };
controllers::GainScheduledController<float, 3, 1> 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<float>());
}

TEST_F(TestGainScheduledController, interpolates_midway_between_points)
{
const auto& gains = scheduler.Schedule(0.25f);

EXPECT_NEAR(gains[0], 1.5f, math::Tolerance<float>());
}

TEST_F(TestGainScheduledController, interpolates_in_second_interval)
{
const auto& gains = scheduler.Schedule(0.75f);

EXPECT_NEAR(gains[0], 3.0f, math::Tolerance<float>());
}

TEST_F(TestGainScheduledController, saturates_below_first_breakpoint)
{
const auto& gains = scheduler.Schedule(-1.0f);

EXPECT_NEAR(gains[0], 1.0f, math::Tolerance<float>());
}

TEST_F(TestGainScheduledController, saturates_above_last_breakpoint)
{
const auto& gains = scheduler.Schedule(2.0f);

EXPECT_NEAR(gains[0], 4.0f, math::Tolerance<float>());
}

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<float>());
}

TEST_F(TestGainScheduledController, multi_gain_vectors_blend_componentwise)
{
using Point2 = controllers::SchedulePoint<float, 2>;
std::array<Point2, 3> table2{ { { 0.0f, { 1.0f, 10.0f } },
{ 0.5f, { 2.0f, 20.0f } },
{ 1.0f, { 4.0f, 40.0f } } } };
controllers::GainScheduledController<float, 3, 2> scheduler2{ table2 };

const auto& gains = scheduler2.Schedule(0.25f);

EXPECT_NEAR(gains[0], 1.5f, math::Tolerance<float>());
EXPECT_NEAR(gains[1], 15.0f, math::Tolerance<float>());
}

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<float>());
}
30 changes: 0 additions & 30 deletions roadmap/controllers/GainScheduledController/explanation.md

This file was deleted.

Loading
Loading