From 7c081cc31ef918af888b60e6f9eff0ef590b975a Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Thu, 23 Apr 2026 21:13:28 +0000 Subject: [PATCH 1/4] introduce LQG and State spaces --- .vscode/launch.json | 20 +++ doc/controllers/LinearTimeInvariant.md | 122 ++++++++++++++ doc/controllers/Lqg.md | 154 ++++++++++++++++++ doc/controllers/README.md | 2 + .../implementations/CMakeLists.txt | 3 + numerical/controllers/implementations/Lqg.cpp | 7 + numerical/controllers/implementations/Lqg.hpp | 104 ++++++++++++ numerical/controllers/implementations/Lqr.hpp | 29 +++- numerical/controllers/implementations/Mpc.hpp | 32 +++- .../implementations/test/CMakeLists.txt | 2 + .../implementations/test/TestLqg.cpp | 103 ++++++++++++ .../implementations/test/TestLqr.cpp | 26 +++ .../implementations/test/TestMpc.cpp | 31 ++++ .../test/TestStateFeedbackController.cpp | 72 ++++++++ .../controllers/interfaces/CMakeLists.txt | 4 +- .../controllers/interfaces/MpcController.hpp | 33 ---- .../interfaces/OutputFeedbackController.hpp | 27 +++ ...roller.hpp => StateFeedbackController.hpp} | 9 +- numerical/filters/active/KalmanFilter.hpp | 30 ++++ numerical/filters/active/KalmanSmoother.hpp | 27 +++ .../filters/active/test/TestKalmanFilter.cpp | 54 ++++++ .../active/test/TestKalmanSmoother.cpp | 13 ++ numerical/math/CMakeLists.txt | 2 + numerical/math/LinearTimeInvariant.cpp | 15 ++ numerical/math/LinearTimeInvariant.hpp | 95 +++++++++++ numerical/math/test/CMakeLists.txt | 1 + .../math/test/TestLinearTimeInvariant.cpp | 143 ++++++++++++++++ simulator/controllers/CMakeLists.txt | 1 + simulator/controllers/Lqg/CMakeLists.txt | 24 +++ simulator/controllers/Lqg/Main.cpp | 12 ++ .../Lqg/application/CMakeLists.txt | 24 +++ .../Lqg/application/LqgSimulator.cpp | 80 +++++++++ .../Lqg/application/LqgSimulator.hpp | 60 +++++++ simulator/controllers/Lqg/view/CMakeLists.txt | 31 ++++ .../Lqg/view/LqgConfigurationPanel.cpp | 99 +++++++++++ .../Lqg/view/LqgConfigurationPanel.hpp | 36 ++++ .../controllers/Lqg/view/LqgMainWindow.cpp | 66 ++++++++ .../controllers/Lqg/view/LqgMainWindow.hpp | 31 ++++ .../LqrCartPole/application/CartPolePlant.cpp | 6 + .../LqrCartPole/application/CartPolePlant.hpp | 2 + .../application/LqrCartPoleSimulator.cpp | 7 +- .../application/LqrCartPoleSimulator.hpp | 6 +- .../Mpc/application/MpcSimulator.cpp | 17 +- .../Mpc/application/MpcSimulator.hpp | 6 +- .../Mpc/application/StateSpacePlant.cpp | 30 ++-- .../Mpc/application/StateSpacePlant.hpp | 14 +- .../Mpc/view/MpcConfigurationPanel.cpp | 2 +- .../Mpc/view/MpcConfigurationPanel.hpp | 2 +- .../application/KalmanFilterSimulator.cpp | 13 +- 49 files changed, 1618 insertions(+), 111 deletions(-) create mode 100644 doc/controllers/LinearTimeInvariant.md create mode 100644 doc/controllers/Lqg.md create mode 100644 numerical/controllers/implementations/Lqg.cpp create mode 100644 numerical/controllers/implementations/Lqg.hpp create mode 100644 numerical/controllers/implementations/test/TestLqg.cpp create mode 100644 numerical/controllers/implementations/test/TestStateFeedbackController.cpp delete mode 100644 numerical/controllers/interfaces/MpcController.hpp create mode 100644 numerical/controllers/interfaces/OutputFeedbackController.hpp rename numerical/controllers/interfaces/{LqrController.hpp => StateFeedbackController.hpp} (67%) create mode 100644 numerical/math/LinearTimeInvariant.cpp create mode 100644 numerical/math/LinearTimeInvariant.hpp create mode 100644 numerical/math/test/TestLinearTimeInvariant.cpp create mode 100644 simulator/controllers/Lqg/CMakeLists.txt create mode 100644 simulator/controllers/Lqg/Main.cpp create mode 100644 simulator/controllers/Lqg/application/CMakeLists.txt create mode 100644 simulator/controllers/Lqg/application/LqgSimulator.cpp create mode 100644 simulator/controllers/Lqg/application/LqgSimulator.hpp create mode 100644 simulator/controllers/Lqg/view/CMakeLists.txt create mode 100644 simulator/controllers/Lqg/view/LqgConfigurationPanel.cpp create mode 100644 simulator/controllers/Lqg/view/LqgConfigurationPanel.hpp create mode 100644 simulator/controllers/Lqg/view/LqgMainWindow.cpp create mode 100644 simulator/controllers/Lqg/view/LqgMainWindow.hpp diff --git a/.vscode/launch.json b/.vscode/launch.json index 1bf9936c..8c9f63fb 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -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", diff --git a/doc/controllers/LinearTimeInvariant.md b/doc/controllers/LinearTimeInvariant.md new file mode 100644 index 00000000..e1a6cd9d --- /dev/null +++ b/doc/controllers/LinearTimeInvariant.md @@ -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 and Limitations + +- **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). diff --git a/doc/controllers/Lqg.md b/doc/controllers/Lqg.md new file mode 100644 index 00000000..f3f7b07d --- /dev/null +++ b/doc/controllers/Lqg.md @@ -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 and Limitations + +- **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. diff --git a/doc/controllers/README.md b/doc/controllers/README.md index 97b62354..c03f6164 100644 --- a/doc/controllers/README.md +++ b/doc/controllers/README.md @@ -8,4 +8,6 @@ Feedback control algorithms for regulating dynamic systems in real time. |--------------------------|-----------------------------------------------------------------------------------------| | [PID Controller](Pid.md) | Proportional-Integral-Derivative controller using a discrete recursive formulation | | [LQR Controller](Lqr.md) | Linear Quadratic Regulator — optimal state-feedback control minimizing a quadratic cost | +| [LQG Controller](Lqg.md) | Linear Quadratic Gaussian — output-feedback optimal control via LQR + Kalman Filter | | [MPC Controller](Mpc.md) | Model Predictive Controller — receding-horizon optimal control with constraint handling | +| [Linear Time-Invariant Model](LinearTimeInvariant.md) | Discrete-time state-space plant model (A, B, C, D) shared across controllers and filters | diff --git a/numerical/controllers/implementations/CMakeLists.txt b/numerical/controllers/implementations/CMakeLists.txt index c3519726..5d5be31e 100644 --- a/numerical/controllers/implementations/CMakeLists.txt +++ b/numerical/controllers/implementations/CMakeLists.txt @@ -7,16 +7,19 @@ target_include_directories(numerical.controllers.implementations ${NUMERICAL_VIS target_link_libraries(numerical.controllers.implementations ${NUMERICAL_VISIBILITY} numerical.controllers.interfaces + numerical.filters.active numerical.solver ) target_sources(numerical.controllers.implementations PRIVATE + Lqg.hpp Lqr.hpp Mpc.hpp PidIncremental.hpp ) numerical_add_coverage_sources(numerical.controllers.implementations + Lqg.cpp Lqr.cpp Mpc.cpp PidIncremental.cpp diff --git a/numerical/controllers/implementations/Lqg.cpp b/numerical/controllers/implementations/Lqg.cpp new file mode 100644 index 00000000..98d41bd3 --- /dev/null +++ b/numerical/controllers/implementations/Lqg.cpp @@ -0,0 +1,7 @@ +#include "numerical/controllers/implementations/Lqg.hpp" + +namespace controllers +{ + template class Lqg; + template class Lqg; +} diff --git a/numerical/controllers/implementations/Lqg.hpp b/numerical/controllers/implementations/Lqg.hpp new file mode 100644 index 00000000..1453e239 --- /dev/null +++ b/numerical/controllers/implementations/Lqg.hpp @@ -0,0 +1,104 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/controllers/implementations/Lqr.hpp" +#include "numerical/controllers/interfaces/OutputFeedbackController.hpp" +#include "numerical/filters/active/KalmanFilter.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" + +namespace controllers +{ + template + struct LqgWeights + { + math::SquareMatrix Q{}; + math::SquareMatrix R{}; + }; + + template + struct LqgNoise + { + math::SquareMatrix processNoise{}; + math::SquareMatrix measurementNoise{}; + }; + + template + class Lqg + : public OutputFeedbackController + { + static_assert(StateSize > 0, "StateSize must be positive"); + static_assert(InputSize > 0, "InputSize must be positive"); + static_assert(MeasurementSize > 0, "MeasurementSize must be positive"); + + public: + using typename OutputFeedbackController::InputVector; + using typename OutputFeedbackController::MeasurementVector; + using StateVector = math::Vector; + using StateCovarianceMatrix = math::SquareMatrix; + + Lqg(const math::LinearTimeInvariant& plant, + const LqgNoise& noise, + const LqgWeights& weights, + const StateVector& initialState, + const StateCovarianceMatrix& initialCovariance); + + InputVector ComputeControl(const MeasurementVector& measurement) override; + + [[nodiscard]] StateVector GetEstimatedState() const; + + [[nodiscard]] const typename Lqr::GainMatrix& GetGain() const; + + private: + filters::KalmanFilter estimator; + Lqr regulator; + }; + + // Implementation // + + template + Lqg::Lqg( + const math::LinearTimeInvariant& plant, + const LqgNoise& noise, + const LqgWeights& weights, + const StateVector& initialState, + const StateCovarianceMatrix& initialCovariance) + : estimator{ initialState, initialCovariance } + , regulator{ plant.A, plant.B, weights.Q, weights.R } + { + estimator.SetPlant(plant); + estimator.SetProcessNoise(noise.processNoise); + estimator.SetMeasurementNoise(noise.measurementNoise); + } + + template + typename Lqg::InputVector + Lqg::ComputeControl(const MeasurementVector& measurement) + { + estimator.Update(measurement); + const auto u = regulator.ComputeControl(estimator.GetState()); + estimator.Predict(u); + return u; + } + + template + typename Lqg::StateVector + Lqg::GetEstimatedState() const + { + return estimator.GetState(); + } + + template + const typename Lqr::GainMatrix& + Lqg::GetGain() const + { + return regulator.GetGain(); + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class Lqg; + extern template class Lqg; +#endif +} diff --git a/numerical/controllers/implementations/Lqr.hpp b/numerical/controllers/implementations/Lqr.hpp index eb3f43d4..32835dc5 100644 --- a/numerical/controllers/implementations/Lqr.hpp +++ b/numerical/controllers/implementations/Lqr.hpp @@ -5,8 +5,9 @@ #endif #include "infra/util/ReallyAssert.hpp" -#include "numerical/controllers/interfaces/LqrController.hpp" +#include "numerical/controllers/interfaces/StateFeedbackController.hpp" #include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include "numerical/solvers/DiscreteAlgebraicRiccatiEquation.hpp" #include "numerical/solvers/GaussianElimination.hpp" @@ -14,21 +15,26 @@ namespace controllers { template class Lqr - : public LqrController + : public StateFeedbackController { + using Base = StateFeedbackController; + public: - using typename LqrController::StateMatrix; - using typename LqrController::InputMatrix; - using typename LqrController::StateVector; - using typename LqrController::InputVector; - using typename LqrController::GainMatrix; + using typename Base::InputVector; + using typename Base::StateVector; + using StateMatrix = math::SquareMatrix; + using InputMatrix = math::Matrix; + using GainMatrix = math::Matrix; using InputWeightMatrix = math::SquareMatrix; Lqr(const StateMatrix& A, const InputMatrix& B, const StateMatrix& Q, const InputWeightMatrix& R); explicit Lqr(const GainMatrix& precomputedGain); + Lqr(const math::LinearTimeInvariant& plant, + const StateMatrix& Q, const InputWeightMatrix& R); + InputVector ComputeControl(const StateVector& state) override; - [[nodiscard]] const GainMatrix& GetGain() const override; + [[nodiscard]] const GainMatrix& GetGain() const; [[nodiscard]] const StateMatrix& GetRiccatiSolution() const; private: @@ -76,6 +82,13 @@ namespace controllers return riccatiSolution; } + template + Lqr::Lqr( + const math::LinearTimeInvariant& plant, + const StateMatrix& Q, const InputWeightMatrix& R) + : Lqr(plant.A, plant.B, Q, R) + {} + template OPTIMIZE_FOR_SPEED void Lqr::ComputeGain( const StateMatrix& A, const InputMatrix& B, const StateMatrix& P, const InputWeightMatrix& R) diff --git a/numerical/controllers/implementations/Mpc.hpp b/numerical/controllers/implementations/Mpc.hpp index e9c72a0e..e6d7d94a 100644 --- a/numerical/controllers/implementations/Mpc.hpp +++ b/numerical/controllers/implementations/Mpc.hpp @@ -1,7 +1,8 @@ #pragma once -#include "numerical/controllers/interfaces/MpcController.hpp" +#include "numerical/controllers/interfaces/StateFeedbackController.hpp" #include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include "numerical/solvers/GaussianElimination.hpp" #include #include @@ -42,19 +43,24 @@ namespace controllers template class Mpc - : public MpcController + : public StateFeedbackController { - using Base = MpcController; + using Base = StateFeedbackController; + + static_assert(PredictionHorizon > 0, + "Prediction horizon must be positive"); + static_assert(ControlHorizon > 0 && ControlHorizon <= PredictionHorizon, + "Control horizon must be positive and not exceed prediction horizon"); static constexpr std::size_t TotalControlDim = ControlHorizon * InputSize; static constexpr std::size_t TotalStateDim = PredictionHorizon * StateSize; public: - using typename Base::ControlSequence; - using typename Base::InputMatrix; using typename Base::InputVector; - using typename Base::StateMatrix; using typename Base::StateVector; + using StateMatrix = math::SquareMatrix; + using InputMatrix = math::Matrix; + using ControlSequence = std::array; using InputWeightMatrix = math::SquareMatrix; using HessianMatrix = math::SquareMatrix; @@ -64,11 +70,15 @@ namespace controllers const MpcWeights& weights, const MpcConstraints& constraints = MpcConstraints{}); + Mpc(const math::LinearTimeInvariant& plant, + const MpcWeights& weights, + const MpcConstraints& constraints = MpcConstraints{}); + Mpc(const HessianMatrix& precomputedH, const GradientMatrix& precomputedF, const MpcConstraints& constraints = MpcConstraints{}); InputVector ComputeControl(const StateVector& state) override; - [[nodiscard]] const ControlSequence& GetControlSequence() const override; + [[nodiscard]] const ControlSequence& GetControlSequence() const; void SetReference(const StateVector& reference); void ClearReference(); @@ -115,6 +125,14 @@ namespace controllers , constraints(constraints) {} + template + Mpc::Mpc( + const math::LinearTimeInvariant& plant, + const MpcWeights& weights, + const MpcConstraints& constraints) + : Mpc(plant.A, plant.B, weights, constraints) + {} + template OPTIMIZE_FOR_SPEED auto Mpc::BuildPsi( const StateMatrix& A) const -> PredictionStateMatrix diff --git a/numerical/controllers/implementations/test/CMakeLists.txt b/numerical/controllers/implementations/test/CMakeLists.txt index cefd5feb..fd1e42e6 100644 --- a/numerical/controllers/implementations/test/CMakeLists.txt +++ b/numerical/controllers/implementations/test/CMakeLists.txt @@ -9,7 +9,9 @@ target_link_libraries(numerical.controllers_test PUBLIC ) target_sources(numerical.controllers_test PRIVATE + TestLqg.cpp TestLqr.cpp TestMpc.cpp TestPidIncremental.cpp + TestStateFeedbackController.cpp ) diff --git a/numerical/controllers/implementations/test/TestLqg.cpp b/numerical/controllers/implementations/test/TestLqg.cpp new file mode 100644 index 00000000..ceba7382 --- /dev/null +++ b/numerical/controllers/implementations/test/TestLqg.cpp @@ -0,0 +1,103 @@ +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/controllers/implementations/Lqg.hpp" +#include + +namespace +{ + class TestLqg : public ::testing::Test + { + protected: + static constexpr std::size_t stateSize = 2; + static constexpr std::size_t inputSize = 1; + static constexpr std::size_t measurementSize = 1; + + math::SquareMatrix A{ + { 1.0f, 0.1f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.1f } + }; + math::Matrix C{ + { 1.0f, 0.0f } + }; + math::Matrix D{}; + + math::LinearTimeInvariant plant{ A, B, C, D }; + + controllers::LqgWeights weights{ + math::SquareMatrix{ { 10.0f, 0.0f }, { 0.0f, 1.0f } }, + math::SquareMatrix{ { 0.1f } } + }; + + controllers::LqgNoise noise{ + math::SquareMatrix{ { 0.01f, 0.0f }, { 0.0f, 0.01f } }, + math::SquareMatrix{ { 0.1f } } + }; + + math::Vector initialState{}; + math::SquareMatrix initialCovariance{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + + controllers::Lqg lqg{ + plant, noise, weights, initialState, initialCovariance + }; + }; +} + +TEST_F(TestLqg, compute_control_returns_finite_value_for_zero_measurement) +{ + math::Vector z{}; + auto u = lqg.ComputeControl(z); + EXPECT_TRUE(std::isfinite(u.at(0, 0))); +} + +TEST_F(TestLqg, get_gain_returns_nonzero_lqr_gain) +{ + const auto& K = lqg.GetGain(); + float normSq = K.at(0, 0) * K.at(0, 0) + K.at(0, 1) * K.at(0, 1); + EXPECT_GT(normSq, 0.0f); +} + +TEST_F(TestLqg, get_estimated_state_starts_at_initial_state) +{ + auto x = lqg.GetEstimatedState(); + EXPECT_NEAR(x.at(0, 0), initialState.at(0, 0), 1e-6f); + EXPECT_NEAR(x.at(1, 0), initialState.at(1, 0), 1e-6f); +} + +TEST_F(TestLqg, repeated_calls_update_estimated_state) +{ + math::Vector z{ { 1.0f } }; + lqg.ComputeControl(z); + lqg.ComputeControl(z); + + auto x = lqg.GetEstimatedState(); + EXPECT_NE(x.at(0, 0), initialState.at(0, 0)); +} + +TEST_F(TestLqg, control_drives_state_toward_zero) +{ + math::Vector z{ { 5.0f } }; + + float firstU = lqg.ComputeControl(z).at(0, 0); + + math::Vector zNear{ { 0.1f } }; + float laterU = lqg.ComputeControl(zNear).at(0, 0); + + EXPECT_LT(std::abs(laterU), std::abs(firstU) + 1.0f); +} + +TEST_F(TestLqg, lqg_satisfies_output_feedback_controller_interface) +{ + controllers::OutputFeedbackController* ptr = &lqg; + math::Vector z{}; + auto u = ptr->ComputeControl(z); + EXPECT_TRUE(std::isfinite(u.at(0, 0))); +} diff --git a/numerical/controllers/implementations/test/TestLqr.cpp b/numerical/controllers/implementations/test/TestLqr.cpp index 26f7b095..18b46479 100644 --- a/numerical/controllers/implementations/test/TestLqr.cpp +++ b/numerical/controllers/implementations/test/TestLqr.cpp @@ -1,4 +1,5 @@ #include "numerical/controllers/implementations/Lqr.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include namespace @@ -87,3 +88,28 @@ TEST_F(TestLqr, dare_constructor_stores_riccati_solution) EXPECT_GT(lqr.GetRiccatiSolution().at(0, 0), 0.0f); } + +TEST_F(TestLqr, lqr_from_lti_matches_lqr_from_matrices) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.1f } + }; + math::SquareMatrix Q{ + { 10.0f, 0.0f }, + { 0.0f, 1.0f } + }; + math::SquareMatrix R{ { 0.1f } }; + + auto plant = math::LinearTimeInvariant::WithFullStateOutput(A, B); + + controllers::Lqr lqrFromMatrices{ A, B, Q, R }; + controllers::Lqr lqrFromLti{ plant, Q, R }; + + EXPECT_NEAR(lqrFromMatrices.GetGain().at(0, 0), lqrFromLti.GetGain().at(0, 0), 1e-4f); + EXPECT_NEAR(lqrFromMatrices.GetGain().at(0, 1), lqrFromLti.GetGain().at(0, 1), 1e-4f); +} diff --git a/numerical/controllers/implementations/test/TestMpc.cpp b/numerical/controllers/implementations/test/TestMpc.cpp index f994ab0b..bf2f06b9 100644 --- a/numerical/controllers/implementations/test/TestMpc.cpp +++ b/numerical/controllers/implementations/test/TestMpc.cpp @@ -1,4 +1,5 @@ #include "numerical/controllers/implementations/Mpc.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include namespace @@ -725,3 +726,33 @@ TEST_F(TestMpc, different_horizons_clear_reference) auto u2 = mpc.ComputeControl(state); EXPECT_NEAR(u2.at(0, 0), 0.0f, 1e-4f); } + +TEST_F(TestMpc, mpc_from_lti_matches_mpc_from_matrices) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.005f }, + { 0.1f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ { 0.1f } }; + + auto plant = math::LinearTimeInvariant::WithFullStateOutput(A, B); + + controllers::Mpc mpcFromMatrices{ A, B, weights }; + controllers::Mpc mpcFromLti{ plant, weights }; + + math::Vector state{ { 1.0f }, { 0.0f } }; + auto uMatrices = mpcFromMatrices.ComputeControl(state); + auto uLti = mpcFromLti.ComputeControl(state); + + EXPECT_NEAR(uMatrices.at(0, 0), uLti.at(0, 0), 1e-4f); +} diff --git a/numerical/controllers/implementations/test/TestStateFeedbackController.cpp b/numerical/controllers/implementations/test/TestStateFeedbackController.cpp new file mode 100644 index 00000000..b9a951f1 --- /dev/null +++ b/numerical/controllers/implementations/test/TestStateFeedbackController.cpp @@ -0,0 +1,72 @@ +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/controllers/implementations/Lqr.hpp" +#include "numerical/controllers/implementations/Mpc.hpp" +#include "numerical/controllers/interfaces/StateFeedbackController.hpp" +#include +#include + +namespace +{ + class TestStateFeedbackController : public ::testing::Test + { + protected: + math::SquareMatrix A{ + { 1.0f, 0.1f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.1f } + }; + math::SquareMatrix Q{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + math::SquareMatrix R{ { 0.1f } }; + }; +} + +TEST_F(TestStateFeedbackController, lqr_is_derived_from_state_feedback_controller) +{ + static_assert( + std::is_base_of_v< + controllers::StateFeedbackController, + controllers::Lqr>, + "Lqr must derive from StateFeedbackController"); +} + +TEST_F(TestStateFeedbackController, mpc_is_derived_from_state_feedback_controller) +{ + static_assert( + std::is_base_of_v< + controllers::StateFeedbackController, + controllers::Mpc>, + "Mpc must derive from StateFeedbackController"); +} + +TEST_F(TestStateFeedbackController, lqr_compute_control_returns_nonzero_for_nonzero_state) +{ + controllers::Lqr lqr{ A, B, Q, R }; + + math::Vector state{ { 1.0f }, { 0.0f } }; + auto u = lqr.ComputeControl(state); + + EXPECT_NE(u.at(0, 0), 0.0f); +} + +TEST_F(TestStateFeedbackController, mpc_compute_control_returns_nonzero_for_nonzero_state) +{ + controllers::MpcWeights weights; + weights.Q = Q; + weights.R = R; + + controllers::Mpc mpc{ A, B, weights }; + + math::Vector state{ { 1.0f }, { 0.0f } }; + auto u = mpc.ComputeControl(state); + + EXPECT_NE(u.at(0, 0), 0.0f); +} diff --git a/numerical/controllers/interfaces/CMakeLists.txt b/numerical/controllers/interfaces/CMakeLists.txt index de3f0ad2..43a47628 100644 --- a/numerical/controllers/interfaces/CMakeLists.txt +++ b/numerical/controllers/interfaces/CMakeLists.txt @@ -11,8 +11,8 @@ target_link_libraries(numerical.controllers.interfaces INTERFACE ) target_sources(numerical.controllers.interfaces PRIVATE - LqrController.hpp - MpcController.hpp + OutputFeedbackController.hpp PidController.hpp PidDriver.hpp + StateFeedbackController.hpp ) diff --git a/numerical/controllers/interfaces/MpcController.hpp b/numerical/controllers/interfaces/MpcController.hpp deleted file mode 100644 index 1a90a167..00000000 --- a/numerical/controllers/interfaces/MpcController.hpp +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include "numerical/math/Matrix.hpp" -#include "numerical/math/QNumber.hpp" -#include - -namespace controllers -{ - template - class MpcController - { - static_assert(math::detail::is_supported_type_v, - "MpcController only supports float or QNumber types"); - static_assert(math::detail::is_valid_dimensions_v, - "State dimensions must be positive"); - static_assert(math::detail::is_valid_dimensions_v, - "Input dimensions must be positive"); - static_assert(PredictionHorizon > 0, - "Prediction horizon must be positive"); - static_assert(ControlHorizon > 0 && ControlHorizon <= PredictionHorizon, - "Control horizon must be positive and not exceed prediction horizon"); - - public: - using StateMatrix = math::SquareMatrix; - using InputMatrix = math::Matrix; - using StateVector = math::Vector; - using InputVector = math::Vector; - using ControlSequence = std::array; - - virtual InputVector ComputeControl(const StateVector& state) = 0; - [[nodiscard]] virtual const ControlSequence& GetControlSequence() const = 0; - }; -} diff --git a/numerical/controllers/interfaces/OutputFeedbackController.hpp b/numerical/controllers/interfaces/OutputFeedbackController.hpp new file mode 100644 index 00000000..f911b472 --- /dev/null +++ b/numerical/controllers/interfaces/OutputFeedbackController.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include "numerical/math/Matrix.hpp" +#include "numerical/math/QNumber.hpp" + +namespace controllers +{ + template + class OutputFeedbackController + { + static_assert(math::detail::is_supported_type_v, + "OutputFeedbackController only supports float or QNumber types"); + static_assert(math::detail::is_valid_dimensions_v, + "State dimensions must be positive"); + static_assert(math::detail::is_valid_dimensions_v, + "Input dimensions must be positive"); + static_assert(math::detail::is_valid_dimensions_v, + "Measurement dimensions must be positive"); + + public: + using MeasurementVector = math::Vector; + using InputVector = math::Vector; + + virtual ~OutputFeedbackController() = default; + virtual InputVector ComputeControl(const MeasurementVector& measurement) = 0; + }; +} diff --git a/numerical/controllers/interfaces/LqrController.hpp b/numerical/controllers/interfaces/StateFeedbackController.hpp similarity index 67% rename from numerical/controllers/interfaces/LqrController.hpp rename to numerical/controllers/interfaces/StateFeedbackController.hpp index 5a8e0808..f8f8dab3 100644 --- a/numerical/controllers/interfaces/LqrController.hpp +++ b/numerical/controllers/interfaces/StateFeedbackController.hpp @@ -6,23 +6,20 @@ namespace controllers { template - class LqrController + class StateFeedbackController { static_assert(math::detail::is_supported_type_v, - "LqrController only supports float or QNumber types"); + "StateFeedbackController only supports float or QNumber types"); static_assert(math::detail::is_valid_dimensions_v, "State dimensions must be positive"); static_assert(math::detail::is_valid_dimensions_v, "Input dimensions must be positive"); public: - using StateMatrix = math::SquareMatrix; - using InputMatrix = math::Matrix; using StateVector = math::Vector; using InputVector = math::Vector; - using GainMatrix = math::Matrix; + virtual ~StateFeedbackController() = default; virtual InputVector ComputeControl(const StateVector& state) = 0; - [[nodiscard]] virtual const GainMatrix& GetGain() const = 0; }; } diff --git a/numerical/filters/active/KalmanFilter.hpp b/numerical/filters/active/KalmanFilter.hpp index cc553732..5979fd2f 100644 --- a/numerical/filters/active/KalmanFilter.hpp +++ b/numerical/filters/active/KalmanFilter.hpp @@ -2,6 +2,7 @@ #include "numerical/filters/active/KalmanFilterBase.hpp" #include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #if defined(__GNUC__) || defined(__clang__) #pragma GCC optimize("O3", "fast-math") @@ -32,6 +33,16 @@ namespace filters void SetControlInputMatrix(const ControlMatrix& B) requires(ControlSize > 0); + // Convenience: configure F, H (and B when ControlSize > 0) from an LTI plant. + // LTI template args: + // Maps: plant.A -> state transition (F), plant.C -> measurement matrix (H), + // plant.B -> control input matrix (B, only when ControlSize > 0) + void SetPlant(const math::LinearTimeInvariant& plant) + requires(ControlSize > 0); + + void SetPlant(const math::LinearTimeInvariant& plant) + requires(ControlSize == 0); + void Predict(); void Predict(const ControlVector& u) @@ -72,6 +83,25 @@ namespace filters controlInputMatrix = B; } + template + void KalmanFilter::SetPlant( + const math::LinearTimeInvariant& plant) + requires(ControlSize > 0) + { + SetStateTransition(plant.A); + SetMeasurementMatrix(plant.C); + SetControlInputMatrix(plant.B); + } + + template + void KalmanFilter::SetPlant( + const math::LinearTimeInvariant& plant) + requires(ControlSize == 0) + { + SetStateTransition(plant.A); + SetMeasurementMatrix(plant.C); + } + template OPTIMIZE_FOR_SPEED void KalmanFilter::Predict() { diff --git a/numerical/filters/active/KalmanSmoother.hpp b/numerical/filters/active/KalmanSmoother.hpp index 16ab2123..e11a3680 100644 --- a/numerical/filters/active/KalmanSmoother.hpp +++ b/numerical/filters/active/KalmanSmoother.hpp @@ -5,6 +5,7 @@ #endif #include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include "numerical/math/Matrix.hpp" #include "numerical/solvers/CholeskyDecomposition.hpp" #include "numerical/solvers/GaussianElimination.hpp" @@ -51,6 +52,17 @@ namespace filters const StateVector& initialState, const StateMatrix& initialCovariance); + // Convenience overload: extracts F = plant.A, H = plant.C from the LTI model. + // LTI template args: (InputSize unused for smoother) + OPTIMIZE_FOR_SPEED SmootherOutput Smooth( + const math::LinearTimeInvariant& plant, + const StateMatrix& Q, + const MeasurementCovariance& R, + const std::array& observations, + std::size_t numSteps, + const StateVector& initialState, + const StateMatrix& initialCovariance); + private: std::array filteredMeans_{}; std::array filteredCovariances_{}; @@ -233,6 +245,21 @@ namespace filters .Transpose(); } + template + OPTIMIZE_FOR_SPEED + typename KalmanSmoother::SmootherOutput + KalmanSmoother::Smooth( + const math::LinearTimeInvariant& plant, + const StateMatrix& Q, + const MeasurementCovariance& R, + const std::array& observations, + std::size_t numSteps, + const StateVector& initialState, + const StateMatrix& initialCovariance) + { + return Smooth(plant.A, plant.C, Q, R, observations, numSteps, initialState, initialCovariance); + } + #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD extern template class KalmanSmoother<2, 1, 10>; extern template class KalmanSmoother<4, 2, 20>; diff --git a/numerical/filters/active/test/TestKalmanFilter.cpp b/numerical/filters/active/test/TestKalmanFilter.cpp index b88cf67a..38e301a1 100644 --- a/numerical/filters/active/test/TestKalmanFilter.cpp +++ b/numerical/filters/active/test/TestKalmanFilter.cpp @@ -1,4 +1,5 @@ #include "numerical/filters/active/KalmanFilter.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include "numerical/math/Tolerance.hpp" #include @@ -438,3 +439,56 @@ TYPED_TEST(KalmanFilterTest, JosephFormPreservesPositiveDefiniteness) EXPECT_GE(det, 0.0f); } } + +namespace +{ + class KalmanFilterWithControlTest : public ::testing::Test + { + protected: + math::SquareMatrix A{ + { 1.0f, 0.1f }, + { 0.0f, 1.0f } + }; + math::Matrix C{ + { 1.0f, 0.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.1f } + }; + math::SquareMatrix Q{ + { 0.01f, 0.0f }, + { 0.0f, 0.01f } + }; + math::SquareMatrix R{ { 0.1f } }; + + math::Vector zeroState{}; + math::SquareMatrix identity{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + }; +} + +TEST_F(KalmanFilterWithControlTest, set_plant_equivalent_to_individual_setters) +{ + filters::KalmanFilter filterA{ zeroState, identity }; + filters::KalmanFilter filterB{ zeroState, identity }; + + filterA.SetStateTransition(A); + filterA.SetMeasurementMatrix(C); + filterA.SetControlInputMatrix(B); + filterA.SetProcessNoise(Q); + filterA.SetMeasurementNoise(R); + + auto plant = math::LinearTimeInvariant{ A, B, C, {} }; + filterB.SetPlant(plant); + filterB.SetProcessNoise(Q); + filterB.SetMeasurementNoise(R); + + filterA.Predict(math::Vector{ { 1.0f } }); + filterB.Predict(math::Vector{ { 1.0f } }); + + EXPECT_NEAR(math::ToFloat(filterA.GetState().at(0, 0)), math::ToFloat(filterB.GetState().at(0, 0)), 1e-5f); + EXPECT_NEAR(math::ToFloat(filterA.GetState().at(1, 0)), math::ToFloat(filterB.GetState().at(1, 0)), 1e-5f); +} diff --git a/numerical/filters/active/test/TestKalmanSmoother.cpp b/numerical/filters/active/test/TestKalmanSmoother.cpp index ed2f6b7c..74658e3d 100644 --- a/numerical/filters/active/test/TestKalmanSmoother.cpp +++ b/numerical/filters/active/test/TestKalmanSmoother.cpp @@ -1,5 +1,6 @@ #include "numerical/filters/active/KalmanFilter.hpp" #include "numerical/filters/active/KalmanSmoother.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include #include @@ -108,3 +109,15 @@ TEST_F(TestKalmanSmoother, smoothed_covariance_at_first_step_less_than_prior) EXPECT_LT(output.smoothedCovariances[0].at(0, 0), P0.at(0, 0)); EXPECT_LT(output.smoothedCovariances[0].at(1, 1), P0.at(1, 1)); } + +TEST_F(TestKalmanSmoother, smooth_with_lti_matches_smooth_with_matrices) +{ + auto plant = math::LinearTimeInvariant{ F, {}, H, {} }; + + const auto outputMatrices = smoother.Smooth(F, H, Q, R, observations, T, x0, P0); + const auto outputLti = smoother.Smooth(plant, Q, R, observations, T, x0, P0); + + EXPECT_NEAR(outputMatrices.smoothedMeans[0].at(0, 0), outputLti.smoothedMeans[0].at(0, 0), 1e-5f); + EXPECT_NEAR(outputMatrices.smoothedMeans[0].at(1, 0), outputLti.smoothedMeans[0].at(1, 0), 1e-5f); + EXPECT_NEAR(outputMatrices.logLikelihood, outputLti.logLikelihood, 1e-4f); +} diff --git a/numerical/math/CMakeLists.txt b/numerical/math/CMakeLists.txt index 262d87e0..536e6719 100644 --- a/numerical/math/CMakeLists.txt +++ b/numerical/math/CMakeLists.txt @@ -14,6 +14,7 @@ target_sources(numerical.math PRIVATE ComplexNumber.hpp Geometry3D.hpp HyperbolicFunctions.hpp + LinearTimeInvariant.hpp Matrix.hpp QNumber.hpp RecursiveBuffer.hpp @@ -26,6 +27,7 @@ target_sources(numerical.math PRIVATE numerical_add_coverage_sources(numerical.math ComplexNumber.cpp + LinearTimeInvariant.cpp Matrix.cpp QNumber.cpp ) diff --git a/numerical/math/LinearTimeInvariant.cpp b/numerical/math/LinearTimeInvariant.cpp new file mode 100644 index 00000000..cc462534 --- /dev/null +++ b/numerical/math/LinearTimeInvariant.cpp @@ -0,0 +1,15 @@ +#include "numerical/math/LinearTimeInvariant.hpp" + +namespace math +{ + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; + template struct LinearTimeInvariant; +} diff --git a/numerical/math/LinearTimeInvariant.hpp b/numerical/math/LinearTimeInvariant.hpp new file mode 100644 index 00000000..cfc1f7c8 --- /dev/null +++ b/numerical/math/LinearTimeInvariant.hpp @@ -0,0 +1,95 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/Matrix.hpp" +#include "numerical/math/QNumber.hpp" + +namespace math +{ + // Discrete-time linear time-invariant state-space model: + // x_{k+1} = A x_k + B u_k + // y_k = C x_k + D u_k + // + // Template args: + // Default OutputSize = StateSize (full-state output, C = I, D = 0). + template + struct LinearTimeInvariant + { + static_assert(detail::is_supported_type_v, + "LinearTimeInvariant only supports float or QNumber types"); + static_assert(detail::is_valid_dimensions_v, + "StateSize must be positive"); + static_assert(detail::is_valid_dimensions_v, + "InputSize must be positive"); + static_assert(detail::is_valid_dimensions_v, + "OutputSize must be positive"); + + using StateMatrix = SquareMatrix; + using InputMatrix = Matrix; + using OutputMatrix = Matrix; + using FeedthroughMatrix = Matrix; + using StateVector = Vector; + using InputVector = Vector; + using OutputVector = Vector; + + StateMatrix A{}; + InputMatrix B{}; + OutputMatrix C{}; + FeedthroughMatrix D{}; + + // x_{k+1} = A x_k + B u_k + ALWAYS_INLINE_HOT StateVector Step(const StateVector& x, const InputVector& u) const + { + return A * x + B * u; + } + + // y_k = C x_k + D u_k + ALWAYS_INLINE_HOT OutputVector Output(const StateVector& x, const InputVector& u) const + { + return C * x + D * u; + } + + // Factory: C = I (OutputSize must equal StateSize), D = 0 + static LinearTimeInvariant WithFullStateOutput( + const StateMatrix& stateTransition, const InputMatrix& inputMatrix) + { + static_assert(OutputSize == StateSize, + "WithFullStateOutput requires OutputSize == StateSize"); + LinearTimeInvariant lti; + lti.A = stateTransition; + lti.B = inputMatrix; + lti.C = OutputMatrix::Identity(); + return lti; + } + + // Factory: autonomous system (B = 0, D = 0) + static LinearTimeInvariant Autonomous( + const StateMatrix& stateTransition, const OutputMatrix& outputMatrix) + { + LinearTimeInvariant lti; + lti.A = stateTransition; + lti.C = outputMatrix; + return lti; + } + }; + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; + extern template struct LinearTimeInvariant; +#endif +} diff --git a/numerical/math/test/CMakeLists.txt b/numerical/math/test/CMakeLists.txt index a12428bd..cb983071 100644 --- a/numerical/math/test/CMakeLists.txt +++ b/numerical/math/test/CMakeLists.txt @@ -9,6 +9,7 @@ target_link_libraries(numerical.math_test PUBLIC target_sources(numerical.math_test PRIVATE TestComplexNumber.cpp + TestLinearTimeInvariant.cpp TestQNumber.cpp TestMatrix.cpp TestRecursiveBuffer.cpp diff --git a/numerical/math/test/TestLinearTimeInvariant.cpp b/numerical/math/test/TestLinearTimeInvariant.cpp new file mode 100644 index 00000000..81d202a7 --- /dev/null +++ b/numerical/math/test/TestLinearTimeInvariant.cpp @@ -0,0 +1,143 @@ +#include "numerical/math/LinearTimeInvariant.hpp" +#include + +namespace +{ + template + class TestLinearTimeInvariant : public ::testing::Test + { + protected: + static T Val(float f) + { + f = std::max(std::min(f, 0.9999f), -0.9999f); + if constexpr (std::is_same_v) + return f; + else + return T(f); + } + + static float ToF(T v) + { + if constexpr (std::is_same_v) + return v; + else + return v.ToFloat(); + } + }; + + using TestTypes = ::testing::Types; + TYPED_TEST_SUITE(TestLinearTimeInvariant, TestTypes); +} + +TYPED_TEST(TestLinearTimeInvariant, default_construction_zeroes_A_B_C_D) +{ + math::LinearTimeInvariant lti; + + for (std::size_t r = 0; r < 2; ++r) + for (std::size_t c = 0; c < 2; ++c) + EXPECT_NEAR(this->ToF(lti.A.at(r, c)), 0.0f, 1e-5f); + + for (std::size_t r = 0; r < 2; ++r) + EXPECT_NEAR(this->ToF(lti.B.at(r, 0)), 0.0f, 1e-5f); +} + +TYPED_TEST(TestLinearTimeInvariant, step_returns_A_x_plus_B_u) +{ + math::LinearTimeInvariant lti; + lti.A = math::SquareMatrix{ + { this->Val(0.9999f), this->Val(0.5f) }, + { this->Val(0.0f), this->Val(0.9f) } + }; + lti.B = math::Matrix{ + { this->Val(0.0f) }, + { this->Val(0.1f) } + }; + + math::Vector x{ { this->Val(0.5f) }, { this->Val(0.25f) } }; + math::Vector u{ { this->Val(0.1f) } }; + + auto xNext = lti.Step(x, u); + + // x_next[0] = ~1.0*0.5 + 0.5*0.25 + 0.0*0.1 ~= 0.625 + // x_next[1] = 0.0*0.5 + 0.9*0.25 + 0.1*0.1 = 0.235 + EXPECT_NEAR(this->ToF(xNext.at(0, 0)), 0.625f, 1e-2f); + EXPECT_NEAR(this->ToF(xNext.at(1, 0)), 0.235f, 1e-2f); +} + +TYPED_TEST(TestLinearTimeInvariant, output_returns_C_x_plus_D_u) +{ + math::LinearTimeInvariant lti; + lti.C = math::Matrix{ + { TypeParam(0.9f), TypeParam(0.0f) } + }; + lti.D = math::Matrix{ { TypeParam(0.0f) } }; + + math::Vector x{ { TypeParam(0.5f) }, { TypeParam(0.25f) } }; + math::Vector u{ { TypeParam(0.1f) } }; + + auto y = lti.Output(x, u); + + // y = 0.9*0.5 + 0.0*0.25 = 0.45 + EXPECT_NEAR(this->ToF(y.at(0, 0)), 0.45f, 5e-3f); +} + +TYPED_TEST(TestLinearTimeInvariant, with_full_state_output_sets_C_to_identity_and_D_to_zero) +{ + auto A = math::SquareMatrix{ + { TypeParam(0.9f), TypeParam(0.1f) }, + { TypeParam(0.0f), TypeParam(0.8f) } + }; + auto B = math::Matrix{ + { TypeParam(0.0f) }, + { TypeParam(0.1f) } + }; + + auto lti = math::LinearTimeInvariant::WithFullStateOutput(A, B); + + // C should be identity + EXPECT_NEAR(this->ToF(lti.C.at(0, 0)), 1.0f, 5e-3f); + EXPECT_NEAR(this->ToF(lti.C.at(1, 1)), 1.0f, 5e-3f); + EXPECT_NEAR(this->ToF(lti.C.at(0, 1)), 0.0f, 1e-5f); + EXPECT_NEAR(this->ToF(lti.C.at(1, 0)), 0.0f, 1e-5f); + + // D should be zero + EXPECT_NEAR(this->ToF(lti.D.at(0, 0)), 0.0f, 1e-5f); +} + +TYPED_TEST(TestLinearTimeInvariant, autonomous_factory_zeroes_B) +{ + auto A = math::SquareMatrix{ + { TypeParam(0.9f), TypeParam(0.0f) }, + { TypeParam(0.0f), TypeParam(0.8f) } + }; + auto C = math::Matrix{ + { TypeParam(0.9f), TypeParam(0.0f) } + }; + + auto lti = math::LinearTimeInvariant::Autonomous(A, C); + + for (std::size_t r = 0; r < 2; ++r) + EXPECT_NEAR(this->ToF(lti.B.at(r, 0)), 0.0f, 1e-5f); +} + +TYPED_TEST(TestLinearTimeInvariant, step_called_twice_propagates_state_correctly) +{ + auto lti = math::LinearTimeInvariant::WithFullStateOutput( + math::SquareMatrix{ + { this->Val(0.9999f), this->Val(0.1f) }, + { this->Val(0.0f), this->Val(0.9f) } }, + math::Matrix{ + { this->Val(0.0f) }, + { this->Val(0.1f) } }); + + math::Vector x{ { TypeParam(0.0f) }, { TypeParam(0.0f) } }; + math::Vector u{ { TypeParam(0.5f) } }; + + x = lti.Step(x, u); + x = lti.Step(x, u); + + // After step 1: x = [0, 0.05] + // After step 2: x = [0.005, 0.095] + EXPECT_NEAR(this->ToF(x.at(0, 0)), 0.005f, 5e-3f); + EXPECT_NEAR(this->ToF(x.at(1, 0)), 0.095f, 5e-3f); +} diff --git a/simulator/controllers/CMakeLists.txt b/simulator/controllers/CMakeLists.txt index 0f242a6d..d0d5a9ed 100644 --- a/simulator/controllers/CMakeLists.txt +++ b/simulator/controllers/CMakeLists.txt @@ -1,5 +1,6 @@ add_subdirectory(common) add_subdirectory(BayesianMpcCalibration) +add_subdirectory(Lqg) add_subdirectory(LqrCartPole) add_subdirectory(Mpc) add_subdirectory(PidController) diff --git a/simulator/controllers/Lqg/CMakeLists.txt b/simulator/controllers/Lqg/CMakeLists.txt new file mode 100644 index 00000000..d91fb485 --- /dev/null +++ b/simulator/controllers/Lqg/CMakeLists.txt @@ -0,0 +1,24 @@ +find_package(Qt6 REQUIRED COMPONENTS Widgets) + +add_subdirectory(application) +add_subdirectory(view) + +add_executable(numerical.simulator.controllers.lqg) +emil_build_for(numerical.simulator.controllers.lqg HOST All PREREQUISITE_BOOL NUMERICAL_TOOLBOX_BUILD_SIMULATOR) + +target_link_libraries(numerical.simulator.controllers.lqg PRIVATE + numerical.simulator.controllers.lqg.application + numerical.simulator.controllers.lqg.view +) + +target_sources(numerical.simulator.controllers.lqg PRIVATE + Main.cpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.lqg PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.lqg PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/Lqg/Main.cpp b/simulator/controllers/Lqg/Main.cpp new file mode 100644 index 00000000..39ce0310 --- /dev/null +++ b/simulator/controllers/Lqg/Main.cpp @@ -0,0 +1,12 @@ +#include "simulator/controllers/Lqg/view/LqgMainWindow.hpp" +#include + +int main(int argc, char* argv[]) +{ + QApplication app(argc, argv); + + simulator::controllers::lqg::view::LqgMainWindow window; + window.show(); + + return app.exec(); +} diff --git a/simulator/controllers/Lqg/application/CMakeLists.txt b/simulator/controllers/Lqg/application/CMakeLists.txt new file mode 100644 index 00000000..a043e5e3 --- /dev/null +++ b/simulator/controllers/Lqg/application/CMakeLists.txt @@ -0,0 +1,24 @@ +add_library(numerical.simulator.controllers.lqg.application STATIC) + +target_include_directories(numerical.simulator.controllers.lqg.application PUBLIC + "$" + "$" +) + +target_link_libraries(numerical.simulator.controllers.lqg.application PUBLIC + numerical.controllers.implementations + numerical.filters.active +) + +target_sources(numerical.simulator.controllers.lqg.application PRIVATE + LqgSimulator.cpp + LqgSimulator.hpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.lqg.application PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.lqg.application PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/Lqg/application/LqgSimulator.cpp b/simulator/controllers/Lqg/application/LqgSimulator.cpp new file mode 100644 index 00000000..7fe8367c --- /dev/null +++ b/simulator/controllers/Lqg/application/LqgSimulator.cpp @@ -0,0 +1,80 @@ +#include "simulator/controllers/Lqg/application/LqgSimulator.hpp" +#include +#include + +namespace simulator::controllers +{ + void LqgSimulator::Configure(const LqgPlant& newPlant, const LqgSimulatorConfig& config) + { + plant = newPlant; + configuration = config; + } + + LqgTimeResponse LqgSimulator::RunStepResponse() + { + LqgTimeResponse result; + + auto& w = configuration.weights; + auto& n = configuration.noise; + auto& sim = configuration.simulation; + + math::SquareMatrix Q{ + { w.stateWeight, 0.0f }, + { 0.0f, w.stateWeight } + }; + math::SquareMatrix R{ { w.controlWeight } }; + + math::SquareMatrix processNoise{ + { n.processNoise, 0.0f }, + { 0.0f, n.processNoise } + }; + math::SquareMatrix measurementNoise{ { n.measurementNoise } }; + + math::Vector initialState{}; + math::SquareMatrix initialCovariance{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + + ::controllers::LqgNoise lqgNoise{ + processNoise, measurementNoise + }; + ::controllers::LqgWeights lqgWeights{ Q, R }; + + LqgController controller(plant, lqgNoise, lqgWeights, initialState, initialCovariance); + + math::Vector trueState{}; + trueState.at(0, 0) = configuration.initialPosition; + + std::mt19937 rng{ 42 }; + std::normal_distribution processDist{ 0.0f, std::sqrt(n.processNoise) }; + std::normal_distribution measureDist{ 0.0f, std::sqrt(n.measurementNoise) }; + + std::size_t steps = static_cast(sim.duration / sim.sampleTime); + result.time.reserve(steps); + result.trueState.reserve(steps); + result.estimatedState.reserve(steps); + result.control.reserve(steps); + + for (std::size_t k = 0; k < steps; ++k) + { + math::Vector measurement{}; + measurement.at(0, 0) = plant.Output(trueState, {}).at(0, 0) + measureDist(rng); + + auto u = controller.ComputeControl(measurement); + + math::Vector noise{}; + noise.at(0, 0) = processDist(rng); + noise.at(1, 0) = processDist(rng); + + trueState = plant.Step(trueState, u) + noise; + + result.time.push_back(static_cast(k) * sim.sampleTime); + result.trueState.push_back(trueState.at(0, 0)); + result.estimatedState.push_back(controller.GetEstimatedState().at(0, 0)); + result.control.push_back(u.at(0, 0)); + } + + return result; + } +} diff --git a/simulator/controllers/Lqg/application/LqgSimulator.hpp b/simulator/controllers/Lqg/application/LqgSimulator.hpp new file mode 100644 index 00000000..54dfddb8 --- /dev/null +++ b/simulator/controllers/Lqg/application/LqgSimulator.hpp @@ -0,0 +1,60 @@ +#pragma once + +#include "numerical/controllers/implementations/Lqg.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" +#include + +namespace simulator::controllers +{ + static constexpr std::size_t lqgStateSize = 2; + static constexpr std::size_t lqgInputSize = 1; + static constexpr std::size_t lqgMeasurementSize = 1; + + using LqgPlant = math::LinearTimeInvariant; + using LqgController = ::controllers::Lqg; + + struct LqgWeightsConfig + { + float stateWeight = 10.0f; + float controlWeight = 0.1f; + }; + + struct LqgNoiseConfig + { + float processNoise = 0.1f; + float measurementNoise = 1.0f; + }; + + struct LqgSimulationConfig + { + float duration = 10.0f; + float sampleTime = 0.1f; + }; + + struct LqgSimulatorConfig + { + LqgWeightsConfig weights; + LqgNoiseConfig noise; + LqgSimulationConfig simulation; + float initialPosition = 1.0f; + }; + + struct LqgTimeResponse + { + std::vector time; + std::vector trueState; + std::vector estimatedState; + std::vector control; + }; + + class LqgSimulator + { + public: + void Configure(const LqgPlant& plant, const LqgSimulatorConfig& config); + LqgTimeResponse RunStepResponse(); + + private: + LqgPlant plant; + LqgSimulatorConfig configuration; + }; +} diff --git a/simulator/controllers/Lqg/view/CMakeLists.txt b/simulator/controllers/Lqg/view/CMakeLists.txt new file mode 100644 index 00000000..ead31905 --- /dev/null +++ b/simulator/controllers/Lqg/view/CMakeLists.txt @@ -0,0 +1,31 @@ +add_library(numerical.simulator.controllers.lqg.view STATIC) + +target_include_directories(numerical.simulator.controllers.lqg.view PUBLIC + "$" + "$" +) + +target_link_libraries(numerical.simulator.controllers.lqg.view PUBLIC + numerical.simulator.controllers.lqg.application + numerical.simulator.widgets + Qt6::Widgets +) + +set_target_properties(numerical.simulator.controllers.lqg.view PROPERTIES + AUTOMOC ON +) + +target_sources(numerical.simulator.controllers.lqg.view PRIVATE + LqgConfigurationPanel.cpp + LqgConfigurationPanel.hpp + LqgMainWindow.cpp + LqgMainWindow.hpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.lqg.view PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.lqg.view PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/Lqg/view/LqgConfigurationPanel.cpp b/simulator/controllers/Lqg/view/LqgConfigurationPanel.cpp new file mode 100644 index 00000000..eed58688 --- /dev/null +++ b/simulator/controllers/Lqg/view/LqgConfigurationPanel.cpp @@ -0,0 +1,99 @@ +#include "simulator/controllers/Lqg/view/LqgConfigurationPanel.hpp" +#include +#include +#include + +namespace simulator::controllers::lqg::view +{ + LqgConfigurationPanel::LqgConfigurationPanel(QWidget* parent) + : QWidget(parent) + { + SetupUi(); + } + + void LqgConfigurationPanel::SetupUi() + { + auto* mainLayout = new QVBoxLayout(this); + + auto* weightsGroup = new QGroupBox("LQR Weights", this); + auto* weightsLayout = new QFormLayout(weightsGroup); + stateWeightSpinBox = new QDoubleSpinBox(this); + stateWeightSpinBox->setRange(0.01, 1000.0); + stateWeightSpinBox->setValue(10.0); + controlWeightSpinBox = new QDoubleSpinBox(this); + controlWeightSpinBox->setRange(0.001, 100.0); + controlWeightSpinBox->setSingleStep(0.01); + controlWeightSpinBox->setValue(0.1); + weightsLayout->addRow("State Weight Q:", stateWeightSpinBox); + weightsLayout->addRow("Control Weight R:", controlWeightSpinBox); + + auto* noiseGroup = new QGroupBox("Kalman Noise", this); + auto* noiseLayout = new QFormLayout(noiseGroup); + processNoiseSpinBox = new QDoubleSpinBox(this); + processNoiseSpinBox->setRange(0.001, 10.0); + processNoiseSpinBox->setSingleStep(0.01); + processNoiseSpinBox->setValue(0.1); + measurementNoiseSpinBox = new QDoubleSpinBox(this); + measurementNoiseSpinBox->setRange(0.001, 10.0); + measurementNoiseSpinBox->setSingleStep(0.1); + measurementNoiseSpinBox->setValue(1.0); + noiseLayout->addRow("Process Noise:", processNoiseSpinBox); + noiseLayout->addRow("Measurement Noise:", measurementNoiseSpinBox); + + auto* simGroup = new QGroupBox("Simulation", this); + auto* simLayout = new QFormLayout(simGroup); + sampleTimeSpinBox = new QDoubleSpinBox(this); + sampleTimeSpinBox->setRange(0.001, 1.0); + sampleTimeSpinBox->setSingleStep(0.01); + sampleTimeSpinBox->setValue(0.1); + durationSpinBox = new QDoubleSpinBox(this); + durationSpinBox->setRange(1.0, 100.0); + durationSpinBox->setValue(10.0); + initialPositionSpinBox = new QDoubleSpinBox(this); + initialPositionSpinBox->setRange(-10.0, 10.0); + initialPositionSpinBox->setValue(1.0); + simLayout->addRow("Sample Time (s):", sampleTimeSpinBox); + simLayout->addRow("Duration (s):", durationSpinBox); + simLayout->addRow("Initial Position:", initialPositionSpinBox); + + computeButton = new QPushButton("Compute", this); + connect(computeButton, &QPushButton::clicked, this, &LqgConfigurationPanel::ComputeRequested); + + mainLayout->addWidget(weightsGroup); + mainLayout->addWidget(noiseGroup); + mainLayout->addWidget(simGroup); + mainLayout->addWidget(computeButton); + mainLayout->addStretch(); + } + + LqgSimulatorConfig LqgConfigurationPanel::GetConfiguration() const + { + LqgSimulatorConfig config; + config.weights.stateWeight = static_cast(stateWeightSpinBox->value()); + config.weights.controlWeight = static_cast(controlWeightSpinBox->value()); + config.noise.processNoise = static_cast(processNoiseSpinBox->value()); + config.noise.measurementNoise = static_cast(measurementNoiseSpinBox->value()); + config.simulation.sampleTime = static_cast(sampleTimeSpinBox->value()); + config.simulation.duration = static_cast(durationSpinBox->value()); + config.initialPosition = static_cast(initialPositionSpinBox->value()); + return config; + } + + LqgPlant LqgConfigurationPanel::CreatePlant() const + { + float dt = static_cast(sampleTimeSpinBox->value()); + math::SquareMatrix A{ + { 1.0f, dt }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { dt } + }; + math::Matrix C{ + { 1.0f, 0.0f } + }; + math::Matrix D{}; + return LqgPlant{ A, B, C, D }; + } +} diff --git a/simulator/controllers/Lqg/view/LqgConfigurationPanel.hpp b/simulator/controllers/Lqg/view/LqgConfigurationPanel.hpp new file mode 100644 index 00000000..32e79f8e --- /dev/null +++ b/simulator/controllers/Lqg/view/LqgConfigurationPanel.hpp @@ -0,0 +1,36 @@ +#pragma once + +#include "simulator/controllers/Lqg/application/LqgSimulator.hpp" +#include +#include +#include + +namespace simulator::controllers::lqg::view +{ + class LqgConfigurationPanel + : public QWidget + { + Q_OBJECT + + public: + explicit LqgConfigurationPanel(QWidget* parent = nullptr); + + LqgSimulatorConfig GetConfiguration() const; + LqgPlant CreatePlant() const; + + signals: + void ComputeRequested(); + + private: + void SetupUi(); + + QDoubleSpinBox* stateWeightSpinBox; + QDoubleSpinBox* controlWeightSpinBox; + QDoubleSpinBox* processNoiseSpinBox; + QDoubleSpinBox* measurementNoiseSpinBox; + QDoubleSpinBox* sampleTimeSpinBox; + QDoubleSpinBox* durationSpinBox; + QDoubleSpinBox* initialPositionSpinBox; + QPushButton* computeButton; + }; +} diff --git a/simulator/controllers/Lqg/view/LqgMainWindow.cpp b/simulator/controllers/Lqg/view/LqgMainWindow.cpp new file mode 100644 index 00000000..5f93f5b9 --- /dev/null +++ b/simulator/controllers/Lqg/view/LqgMainWindow.cpp @@ -0,0 +1,66 @@ +#include "simulator/controllers/Lqg/view/LqgMainWindow.hpp" +#include "simulator/widgets/TimeSeriesChartWidget.hpp" +#include + +namespace simulator::controllers::lqg::view +{ + LqgMainWindow::LqgMainWindow(QWidget* parent) + : QMainWindow(parent) + { + setWindowTitle("LQG Controller Simulator"); + resize(1280, 800); + + auto* splitter = new QSplitter(Qt::Horizontal, this); + + configPanel = new LqgConfigurationPanel(splitter); + configPanel->setMaximumWidth(350); + + chart = new widgets::TimeSeriesChartWidget(splitter); + + splitter->addWidget(configPanel); + splitter->addWidget(chart); + splitter->setStretchFactor(0, 0); + splitter->setStretchFactor(1, 1); + + setCentralWidget(splitter); + + statusBar()->showMessage("Configure LQG parameters and press Compute"); + + connect(configPanel, &LqgConfigurationPanel::ComputeRequested, this, &LqgMainWindow::OnComputeRequested); + } + + void LqgMainWindow::OnComputeRequested() + { + auto config = configPanel->GetConfiguration(); + auto plant = configPanel->CreatePlant(); + lqgSimulator.Configure(plant, config); + + auto result = lqgSimulator.RunStepResponse(); + DisplayResponse(result); + + statusBar()->showMessage( + QString("LQG: Q=%1 R=%2 | ProcessNoise=%3 MeasNoise=%4") + .arg(static_cast(config.weights.stateWeight), 0, 'f', 2) + .arg(static_cast(config.weights.controlWeight), 0, 'f', 3) + .arg(static_cast(config.noise.processNoise), 0, 'f', 3) + .arg(static_cast(config.noise.measurementNoise), 0, 'f', 3)); + } + + void LqgMainWindow::DisplayResponse(const LqgTimeResponse& result) + { + chart->SetTimeAxis(result.time); + chart->SetPanels({ + { "Position", + "x [m]", + { + { "True State", QColor(41, 128, 185), result.trueState }, + { "Estimated State", QColor(231, 76, 60), result.estimatedState }, + } }, + { "Control Input", + "u", + { + { "Control", QColor(39, 174, 96), result.control }, + } }, + }); + } +} diff --git a/simulator/controllers/Lqg/view/LqgMainWindow.hpp b/simulator/controllers/Lqg/view/LqgMainWindow.hpp new file mode 100644 index 00000000..d26451f5 --- /dev/null +++ b/simulator/controllers/Lqg/view/LqgMainWindow.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include "simulator/controllers/Lqg/application/LqgSimulator.hpp" +#include "simulator/controllers/Lqg/view/LqgConfigurationPanel.hpp" +#include +#include + +namespace simulator::widgets +{ + class TimeSeriesChartWidget; +} + +namespace simulator::controllers::lqg::view +{ + class LqgMainWindow + : public QMainWindow + { + Q_OBJECT + + public: + explicit LqgMainWindow(QWidget* parent = nullptr); + + private: + void OnComputeRequested(); + void DisplayResponse(const LqgTimeResponse& result); + + LqgSimulator lqgSimulator; + LqgConfigurationPanel* configPanel; + widgets::TimeSeriesChartWidget* chart; + }; +} diff --git a/simulator/controllers/LqrCartPole/application/CartPolePlant.cpp b/simulator/controllers/LqrCartPole/application/CartPolePlant.cpp index 04d92f38..34b9cf09 100644 --- a/simulator/controllers/LqrCartPole/application/CartPolePlant.cpp +++ b/simulator/controllers/LqrCartPole/application/CartPolePlant.cpp @@ -107,4 +107,10 @@ namespace simulator::controllers::lqr { -dt / (mc * l) }, }; } + + math::LinearTimeInvariant CartPolePlant::Linearize(float dt) const + { + return math::LinearTimeInvariant::WithFullStateOutput( + LinearizedA(dt), LinearizedB(dt)); + } } diff --git a/simulator/controllers/LqrCartPole/application/CartPolePlant.hpp b/simulator/controllers/LqrCartPole/application/CartPolePlant.hpp index dd3b7cba..bf4888fe 100644 --- a/simulator/controllers/LqrCartPole/application/CartPolePlant.hpp +++ b/simulator/controllers/LqrCartPole/application/CartPolePlant.hpp @@ -1,5 +1,6 @@ #pragma once +#include "numerical/math/LinearTimeInvariant.hpp" #include "numerical/math/Matrix.hpp" namespace simulator::controllers::lqr @@ -43,6 +44,7 @@ namespace simulator::controllers::lqr [[nodiscard]] StateMatrix LinearizedA(float dt) const; [[nodiscard]] InputMatrix LinearizedB(float dt) const; + [[nodiscard]] math::LinearTimeInvariant Linearize(float dt) const; private: CartPoleParameters parameters; diff --git a/simulator/controllers/LqrCartPole/application/LqrCartPoleSimulator.cpp b/simulator/controllers/LqrCartPole/application/LqrCartPoleSimulator.cpp index f223dbf5..43bee937 100644 --- a/simulator/controllers/LqrCartPole/application/LqrCartPoleSimulator.cpp +++ b/simulator/controllers/LqrCartPole/application/LqrCartPoleSimulator.cpp @@ -27,9 +27,6 @@ namespace simulator::controllers::lqr void LqrCartPoleSimulator::RecomputeGain() { - auto A = plant.LinearizedA(configuration.simulation.dt); - auto B = plant.LinearizedB(configuration.simulation.dt); - auto& w = configuration.weights; StateMatrix Q{ @@ -41,10 +38,10 @@ namespace simulator::controllers::lqr math::SquareMatrix R{ { w.rForce } }; - lqr = std::make_unique<::controllers::Lqr>(A, B, Q, R); + lqr.emplace(plant.Linearize(configuration.simulation.dt), Q, R); } - float LqrCartPoleSimulator::ComputeControlForce() const + float LqrCartPoleSimulator::ComputeControlForce() { auto& s = plant.GetState(); diff --git a/simulator/controllers/LqrCartPole/application/LqrCartPoleSimulator.hpp b/simulator/controllers/LqrCartPole/application/LqrCartPoleSimulator.hpp index 4afa92d6..d777117d 100644 --- a/simulator/controllers/LqrCartPole/application/LqrCartPoleSimulator.hpp +++ b/simulator/controllers/LqrCartPole/application/LqrCartPoleSimulator.hpp @@ -2,7 +2,7 @@ #include "numerical/controllers/implementations/Lqr.hpp" #include "simulator/controllers/LqrCartPole/application/CartPolePlant.hpp" -#include +#include namespace simulator::controllers::lqr { @@ -40,7 +40,7 @@ namespace simulator::controllers::lqr [[nodiscard]] float Step(float externalForce = 0.0f); void SetState(const CartPoleState& state); - [[nodiscard]] float ComputeControlForce() const; + [[nodiscard]] float ComputeControlForce(); [[nodiscard]] const CartPoleState& GetState() const; [[nodiscard]] const CartPoleParameters& GetPlantParameters() const; [[nodiscard]] float GetDt() const; @@ -51,6 +51,6 @@ namespace simulator::controllers::lqr LqrCartPoleConfig configuration; CartPolePlant plant; - std::unique_ptr lqr; + std::optional lqr; }; } diff --git a/simulator/controllers/Mpc/application/MpcSimulator.cpp b/simulator/controllers/Mpc/application/MpcSimulator.cpp index 8dae0fb6..c55a7262 100644 --- a/simulator/controllers/Mpc/application/MpcSimulator.cpp +++ b/simulator/controllers/Mpc/application/MpcSimulator.cpp @@ -4,9 +4,9 @@ namespace simulator::controllers { - void MpcSimulator::Configure(const StateSpacePlant& plant, const Configuration& config) + void MpcSimulator::Configure(const math::LinearTimeInvariant& ltiPlant, const Configuration& config) { - this->plant = plant; + plant = ltiPlant; configuration = config; } @@ -26,15 +26,6 @@ namespace simulator::controllers auto duration = configuration.simulation.duration; auto numSamples = static_cast(duration / dt); - auto A = math::SquareMatrix{ - { plant.A[0][0], plant.A[0][1] }, - { plant.A[1][0], plant.A[1][1] } - }; - auto B = math::Matrix{ - { plant.B[0][0] }, - { plant.B[1][0] } - }; - auto weights = ::controllers::MpcWeights{}; weights.Q = math::SquareMatrix{ { configuration.weights.stateWeight, 0.0f }, @@ -51,7 +42,7 @@ namespace simulator::controllers constraints.uMax = math::Vector{ configuration.constraints.uMax }; } - auto mpc = ::controllers::Mpc(A, B, weights, constraints); + auto mpc = ::controllers::Mpc(plant, weights, constraints); auto ref = math::Vector{ configuration.referencePosition, 0.0f }; mpc.SetReference(ref); @@ -77,7 +68,7 @@ namespace simulator::controllers configuration.weights.controlWeight * u.at(0, 0) * u.at(0, 0); response.cost.push_back(costStep); - state = A * state + B * u; + state = plant.Step(state, u); } return response; diff --git a/simulator/controllers/Mpc/application/MpcSimulator.hpp b/simulator/controllers/Mpc/application/MpcSimulator.hpp index 1df13d24..21d90c7e 100644 --- a/simulator/controllers/Mpc/application/MpcSimulator.hpp +++ b/simulator/controllers/Mpc/application/MpcSimulator.hpp @@ -1,6 +1,6 @@ #pragma once -#include "simulator/controllers/Mpc/application/StateSpacePlant.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include namespace simulator::controllers @@ -43,14 +43,14 @@ namespace simulator::controllers float referencePosition = 1.0f; }; - void Configure(const StateSpacePlant& plant, const Configuration& config); + void Configure(const math::LinearTimeInvariant& plant, const Configuration& config); MpcTimeResponse ComputeStepResponse(); MpcTimeResponse ComputeConstrainedResponse(); private: MpcTimeResponse Simulate(bool enableConstraints); - StateSpacePlant plant; + math::LinearTimeInvariant plant; Configuration configuration; }; } diff --git a/simulator/controllers/Mpc/application/StateSpacePlant.cpp b/simulator/controllers/Mpc/application/StateSpacePlant.cpp index 5a6afbd0..071e2a86 100644 --- a/simulator/controllers/Mpc/application/StateSpacePlant.cpp +++ b/simulator/controllers/Mpc/application/StateSpacePlant.cpp @@ -3,26 +3,28 @@ namespace simulator::controllers { - StateSpacePlant MakeDoubleIntegrator(float dt) + math::LinearTimeInvariant MakeDoubleIntegrator(float dt) { - return StateSpacePlant{ - .A = { { 1.0f, dt }, { 0.0f, 1.0f } }, - .B = { { 0.5f * dt * dt }, { dt } }, - .stateSize = 2, - .inputSize = 1 - }; + return math::LinearTimeInvariant::WithFullStateOutput( + math::SquareMatrix{ + { 1.0f, dt }, + { 0.0f, 1.0f } }, + math::Matrix{ + { 0.5f * dt * dt }, + { dt } }); } - StateSpacePlant MakeFirstOrderWithIntegrator(float gain, float timeConstant, float dt) + math::LinearTimeInvariant MakeFirstOrderWithIntegrator(float gain, float timeConstant, float dt) { auto a = std::exp(-dt / timeConstant); auto b = gain * (1.0f - a); - return StateSpacePlant{ - .A = { { 1.0f, dt }, { 0.0f, a } }, - .B = { { 0.0f }, { b } }, - .stateSize = 2, - .inputSize = 1 - }; + return math::LinearTimeInvariant::WithFullStateOutput( + math::SquareMatrix{ + { 1.0f, dt }, + { 0.0f, a } }, + math::Matrix{ + { 0.0f }, + { b } }); } } diff --git a/simulator/controllers/Mpc/application/StateSpacePlant.hpp b/simulator/controllers/Mpc/application/StateSpacePlant.hpp index a1ff16dc..cb6182b7 100644 --- a/simulator/controllers/Mpc/application/StateSpacePlant.hpp +++ b/simulator/controllers/Mpc/application/StateSpacePlant.hpp @@ -1,17 +1,9 @@ #pragma once -#include +#include "numerical/math/LinearTimeInvariant.hpp" namespace simulator::controllers { - struct StateSpacePlant - { - std::vector> A; - std::vector> B; - std::size_t stateSize; - std::size_t inputSize; - }; - - StateSpacePlant MakeDoubleIntegrator(float dt); - StateSpacePlant MakeFirstOrderWithIntegrator(float gain, float timeConstant, float dt); + math::LinearTimeInvariant MakeDoubleIntegrator(float dt); + math::LinearTimeInvariant MakeFirstOrderWithIntegrator(float gain, float timeConstant, float dt); } diff --git a/simulator/controllers/Mpc/view/MpcConfigurationPanel.cpp b/simulator/controllers/Mpc/view/MpcConfigurationPanel.cpp index 0b6e3fb3..def9cfee 100644 --- a/simulator/controllers/Mpc/view/MpcConfigurationPanel.cpp +++ b/simulator/controllers/Mpc/view/MpcConfigurationPanel.cpp @@ -101,7 +101,7 @@ namespace simulator::controllers::view return config; } - StateSpacePlant MpcConfigurationPanel::CreatePlant() const + math::LinearTimeInvariant MpcConfigurationPanel::CreatePlant() const { float dt = static_cast(sampleTimeSpinBox->value()); diff --git a/simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp b/simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp index a5bf10f5..c1029cfc 100644 --- a/simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp +++ b/simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp @@ -20,7 +20,7 @@ namespace simulator::controllers::view explicit MpcConfigurationPanel(QWidget* parent = nullptr); MpcSimulator::Configuration GetConfiguration() const; - StateSpacePlant CreatePlant() const; + math::LinearTimeInvariant CreatePlant() const; QString GetPlantDescription() const; signals: diff --git a/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.cpp b/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.cpp index 83b0b8b4..74348c92 100644 --- a/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.cpp +++ b/simulator/filters/KalmanFilter/application/KalmanFilterSimulator.cpp @@ -2,6 +2,7 @@ #include "numerical/filters/active/ExtendedKalmanFilter.hpp" #include "numerical/filters/active/KalmanFilter.hpp" #include "numerical/filters/active/UnscentedKalmanFilter.hpp" +#include "numerical/math/LinearTimeInvariant.hpp" #include #include @@ -99,10 +100,14 @@ namespace simulator::filters auto R = MeasCov{ { rVar } }; ::filters::KalmanFilter kf(initialState, initialP); - kf.SetStateTransition(StateMat{ - { 1.0f, dt }, - { -(g / L) * dt, 1.0f - b * dt } }); - kf.SetMeasurementMatrix(math::Matrix{ { 1.0f, 0.0f } }); + { + auto kfPlant = math::LinearTimeInvariant::Autonomous( + StateMat{ + { 1.0f, dt }, + { -(g / L) * dt, 1.0f - b * dt } }, + math::Matrix{ { 1.0f, 0.0f } }); + kf.SetPlant(kfPlant); + } kf.SetProcessNoise(Q); kf.SetMeasurementNoise(R); From a5465d13346808417ec5f5396c3ffd220259dc3a Mon Sep 17 00:00:00 2001 From: gfs Date: Thu, 23 Apr 2026 23:19:32 +0200 Subject: [PATCH 2/4] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/controllers/LinearTimeInvariant.md | 10 +++++----- doc/controllers/Lqg.md | 20 ++++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/doc/controllers/LinearTimeInvariant.md b/doc/controllers/LinearTimeInvariant.md index e1a6cd9d..d6729727 100644 --- a/doc/controllers/LinearTimeInvariant.md +++ b/doc/controllers/LinearTimeInvariant.md @@ -49,11 +49,11 @@ Controllability and observability are prerequisites for LQR and Kalman Filter st ## 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 | +| 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 diff --git a/doc/controllers/Lqg.md b/doc/controllers/Lqg.md index f3f7b07d..ef1305f0 100644 --- a/doc/controllers/Lqg.md +++ b/doc/controllers/Lqg.md @@ -77,10 +77,10 @@ At each time step $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 | +| 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. @@ -112,12 +112,12 @@ $$A = \begin{bmatrix} 1 & 0.1 \\ 0 & 1 \end{bmatrix}, \quad B = \begin{bmatrix} **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 | +| 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. From cc22e0f5fe2af28f78fa67946643459a8182aad3 Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Thu, 23 Apr 2026 21:32:10 +0000 Subject: [PATCH 3/4] process review comments --- doc/controllers/LinearTimeInvariant.md | 2 +- doc/controllers/Lqg.md | 2 +- numerical/controllers/implementations/Mpc.hpp | 63 ++++++++--------- numerical/filters/active/KalmanSmoother.hpp | 5 +- .../filters/active/UnscentedKalmanFilter.hpp | 31 +++------ numerical/math/LinearTimeInvariant.hpp | 3 +- numerical/math/Matrix.hpp | 49 +++++++++++++ numerical/math/test/TestMatrix.cpp | 68 +++++++++++++++++++ 8 files changed, 158 insertions(+), 65 deletions(-) diff --git a/doc/controllers/LinearTimeInvariant.md b/doc/controllers/LinearTimeInvariant.md index e1a6cd9d..3c2dd9d1 100644 --- a/doc/controllers/LinearTimeInvariant.md +++ b/doc/controllers/LinearTimeInvariant.md @@ -62,7 +62,7 @@ Controllability and observability are prerequisites for LQR and Kalman Filter st - **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 and Limitations +## 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. diff --git a/doc/controllers/Lqg.md b/doc/controllers/Lqg.md index f3f7b07d..0dc4f640 100644 --- a/doc/controllers/Lqg.md +++ b/doc/controllers/Lqg.md @@ -92,7 +92,7 @@ where $n$ = state size, $m$ = input size, $p$ = measurement size. - **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 and Limitations +## 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. diff --git a/numerical/controllers/implementations/Mpc.hpp b/numerical/controllers/implementations/Mpc.hpp index e6d7d94a..5bbab7c7 100644 --- a/numerical/controllers/implementations/Mpc.hpp +++ b/numerical/controllers/implementations/Mpc.hpp @@ -28,19 +28,6 @@ namespace controllers std::optional> uMax; }; - namespace detail - { - template - ALWAYS_INLINE_HOT void SetBlock(math::Matrix& dest, - const math::Matrix& src, - std::size_t rowOffset, std::size_t colOffset) - { - for (std::size_t r = 0; r < SrcRows; ++r) - for (std::size_t c = 0; c < SrcCols; ++c) - dest.at(rowOffset + r, colOffset + c) = src.at(r, c); - } - } - template class Mpc : public StateFeedbackController @@ -143,7 +130,7 @@ namespace controllers for (std::size_t k = 0; k < PredictionHorizon; ++k) { Apow = Apow * A; - detail::SetBlock(psi, Apow, k * StateSize, 0); + psi.SetBlock(Apow, k * StateSize, 0); } return psi; @@ -153,18 +140,19 @@ namespace controllers OPTIMIZE_FOR_SPEED auto Mpc::BuildTheta( const StateMatrix& A, const InputMatrix& B) const -> PredictionInputMatrix { + std::array aPowers; + aPowers[0] = StateMatrix::Identity(); + for (std::size_t p = 1; p <= PredictionHorizon; ++p) + aPowers[p] = aPowers[p - 1] * A; + PredictionInputMatrix theta; for (std::size_t k = 0; k < PredictionHorizon; ++k) { for (std::size_t j = 0; j < ControlHorizon && j <= k; ++j) { - auto ApowLocal = StateMatrix::Identity(); - for (std::size_t p = 0; p < k - j; ++p) - ApowLocal = ApowLocal * A; - - auto block = ApowLocal * B; - detail::SetBlock(theta, block, k * StateSize, j * InputSize); + auto block = aPowers[k - j] * B; + theta.SetBlock(block, k * StateSize, j * InputSize); } } @@ -186,12 +174,12 @@ namespace controllers ? *weights.terminalP : weights.Q; - detail::SetBlock(qBar, Qk, k * StateSize, k * StateSize); + qBar.SetBlock(Qk, k * StateSize, k * StateSize); } AugmentedInputWeight rBar; for (std::size_t k = 0; k < ControlHorizon; ++k) - detail::SetBlock(rBar, weights.R, k * InputSize, k * InputSize); + rBar.SetBlock(weights.R, k * InputSize, k * InputSize); auto thetaT = theta.Transpose(); hessian = thetaT * qBar * theta + rBar; @@ -204,15 +192,26 @@ namespace controllers if (!constraints.uMin && !constraints.uMax) return; - for (std::size_t k = 0; k < ControlHorizon; ++k) + if (constraints.uMin && constraints.uMax) { - for (std::size_t i = 0; i < InputSize; ++i) - { - if (constraints.uMin) + for (std::size_t k = 0; k < ControlHorizon; ++k) + for (std::size_t i = 0; i < InputSize; ++i) + { + auto& val = u.at(k * InputSize + i, 0); + val = std::max(std::min(val, constraints.uMax->at(i, 0)), constraints.uMin->at(i, 0)); + } + } + else if (constraints.uMin) + { + for (std::size_t k = 0; k < ControlHorizon; ++k) + for (std::size_t i = 0; i < InputSize; ++i) u.at(k * InputSize + i, 0) = std::max(u.at(k * InputSize + i, 0), constraints.uMin->at(i, 0)); - if (constraints.uMax) + } + else + { + for (std::size_t k = 0; k < ControlHorizon; ++k) + for (std::size_t i = 0; i < InputSize; ++i) u.at(k * InputSize + i, 0) = std::min(u.at(k * InputSize + i, 0), constraints.uMax->at(i, 0)); - } } } @@ -223,17 +222,13 @@ namespace controllers { auto effectiveState = reference ? state - *reference : state; auto g = gradientMatrix * effectiveState; - - ControlVector negG; - for (std::size_t i = 0; i < TotalControlDim; ++i) - negG.at(i, 0) = T(-1.0f) * g.at(i, 0); + auto negG = g * T(-1.0f); auto uOptimal = solvers::SolveSystem(hessian, negG); ApplyConstraints(uOptimal); for (std::size_t k = 0; k < ControlHorizon; ++k) - for (std::size_t i = 0; i < InputSize; ++i) - controlSequence[k].at(i, 0) = uOptimal.at(k * InputSize + i, 0); + controlSequence[k] = uOptimal.template GetBlock(k * InputSize, 0); return controlSequence[0]; } diff --git a/numerical/filters/active/KalmanSmoother.hpp b/numerical/filters/active/KalmanSmoother.hpp index e11a3680..9ad4a48c 100644 --- a/numerical/filters/active/KalmanSmoother.hpp +++ b/numerical/filters/active/KalmanSmoother.hpp @@ -222,13 +222,10 @@ namespace filters const auto L = solvers::CholeskyDecomposition(innovationCovariance); const auto sInvNu = solvers::SolveSystem(innovationCovariance, innovation); float logDetS = 0.0f; - float quadForm = 0.0f; for (std::size_t i = 0; i < MeasurementSize; ++i) - { logDetS += std::log(L.at(i, i)); - quadForm += innovation.at(i, 0) * sInvNu.at(i, 0); - } logDetS *= 2.0f; + const float quadForm = (innovation.Transpose() * sInvNu).at(0, 0); return -0.5f * (logDetS + quadForm + static_cast(MeasurementSize) * log2pi); } diff --git a/numerical/filters/active/UnscentedKalmanFilter.hpp b/numerical/filters/active/UnscentedKalmanFilter.hpp index 9c45e9d4..39c0cdb3 100644 --- a/numerical/filters/active/UnscentedKalmanFilter.hpp +++ b/numerical/filters/active/UnscentedKalmanFilter.hpp @@ -4,6 +4,7 @@ #include "numerical/filters/active/KalmanFilterBase.hpp" #include "numerical/math/CompilerOptimizations.hpp" #include "numerical/solvers/CholeskyDecomposition.hpp" +#include #include #include @@ -128,11 +129,9 @@ namespace filters weightsMean[0] = lambda / (n + lambda); weightsCovariance[0] = lambda / (n + lambda) + (1.0f - parameters.alpha * parameters.alpha + parameters.beta); - for (std::size_t i = 1; i < SigmaPointCount; ++i) - { - weightsMean[i] = 1.0f / (2.0f * (n + lambda)); - weightsCovariance[i] = 1.0f / (2.0f * (n + lambda)); - } + const float wRest = 1.0f / (2.0f * (n + lambda)); + std::fill(weightsMean.begin() + 1, weightsMean.end(), wRest); + std::fill(weightsCovariance.begin() + 1, weightsCovariance.end(), wRest); } template @@ -148,10 +147,7 @@ namespace filters // σᵢ = x̂ ± √(n+λ) · column_i(L) for (std::size_t i = 0; i < StateSize; ++i) { - StateVector column; - for (std::size_t j = 0; j < StateSize; ++j) - column.at(j, 0) = QNumberType(math::ToFloat(L.at(j, i)) * scaleFactor); - + auto column = L.GetColumn(i) * QNumberType(scaleFactor); sigmaPoints[i + 1] = this->state() + column; sigmaPoints[i + 1 + StateSize] = this->state() - column; } @@ -165,10 +161,7 @@ namespace filters { math::Vector result; for (std::size_t i = 0; i < SigmaPointCount; ++i) - for (std::size_t j = 0; j < VectorSize; ++j) - result.at(j, 0) = QNumberType( - math::ToFloat(result.at(j, 0)) + - weightsMean[i] * math::ToFloat(points[i].at(j, 0))); + result = result + points[i] * QNumberType(weightsMean[i]); return result; } @@ -184,11 +177,7 @@ namespace filters { auto diff = points[i] - mean; auto outer = diff * diff.Transpose(); - for (std::size_t r = 0; r < Size; ++r) - for (std::size_t c = 0; c < Size; ++c) - result.at(r, c) = QNumberType( - math::ToFloat(result.at(r, c)) + - weightsCovariance[i] * math::ToFloat(outer.at(r, c))); + result = result + outer * QNumberType(weightsCovariance[i]); } return result; } @@ -207,11 +196,7 @@ namespace filters auto stateDiff = statePoints[i] - stateMean; auto measDiff = measurementPoints[i] - measurementMean; auto outer = stateDiff * measDiff.Transpose(); - for (std::size_t r = 0; r < StateSize; ++r) - for (std::size_t c = 0; c < MeasurementSize; ++c) - result.at(r, c) = QNumberType( - math::ToFloat(result.at(r, c)) + - weightsCovariance[i] * math::ToFloat(outer.at(r, c))); + result = result + outer * QNumberType(weightsCovariance[i]); } return result; } diff --git a/numerical/math/LinearTimeInvariant.hpp b/numerical/math/LinearTimeInvariant.hpp index cfc1f7c8..b87cf573 100644 --- a/numerical/math/LinearTimeInvariant.hpp +++ b/numerical/math/LinearTimeInvariant.hpp @@ -59,9 +59,8 @@ namespace math // Factory: C = I (OutputSize must equal StateSize), D = 0 static LinearTimeInvariant WithFullStateOutput( const StateMatrix& stateTransition, const InputMatrix& inputMatrix) + requires(OutputSize == StateSize) { - static_assert(OutputSize == StateSize, - "WithFullStateOutput requires OutputSize == StateSize"); LinearTimeInvariant lti; lti.A = stateTransition; lti.B = inputMatrix; diff --git a/numerical/math/Matrix.hpp b/numerical/math/Matrix.hpp index 17380301..d29d6f5e 100644 --- a/numerical/math/Matrix.hpp +++ b/numerical/math/Matrix.hpp @@ -113,6 +113,16 @@ namespace math [[nodiscard]] static constexpr Matrix Identity(); [[nodiscard]] constexpr T Trace() const; + template + ALWAYS_INLINE_HOT constexpr void SetBlock(const Matrix& src, + size_type rowOffset, size_type colOffset); + + template + [[nodiscard]] ALWAYS_INLINE_HOT constexpr Matrix GetBlock( + size_type rowOffset, size_type colOffset) const; + + [[nodiscard]] ALWAYS_INLINE_HOT constexpr Matrix GetColumn(size_type col) const; + private: std::array data; }; @@ -294,6 +304,45 @@ namespace math return sum; } + // Implementation of new block methods // + + template + template + ALWAYS_INLINE_HOT constexpr void + Matrix::SetBlock(const Matrix& src, + size_type rowOffset, size_type colOffset) + { + static_assert(SrcRows <= Rows && SrcCols <= Cols, + "Source block exceeds destination matrix dimensions"); + for (size_type r = 0; r < SrcRows; ++r) + for (size_type c = 0; c < SrcCols; ++c) + at(rowOffset + r, colOffset + c) = src.at(r, c); + } + + template + template + [[nodiscard]] ALWAYS_INLINE_HOT constexpr Matrix + Matrix::GetBlock(size_type rowOffset, size_type colOffset) const + { + static_assert(BlockRows <= Rows && BlockCols <= Cols, + "Requested block exceeds source matrix dimensions"); + Matrix result; + for (size_type r = 0; r < BlockRows; ++r) + for (size_type c = 0; c < BlockCols; ++c) + result.at(r, c) = at(rowOffset + r, colOffset + c); + return result; + } + + template + [[nodiscard]] ALWAYS_INLINE_HOT constexpr Matrix + Matrix::GetColumn(size_type col) const + { + Vector result; + for (size_type r = 0; r < Rows; ++r) + result.at(r, 0) = at(r, col); + return result; + } + #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD extern template class Matrix; extern template class Matrix; diff --git a/numerical/math/test/TestMatrix.cpp b/numerical/math/test/TestMatrix.cpp index 2286a35f..b8f612d6 100644 --- a/numerical/math/test/TestMatrix.cpp +++ b/numerical/math/test/TestMatrix.cpp @@ -184,3 +184,71 @@ TYPED_TEST(MatrixTest, MultiplicationRangeCheck) } } } + +namespace +{ + class MatrixBlockTest : public ::testing::Test + { + protected: + math::Matrix dest{}; + math::Matrix src{ + { 0.1f, 0.2f }, + { 0.3f, 0.4f } + }; + }; +} + +TEST_F(MatrixBlockTest, SetBlock_writes_correct_elements) +{ + dest.SetBlock(src, 1, 1); + + EXPECT_FLOAT_EQ(dest.at(1, 1), 0.1f); + EXPECT_FLOAT_EQ(dest.at(1, 2), 0.2f); + EXPECT_FLOAT_EQ(dest.at(2, 1), 0.3f); + EXPECT_FLOAT_EQ(dest.at(2, 2), 0.4f); + EXPECT_FLOAT_EQ(dest.at(0, 0), 0.0f); + EXPECT_FLOAT_EQ(dest.at(3, 3), 0.0f); +} + +TEST_F(MatrixBlockTest, GetBlock_reads_correct_elements) +{ + math::Matrix m{ + { 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.1f, 0.2f, 0.0f }, + { 0.0f, 0.3f, 0.4f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f } + }; + + auto block = m.GetBlock<2, 2>(1, 1); + + EXPECT_FLOAT_EQ(block.at(0, 0), 0.1f); + EXPECT_FLOAT_EQ(block.at(0, 1), 0.2f); + EXPECT_FLOAT_EQ(block.at(1, 0), 0.3f); + EXPECT_FLOAT_EQ(block.at(1, 1), 0.4f); +} + +TEST_F(MatrixBlockTest, GetColumn_reads_correct_column) +{ + math::Matrix m{ + { 0.1f, 0.2f, 0.3f }, + { 0.4f, 0.5f, 0.6f }, + { 0.7f, 0.8f, 0.9f } + }; + + auto col = m.GetColumn(1); + + EXPECT_FLOAT_EQ(col.at(0, 0), 0.2f); + EXPECT_FLOAT_EQ(col.at(1, 0), 0.5f); + EXPECT_FLOAT_EQ(col.at(2, 0), 0.8f); +} + +TEST_F(MatrixBlockTest, SetBlock_then_GetBlock_roundtrip) +{ + dest.SetBlock(src, 2, 2); + auto result = dest.GetBlock<2, 2>(2, 2); + + EXPECT_FLOAT_EQ(result.at(0, 0), src.at(0, 0)); + EXPECT_FLOAT_EQ(result.at(0, 1), src.at(0, 1)); + EXPECT_FLOAT_EQ(result.at(1, 0), src.at(1, 0)); + EXPECT_FLOAT_EQ(result.at(1, 1), src.at(1, 1)); +} From dd8e74b034feb880ec278e889956e5ec6cc8cffb Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Thu, 23 Apr 2026 21:51:56 +0000 Subject: [PATCH 4/4] process review comments --- .../implementations/test/TestLqg.cpp | 1 + .../implementations/test/TestMpc.cpp | 64 ++++++++++++ numerical/filters/active/KalmanFilter.hpp | 6 +- numerical/filters/active/KalmanSmoother.hpp | 8 +- .../filters/active/test/TestKalmanFilter.cpp | 34 +++++++ numerical/math/LinearTimeInvariant.hpp | 3 +- numerical/math/Matrix.hpp | 12 +-- .../math/test/TestLinearTimeInvariant.cpp | 98 +++++++++++++++++++ numerical/math/test/TestMatrix.cpp | 3 + 9 files changed, 217 insertions(+), 12 deletions(-) diff --git a/numerical/controllers/implementations/test/TestLqg.cpp b/numerical/controllers/implementations/test/TestLqg.cpp index ceba7382..43d7ea73 100644 --- a/numerical/controllers/implementations/test/TestLqg.cpp +++ b/numerical/controllers/implementations/test/TestLqg.cpp @@ -3,6 +3,7 @@ #endif #include "numerical/controllers/implementations/Lqg.hpp" +#include #include namespace diff --git a/numerical/controllers/implementations/test/TestMpc.cpp b/numerical/controllers/implementations/test/TestMpc.cpp index bf2f06b9..fd5845c2 100644 --- a/numerical/controllers/implementations/test/TestMpc.cpp +++ b/numerical/controllers/implementations/test/TestMpc.cpp @@ -756,3 +756,67 @@ TEST_F(TestMpc, mpc_from_lti_matches_mpc_from_matrices) EXPECT_NEAR(uMatrices.at(0, 0), uLti.at(0, 0), 1e-4f); } + +TEST_F(TestMpc, umin_only_constraint_clamps_lower_bound) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.005f }, + { 0.1f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ { 100.0f, 0.0f }, { 0.0f, 100.0f } }; + weights.R = math::SquareMatrix{ { 0.01f } }; + + controllers::MpcConstraints constraints; + constraints.uMin = math::Vector{ -0.3f }; + // uMax intentionally not set + + controllers::Mpc mpc(A, B, weights, constraints); + + // Negative state drives control negative; clamp should enforce lower bound + math::Vector state{ -10.0f, 0.0f }; + auto u = mpc.ComputeControl(state); + + EXPECT_GE(u.at(0, 0), -0.3f); + + auto seq = mpc.GetControlSequence(); + for (std::size_t k = 0; k < seq.size(); ++k) + EXPECT_GE(seq[k].at(0, 0), -0.3f); +} + +TEST_F(TestMpc, umax_only_constraint_clamps_upper_bound) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.005f }, + { 0.1f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ { 100.0f, 0.0f }, { 0.0f, 100.0f } }; + weights.R = math::SquareMatrix{ { 0.01f } }; + + controllers::MpcConstraints constraints; + constraints.uMax = math::Vector{ 0.3f }; + // uMin intentionally not set + + controllers::Mpc mpc(A, B, weights, constraints); + + // Positive state drives control positive; clamp should enforce upper bound + math::Vector state{ 10.0f, 0.0f }; + auto u = mpc.ComputeControl(state); + + EXPECT_LE(u.at(0, 0), 0.3f); + + auto seq = mpc.GetControlSequence(); + for (std::size_t k = 0; k < seq.size(); ++k) + EXPECT_LE(seq[k].at(0, 0), 0.3f); +} diff --git a/numerical/filters/active/KalmanFilter.hpp b/numerical/filters/active/KalmanFilter.hpp index 5979fd2f..48ad312f 100644 --- a/numerical/filters/active/KalmanFilter.hpp +++ b/numerical/filters/active/KalmanFilter.hpp @@ -40,7 +40,8 @@ namespace filters void SetPlant(const math::LinearTimeInvariant& plant) requires(ControlSize > 0); - void SetPlant(const math::LinearTimeInvariant& plant) + template + void SetPlant(const math::LinearTimeInvariant& plant) requires(ControlSize == 0); void Predict(); @@ -94,8 +95,9 @@ namespace filters } template + template void KalmanFilter::SetPlant( - const math::LinearTimeInvariant& plant) + const math::LinearTimeInvariant& plant) requires(ControlSize == 0) { SetStateTransition(plant.A); diff --git a/numerical/filters/active/KalmanSmoother.hpp b/numerical/filters/active/KalmanSmoother.hpp index 9ad4a48c..85ec3a13 100644 --- a/numerical/filters/active/KalmanSmoother.hpp +++ b/numerical/filters/active/KalmanSmoother.hpp @@ -53,9 +53,10 @@ namespace filters const StateMatrix& initialCovariance); // Convenience overload: extracts F = plant.A, H = plant.C from the LTI model. - // LTI template args: (InputSize unused for smoother) + // InputSize is not used; any plant input dimension is accepted. + template OPTIMIZE_FOR_SPEED SmootherOutput Smooth( - const math::LinearTimeInvariant& plant, + const math::LinearTimeInvariant& plant, const StateMatrix& Q, const MeasurementCovariance& R, const std::array& observations, @@ -243,10 +244,11 @@ namespace filters } template + template OPTIMIZE_FOR_SPEED typename KalmanSmoother::SmootherOutput KalmanSmoother::Smooth( - const math::LinearTimeInvariant& plant, + const math::LinearTimeInvariant& plant, const StateMatrix& Q, const MeasurementCovariance& R, const std::array& observations, diff --git a/numerical/filters/active/test/TestKalmanFilter.cpp b/numerical/filters/active/test/TestKalmanFilter.cpp index 38e301a1..30df6e72 100644 --- a/numerical/filters/active/test/TestKalmanFilter.cpp +++ b/numerical/filters/active/test/TestKalmanFilter.cpp @@ -492,3 +492,37 @@ TEST_F(KalmanFilterWithControlTest, set_plant_equivalent_to_individual_setters) EXPECT_NEAR(math::ToFloat(filterA.GetState().at(0, 0)), math::ToFloat(filterB.GetState().at(0, 0)), 1e-5f); EXPECT_NEAR(math::ToFloat(filterA.GetState().at(1, 0)), math::ToFloat(filterB.GetState().at(1, 0)), 1e-5f); } + +TEST_F(KalmanFilterWithControlTest, set_plant_with_control_size_zero_accepts_any_input_dimension) +{ + // ControlSize == 0 but plant has InputSize == 2 — only A and C should be extracted + math::SquareMatrix F{ + { 0.9f, 0.1f }, + { 0.0f, 0.8f } + }; + math::Matrix H{ + { 1.0f, 0.0f } + }; + + math::Vector initialState{}; + math::SquareMatrix initialCov{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + + filters::KalmanFilter filter{ initialState, initialCov }; + + math::LinearTimeInvariant plant; + plant.A = F; + plant.C = H; + + filter.SetPlant(plant); + filter.SetProcessNoise(math::SquareMatrix{ { 0.01f, 0.0f }, { 0.0f, 0.01f } }); + filter.SetMeasurementNoise(math::SquareMatrix{ { 0.1f } }); + + filter.Predict(); + filter.Update(math::Vector{ { 1.0f } }); + + // State should have moved from zero toward the measurement + EXPECT_NE(math::ToFloat(filter.GetState().at(0, 0)), 0.0f); +} diff --git a/numerical/math/LinearTimeInvariant.hpp b/numerical/math/LinearTimeInvariant.hpp index b87cf573..84ec75e9 100644 --- a/numerical/math/LinearTimeInvariant.hpp +++ b/numerical/math/LinearTimeInvariant.hpp @@ -15,7 +15,8 @@ namespace math // y_k = C x_k + D u_k // // Template args: - // Default OutputSize = StateSize (full-state output, C = I, D = 0). + // OutputSize defaults to StateSize. All matrices are zero-initialised by default; + // use the WithFullStateOutput factory to get C = I. template - ALWAYS_INLINE_HOT constexpr void SetBlock(const Matrix& src, + constexpr void SetBlock(const Matrix& src, size_type rowOffset, size_type colOffset); template - [[nodiscard]] ALWAYS_INLINE_HOT constexpr Matrix GetBlock( + [[nodiscard]] constexpr Matrix GetBlock( size_type rowOffset, size_type colOffset) const; - [[nodiscard]] ALWAYS_INLINE_HOT constexpr Matrix GetColumn(size_type col) const; + [[nodiscard]] constexpr Matrix GetColumn(size_type col) const; private: std::array data; @@ -308,7 +308,7 @@ namespace math template template - ALWAYS_INLINE_HOT constexpr void + constexpr void Matrix::SetBlock(const Matrix& src, size_type rowOffset, size_type colOffset) { @@ -321,7 +321,7 @@ namespace math template template - [[nodiscard]] ALWAYS_INLINE_HOT constexpr Matrix + [[nodiscard]] constexpr Matrix Matrix::GetBlock(size_type rowOffset, size_type colOffset) const { static_assert(BlockRows <= Rows && BlockCols <= Cols, @@ -334,7 +334,7 @@ namespace math } template - [[nodiscard]] ALWAYS_INLINE_HOT constexpr Matrix + [[nodiscard]] constexpr Matrix Matrix::GetColumn(size_type col) const { Vector result; diff --git a/numerical/math/test/TestLinearTimeInvariant.cpp b/numerical/math/test/TestLinearTimeInvariant.cpp index 81d202a7..3dacd0fd 100644 --- a/numerical/math/test/TestLinearTimeInvariant.cpp +++ b/numerical/math/test/TestLinearTimeInvariant.cpp @@ -141,3 +141,101 @@ TYPED_TEST(TestLinearTimeInvariant, step_called_twice_propagates_state_correctly EXPECT_NEAR(this->ToF(x.at(0, 0)), 0.005f, 5e-3f); EXPECT_NEAR(this->ToF(x.at(1, 0)), 0.095f, 5e-3f); } + +namespace +{ + class TestLinearTimeInvariantFloat : public ::testing::Test + {}; +} + +TEST_F(TestLinearTimeInvariantFloat, three_state_system_step_and_output) +{ + auto A = math::SquareMatrix{ + { 0.9f, 0.1f, 0.0f }, + { 0.0f, 0.8f, 0.1f }, + { 0.0f, 0.0f, 0.7f } + }; + auto B = math::Matrix{ { 0.0f }, { 0.0f }, { 0.1f } }; + + auto lti = math::LinearTimeInvariant::WithFullStateOutput(A, B); + + math::Vector x{ { 1.0f }, { 0.5f }, { 0.25f } }; + math::Vector u{ { 2.0f } }; + + auto xNext = lti.Step(x, u); + EXPECT_NEAR(xNext.at(0, 0), 0.9f * 1.0f + 0.1f * 0.5f, 1e-5f); + EXPECT_NEAR(xNext.at(1, 0), 0.8f * 0.5f + 0.1f * 0.25f, 1e-5f); + EXPECT_NEAR(xNext.at(2, 0), 0.7f * 0.25f + 0.1f * 2.0f, 1e-5f); + + // C = I, D = 0, so Output(x, u) == x + auto y = lti.Output(x, u); + EXPECT_NEAR(y.at(0, 0), x.at(0, 0), 5e-3f); + EXPECT_NEAR(y.at(1, 0), x.at(1, 0), 5e-3f); + EXPECT_NEAR(y.at(2, 0), x.at(2, 0), 5e-3f); +} + +TEST_F(TestLinearTimeInvariantFloat, four_state_system_step) +{ + auto lti = math::LinearTimeInvariant::WithFullStateOutput( + math::SquareMatrix{ + { 0.9f, 0.1f, 0.0f, 0.0f }, + { 0.0f, 0.8f, 0.1f, 0.0f }, + { 0.0f, 0.0f, 0.7f, 0.1f }, + { 0.0f, 0.0f, 0.0f, 0.6f } }, + math::Matrix{ { 0.0f }, { 0.0f }, { 0.0f }, { 0.1f } }); + + math::Vector x{ { 1.0f }, { 0.0f }, { 0.0f }, { 0.0f } }; + math::Vector u{ { 1.0f } }; + + auto xNext = lti.Step(x, u); + EXPECT_NEAR(xNext.at(0, 0), 0.9f, 1e-5f); + EXPECT_NEAR(xNext.at(3, 0), 0.1f, 1e-5f); +} + +TEST_F(TestLinearTimeInvariantFloat, four_state_single_output_autonomous) +{ + auto A = math::SquareMatrix{ + { 0.9f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.8f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.7f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.6f } + }; + auto C = math::Matrix{ { 1.0f, 0.0f, 0.0f, 0.0f } }; + + auto lti = math::LinearTimeInvariant::Autonomous(A, C); + + for (std::size_t r = 0; r < 4; ++r) + EXPECT_NEAR(lti.B.at(r, 0), 0.0f, 1e-5f); + + math::Vector x{ { 1.0f }, { 0.5f }, { 0.25f }, { 0.1f } }; + math::Vector u{}; + auto xNext = lti.Step(x, u); + EXPECT_NEAR(xNext.at(0, 0), 0.9f, 1e-5f); +} + +TEST_F(TestLinearTimeInvariantFloat, two_state_two_input_with_full_state_output) +{ + auto A = math::SquareMatrix{ + { 0.9f, 0.0f }, + { 0.0f, 0.8f } + }; + auto B = math::Matrix{ + { 0.1f, 0.0f }, + { 0.0f, 0.1f } + }; + + auto lti = math::LinearTimeInvariant::WithFullStateOutput(A, B); + + // C must be identity + EXPECT_NEAR(lti.C.at(0, 0), 1.0f, 5e-3f); + EXPECT_NEAR(lti.C.at(1, 1), 1.0f, 5e-3f); + EXPECT_NEAR(lti.C.at(0, 1), 0.0f, 5e-3f); + EXPECT_NEAR(lti.C.at(1, 0), 0.0f, 5e-3f); + + math::Vector x{ { 1.0f }, { 0.5f } }; + math::Vector u{ { 1.0f }, { 2.0f } }; + + auto xNext = lti.Step(x, u); + EXPECT_NEAR(xNext.at(0, 0), 0.9f + 0.1f, 1e-5f); + EXPECT_NEAR(xNext.at(1, 0), 0.4f + 0.2f, 1e-5f); +} diff --git a/numerical/math/test/TestMatrix.cpp b/numerical/math/test/TestMatrix.cpp index b8f612d6..4972559e 100644 --- a/numerical/math/test/TestMatrix.cpp +++ b/numerical/math/test/TestMatrix.cpp @@ -1,5 +1,8 @@ #include "numerical/math/Matrix.hpp" +#include +#include #include +#include namespace {