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
20 changes: 20 additions & 0 deletions .vscode/launch.json
Comment thread
gabrielfrasantos marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,26 @@
}
]
},
{
"name": "Lqg Simulator",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/host/simulator/controllers/Lqg/Debug/numerical.simulator.controllers.lqg",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
{
"name": "Linux Debug",
"type": "cppdbg",
Expand Down
122 changes: 122 additions & 0 deletions doc/controllers/LinearTimeInvariant.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Linear Time-Invariant System Model

## Overview & Motivation

A **Linear Time-Invariant (LTI)** system model is the fundamental mathematical object shared across state-space control, estimation, and signal processing. It captures the dynamics of a physical plant — a motor, a pendulum, a vehicle — in a compact matrix representation that enables the systematic application of optimal control and filtering theory.

Representing an LTI model as a first-class value type makes it possible to pass a single plant description into algorithms such as the Kalman Filter, LQR, LQG, and MPC, eliminating the error-prone practice of supplying the same system matrices (A, B, C, D) separately to each component.

## Mathematical Theory

### Discrete-Time State-Space Representation

A discrete-time LTI system with state $x_k \in \mathbb{R}^n$, input $u_k \in \mathbb{R}^m$, and output $y_k \in \mathbb{R}^p$ is described by two equations:

**State equation:**
$$x_{k+1} = A x_k + B u_k$$

**Output equation:**
$$y_k = C x_k + D u_k$$

where:
- $A \in \mathbb{R}^{n \times n}$ is the **state transition matrix**
- $B \in \mathbb{R}^{n \times m}$ is the **input matrix** (sometimes called the control matrix)
- $C \in \mathbb{R}^{p \times n}$ is the **output matrix** (sometimes called the measurement matrix)
- $D \in \mathbb{R}^{p \times m}$ is the **feedthrough matrix** (often zero for strictly proper systems)

### Special Cases

**Full-state output ($C = I$, $D = 0$):** When all states are directly observable (e.g., a simulation or a state-feedback controller with perfect sensing), the output equation collapses to $y_k = x_k$. This is the typical case for LQR.

**Autonomous system ($B = 0$, $u_k = 0$):** A system driven only by initial conditions and process noise. Used in Kalman smoothing and spectral analysis.

### Discretisation

Continuous-time plants described by $\dot{x} = A_c x + B_c u$ must be discretised before use in digital controllers:

$$A = e^{A_c T_s}, \quad B = A_c^{-1}(A - I) B_c$$

where $T_s$ is the sampling period. For small $T_s$ and stable $A_c$, the forward-Euler approximation $A \approx I + A_c T_s$, $B \approx B_c T_s$ may be used.

### Stability and Controllability

An LTI model is:
- **Stable** if all eigenvalues of $A$ lie strictly inside the unit disc ($|\lambda_i| < 1$ for discrete-time systems).
- **Controllable** if the controllability matrix $\mathcal{C} = [B \; AB \; A^2B \; \cdots \; A^{n-1}B]$ has full row rank.
- **Observable** if the observability matrix $\mathcal{O} = [C^T \; (CA)^T \; \cdots \; (CA^{n-1})^T]^T$ has full column rank.

Controllability and observability are prerequisites for LQR and Kalman Filter stability, respectively.

## Complexity Analysis

| Operation | Time | Space | Notes |
|--------------|---------------|-------------------------|-------------------------------------|
| Step (state) | $O(n^2 + nm)$ | $O(n)$ | One matrix-vector multiply per term |
| Output | $O(pn + pm)$ | $O(p)$ | One matrix-vector multiply per term |
| Construction | $O(1)$ | $O(n^2 + nm + pn + pm)$ | Value-type struct, no allocation |

## Numerical Considerations

- **Condition number of A:** Poorly conditioned $A$ amplifies numerical errors during iterative integration. Monitor the spectral radius of $A$ to ensure stability is not lost due to finite-precision arithmetic.
- **Feedthrough matrix D:** For most physical systems $D = 0$ (strictly proper). A nonzero $D$ requires care in closed-loop analysis since direct input-to-output coupling may cause algebraic loops.
- **Fixed-point use:** LTI matrices are suitable for Q15/Q31 when all matrix entries and intermediate products remain within $[-1, 1]$. For real physical systems with gains exceeding unity, scale the representation (e.g., normalise state and input ranges) before using fixed-point arithmetic.
- **Identity construction:** When building the $C = I$ case (full-state output), use $0.9999$ rather than $1.0$ for Q15 compatibility, since $1.0$ is not representable in the Q15 format.

## Pitfalls & Edge Cases

- **Time-varying systems:** The LTI model is invalid for systems whose matrices $A$, $B$, $C$, $D$ depend on time or operating point. Use scheduling or re-linearisation for such plants.
- **Nonlinear plants:** State-space linearisation is valid only in a neighbourhood of the operating point. Large deviations from the linearisation point invalidate the model.
- **Sampling rate:** Discrete-time LTI models are sampling-rate-specific. Changing $T_s$ requires re-discretisation and possibly re-tuning of dependent controllers and filters.

## Step-by-Step Walkthrough

Consider a double integrator (position and velocity state, force input, position output) with sample period $T_s = 0.1\,\text{s}$:

**Continuous-time plant:** $\dot{x} = \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix} x + \begin{bmatrix} 0 \\ 1 \end{bmatrix} u$, $y = \begin{bmatrix} 1 & 0 \end{bmatrix} x$

**Step 1 — Discretise using forward-Euler** ($A \approx I + A_c T_s$, $B \approx B_c T_s$):

$$A = \begin{bmatrix} 1 & 0.1 \\ 0 & 1 \end{bmatrix}, \quad B = \begin{bmatrix} 0 \\ 0.1 \end{bmatrix}, \quad C = \begin{bmatrix} 1 & 0 \end{bmatrix}, \quad D = \begin{bmatrix} 0 \end{bmatrix}$$

**Step 2 — Simulate one step** from $x_0 = [1, 0]^T$ with $u_0 = -2$:

$$x_1 = A x_0 + B u_0 = \begin{bmatrix} 1 & 0.1 \\ 0 & 1 \end{bmatrix} \begin{bmatrix} 1 \\ 0 \end{bmatrix} + \begin{bmatrix} 0 \\ 0.1 \end{bmatrix}(-2) = \begin{bmatrix} 1 \\ -0.2 \end{bmatrix}$$

**Step 3 — Compute output** at $k=0$:

$$y_0 = C x_0 = \begin{bmatrix} 1 & 0 \end{bmatrix} \begin{bmatrix} 1 \\ 0 \end{bmatrix} = 1$$

The position measurement is $1.0$ (exact, since $D = 0$ and noise is excluded here).

## Variants & Generalizations

- **Full-state output ($C = I$, $D = 0$):** All states are directly available as outputs. Used in LQR with perfect sensing. Constructed via the `WithFullStateOutput` factory, which sets $C$ to the identity.
- **Autonomous system ($B = 0$):** No input; the system evolves freely from initial conditions. Used in Kalman smoothing and spectral analysis (e.g., auto-regressive models).
- **Strictly proper systems ($D = 0$):** Most physical plants have zero feedthrough; the $D$ matrix is omitted from the signal path. The LTI representation preserves $D$ for generality.
- **Continuous-time counterpart:** Described by $\dot{x} = A_c x + B_c u$, $y = C_c x + D_c u$. Requires discretisation before use in digital controllers.
- **Multi-rate LTI:** Different sensors and actuators may operate at different sample rates; a lifted LTI representation can handle periodic multi-rate systems.

## Applications

- **Digital control design:** The LTI model is the canonical starting point for controller synthesis (LQR, MPC, pole placement). A linearised plant description is the single shared artefact that all design tools consume.
- **Kalman Filter initialisation:** The $(A, B, C)$ matrices are passed directly into the Kalman Filter to define the predict and update equations, ensuring consistency between plant and estimator.
- **Simulation and validation:** Monte Carlo simulations propagate an LTI model forward to verify closed-loop stability margins, noise sensitivity, and disturbance rejection before deployment on hardware.
- **System identification:** Identified discrete-time state-space models from input-output data (e.g., via subspace identification or prediction-error methods) are naturally expressed as LTI structs.
- **Transfer function analysis:** The $z$-domain transfer function $H(z) = C(zI - A)^{-1}B + D$ can be extracted from the LTI matrices for frequency-response computation and Bode plotting.

## Connections to Other Algorithms

- **LQR:** Uses the $(A, B)$ pair to solve the DARE and compute the optimal state-feedback gain.
- **Kalman Filter:** Uses $(A, B, C)$ to predict the next state and relate states to measurements.
- **LQG:** Composes both — $(A, B)$ for the regulator and $(A, B, C)$ for the estimator.
- **MPC:** Uses $(A, B)$ to build the prediction model over a finite horizon.
- **Kalman Smoother:** Uses $(A, C)$ for the forward-backward pass in batch smoothing.
- **DARE Solver:** Receives $(A, B)$ as inputs to compute the Riccati solution.

## References & Further Reading

- C.-T. Chen, *Linear System Theory and Design*, 4th ed., Oxford University Press, 2013. Chapters 4–5.
- R. E. Kalman, "Mathematical Description of Linear Dynamical Systems," *SIAM Journal on Control*, 1(2):152–192, 1963.
- G. F. Franklin, J. D. Powell, and A. Emami-Naeini, *Feedback Control of Dynamic Systems*, 8th ed., Pearson, 2019. Chapter 7.
- T. Kailath, *Linear Systems*, Prentice Hall, 1980. Comprehensive reference on state-space representations and transformations.
- K. J. Åström and B. Wittenmark, *Computer-Controlled Systems: Theory and Design*, 3rd ed., Dover, 2011. Chapter 3 (discretisation methods).
154 changes: 154 additions & 0 deletions doc/controllers/Lqg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# Linear Quadratic Gaussian (LQG) Controller

## Overview & Motivation

The Linear Quadratic Gaussian (LQG) controller combines two classical optimal control results: the Linear Quadratic Regulator (LQR) and the Kalman Filter (KF). It is the optimal output-feedback controller for linear time-invariant (LTI) systems subject to Gaussian process and measurement noise.

While LQR assumes full state availability — a strict requirement rarely satisfied in practice — LQG relaxes this by estimating the state from noisy output measurements. The Kalman Filter provides the minimum-variance estimate, and LQR computes the optimal control law given that estimate. By the **Separation Principle**, these two subproblems can be solved independently and their solutions combined without loss of optimality.

LQG is widely used in aerospace guidance, robotics, and process control when sensor noise is substantial and the plant model is reasonably accurate.

## Mathematical Theory

### System Model

Consider the discrete-time LTI system:

$$x_{k+1} = A x_k + B u_k + w_k$$

$$y_k = C x_k + v_k$$

where:
- $x_k \in \mathbb{R}^n$ is the state vector
- $u_k \in \mathbb{R}^m$ is the control input
- $y_k \in \mathbb{R}^p$ is the measurement vector
- $w_k \sim \mathcal{N}(0, Q_w)$ is process noise
- $v_k \sim \mathcal{N}(0, R_v)$ is measurement noise

### LQR Subproblem

The regulator minimises the infinite-horizon quadratic cost:

$$J = \sum_{k=0}^{\infty} \left( x_k^T Q x_k + u_k^T R u_k \right)$$

The optimal state-feedback gain is:

$$K = (R + B^T P B)^{-1} B^T P A$$

where $P$ is the positive semi-definite solution to the Discrete Algebraic Riccati Equation (DARE):

$$P = Q + A^T P A - A^T P B (R + B^T P B)^{-1} B^T P A$$

The optimal control law is $u_k = -K \hat{x}_{k|k}$.

### Kalman Filter Subproblem

The optimal state estimator propagates:

**Predict:**
$$\hat{x}_{k+1|k} = A \hat{x}_{k|k} + B u_k$$

$$P_{k+1|k} = A P_{k|k} A^T + Q_w$$

**Update:**
$$K_f = P_{k|k-1} C^T (C P_{k|k-1} C^T + R_v)^{-1}$$

$$\hat{x}_{k|k} = \hat{x}_{k|k-1} + K_f (y_k - C \hat{x}_{k|k-1})$$

$$P_{k|k} = (I - K_f C) P_{k|k-1} (I - K_f C)^T + K_f R_v K_f^T$$

The steady-state Kalman gain converges to a fixed matrix as $k \to \infty$.

### Separation Principle

The fundamental result that makes LQG tractable is:

**Theorem (Separation Principle):** The optimal output-feedback control law for the LQG problem is the composition of (1) the optimal state estimator (Kalman Filter) and (2) the optimal state-feedback controller (LQR), designed independently.

This means the LQR gain $K$ and the Kalman gain $K_f$ do not interact — changing the noise covariances $Q_w$, $R_v$ affects only the estimator, and changing the cost weights $Q$, $R$ affects only the regulator.

### Combined Control Loop

At each time step $k$:

1. **Measurement update:** $\hat{x}_{k|k} \leftarrow \text{KF.Update}(y_k)$
2. **Compute control:** $u_k = -K \hat{x}_{k|k}$
3. **Time update:** $\hat{x}_{k+1|k} \leftarrow \text{KF.Predict}(u_k)$

## Complexity Analysis

| Step | Time | Space | Notes |
|----------------|---------------|----------|--------------------------|
| Construction | $O(n^3)$ | $O(n^2)$ | DARE solve for LQR gain |
| ComputeControl | $O(n^2 + nm)$ | $O(1)$ | KF update + LQR multiply |

where $n$ = state size, $m$ = input size, $p$ = measurement size.

## Numerical Considerations

- **DARE convergence:** The LQR DARE requires $(A, B)$ to be stabilisable and $(A, Q^{1/2})$ to be detectable. Ill-conditioned cost matrices or near-unstable plants can slow convergence or yield poor numerical accuracy.
- **Kalman Filter initialisation:** The choice of initial covariance $P_0$ affects transient performance. A larger $P_0$ leads to faster initial adaptation at the cost of more initial aggressiveness.
- **Noise covariance tuning:** $Q_w / R_v$ ratio controls the balance between trusting the model (large $R_v$) versus measurements (small $R_v$). Poor tuning degrades closed-loop performance.
- **Stability:** The separation principle guarantees stability only when both the LQR gain and the Kalman Filter produce stable designs individually. Verify that the observer eigenvalues are well within the unit disc.
- **Fixed-point arithmetic:** LQG is not recommended for Q15/Q31 types unless the operating range can be normalised to $[-1, 1]$ for all state, input, and measurement signals. Use `float` unless the target platform lacks an FPU.

## Pitfalls & Edge Cases

- **Model uncertainty:** LQG is optimal only for the assumed model. Unmodelled dynamics (e.g., flexible modes, time delays) can destabilise the closed loop. LQG/LTR (loop transfer recovery) or robust variants should be considered when model fidelity is limited.
- **Non-minimum-phase systems:** LQG does not guarantee good robustness margins for non-minimum-phase plants. The loop gain can drop, resulting in poor disturbance rejection.
- **Nonlinear systems:** LQG is only optimal for linear systems with Gaussian noise. For nonlinear systems, Extended Kalman Filter (EKF) or Unscented Kalman Filter (UKF) with an LQR gain around an operating point provides a linearisation-based approximation.

## Step-by-Step Walkthrough

Consider a double integrator plant — a mass subject to force input, observed through a noisy position sensor. The discrete-time matrices with sample period $T_s = 0.1\,\text{s}$ are:

$$A = \begin{bmatrix} 1 & 0.1 \\ 0 & 1 \end{bmatrix}, \quad B = \begin{bmatrix} 0 \\ 0.1 \end{bmatrix}, \quad C = \begin{bmatrix} 1 & 0 \end{bmatrix}$$

**Construction (offline):**

1. Choose LQR weights $Q = 10 I_2$, $R = 0.1$. Solve DARE for $P$, compute gain $K = (R + B^T P B)^{-1} B^T P A$.
2. Choose noise covariances $Q_w = 0.1 I_2$, $R_v = 1.0$. Solve dual DARE for steady-state Kalman gain $K_f$.
3. Verify closed-loop stability: eigenvalues of $(A - BK)$ and $(A - K_f C)$ must lie strictly inside the unit disc.

**Online loop (per sample):**

| Step | Operation | Notes |
|------|--------------------------------------------------------------------|------------------------|
| 1 | Receive sensor measurement $y_k$ | Noisy position reading |
| 2 | $\hat{x}_{k\|k} = \hat{x}_{k\|k-1} + K_f(y_k - C\hat{x}_{k\|k-1})$ | Kalman update |
| 3 | $u_k = -K \hat{x}_{k\|k}$ | LQR control law |
| 4 | $\hat{x}_{k+1\|k} = A \hat{x}_{k\|k} + B u_k$ | Kalman predict |

Starting from initial position $x_0 = [1, 0]^T$, the LQG regulator drives the position to zero while the Kalman Filter's estimated trajectory converges to the true state despite measurement noise.

## Variants & Generalizations

- **LQG/LTR (Loop Transfer Recovery):** A systematic method to recover the robustness margins of the full-state LQR design, which are not preserved by the LQG output-feedback loop. Achieved by scaling $Q_w \to \rho B B^T$ with $\rho \to \infty$.
- **Output-feedback MPC:** Replaces the LQR regulator with an MPC solver while retaining the Kalman Filter estimator. Handles hard state and input constraints at the cost of online optimisation.
- **LQG with integral action:** Augments the state with an integrator on the tracking error to eliminate steady-state offset for step reference signals. The augmented system $(A_a, B_a, C_a)$ is formed and the DARE solved on the expanded state.
- **Reduced-order Kalman Filter:** When $p < n$, a Luenberger observer with Kalman-optimal gain provides a simpler alternative to the full Kalman Filter.
- **Extended/Unscented LQG:** Replaces the Kalman Filter with EKF or UKF for mildly nonlinear plants while keeping the LQR gain computed around the operating point.

## Applications

- **Aerospace guidance:** Inertial navigation systems use LQG to fuse accelerometer/gyroscope measurements with GPS for optimal state estimation under sensor noise.
- **Vibration suppression:** Active damping in flexible structures (spacecraft appendages, machine tools) employs LQG to attenuate resonant modes while rejecting measurement noise from strain gauges.
- **Process control:** Chemical reactors and distillation columns use LQG when only a subset of states are measured (e.g., temperature at one point, not at every tray).
- **Robotics:** Joint torque control in manipulators with encoder noise and flexible joint dynamics benefits from LQG to smooth out the velocity estimates used by the feedback law.
- **Automotive:** Active suspension and powertrain control use LQG to balance ride comfort (low state weight on acceleration) against actuator energy (high control weight) while filtering noisy road-profile sensors.

## Connections to Other Algorithms

- **LQR:** LQG reduces to LQR when full state is directly observed (no noise, identity measurement matrix).
- **Kalman Filter:** The estimation subproblem is exactly the standard Kalman Filter.
- **MPC:** Model Predictive Control generalises LQR to handle hard constraints on states and inputs; LQG provides the estimator component in output-feedback MPC.
- **DARE Solver:** Both LQR and the steady-state Kalman Filter depend on the Discrete Algebraic Riccati Equation.
- **Separation Principle:** Connects to the Certainty Equivalence Principle in stochastic optimal control, which states that the optimal policy under Gaussian uncertainty acts as if the state estimate is the true state.

## References & Further Reading

- B. D. O. Anderson and J. B. Moore, *Optimal Control: Linear Quadratic Methods*, Prentice Hall, 1990. Chapters 7–9.
- K. J. Åström, *Introduction to Stochastic Control Theory*, Dover, 2006.
- R. E. Kalman, "A New Approach to Linear Filtering and Prediction Problems," *ASME Journal of Basic Engineering*, 82(1):35–45, 1960.
- J. C. Doyle, "Guaranteed Margins for LQG Regulators," *IEEE Transactions on Automatic Control*, 23(4):756–757, 1978. (Motivation for LQG/LTR.)
- G. F. Franklin, J. D. Powell, and M. L. Emami-Naeini, *Feedback Control of Dynamic Systems*, 8th ed., Pearson, 2019. Chapter 9.
Loading
Loading