diff --git a/.vscode/launch.json b/.vscode/launch.json index e3823be1..7222c113 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -101,6 +101,26 @@ } ] }, + { + "name": "MPC Controller Simulator", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/build/host/simulator/controllers/Mpc/Debug/numerical.simulator.controllers.mpc", + "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/Mpc.md b/doc/controllers/Mpc.md new file mode 100644 index 00000000..aa799a3c --- /dev/null +++ b/doc/controllers/Mpc.md @@ -0,0 +1,165 @@ +# Model Predictive Controller (MPC) + +## Overview & Motivation + +Model Predictive Control (MPC) is a receding-horizon optimal control strategy that computes control inputs by solving a finite-horizon optimization problem at each time step. Unlike LQR, which applies a fixed gain computed offline, MPC re-solves the optimization online, enabling it to handle constraints on control inputs directly. + +At each sample instant, MPC predicts the future system trajectory over a prediction horizon $N_p$, optimizes a sequence of control moves over a control horizon $N_c \leq N_p$, applies only the first control move, and repeats at the next step. This receding-horizon approach provides feedback and robustness to disturbances. + +**Key advantages over LQR:** +- Explicit handling of input constraints (actuator limits) +- Preview and anticipation of future reference changes +- Tunable trade-off between horizon length and computational cost + +**When to use MPC:** +- Systems with actuator saturation or operational limits +- Multi-input multi-output (MIMO) systems requiring coordinated control +- Applications where the computational budget allows online optimization (typically $N_c \cdot m \leq 20$) + +## Mathematical Theory + +### Prerequisites + +- Discrete-time linear state-space model: $x_{k+1} = Ax_k + Bu_k$ +- Quadratic cost weighting matrices $Q \succeq 0$ (state), $R \succ 0$ (control) +- Optional terminal cost matrix $P \succeq 0$ (typically from DARE) + +### Core Definitions + +**Cost function** over prediction horizon $N_p$ with control horizon $N_c$: + +$$J = \sum_{k=0}^{N_p-1} x_k^T Q\, x_k + \sum_{k=0}^{N_c-1} u_k^T R\, u_k + x_{N_p}^T P\, x_{N_p}$$ + +For $k \geq N_c$, the control input is held at $u_{N_c-1}$ or zero (our implementation sets it to zero beyond $N_c$). + +### Prediction Matrices + +The future state trajectory can be expressed as: + +$$\mathbf{X} = \Psi\, x_0 + \Theta\, \mathbf{U}$$ + +where $\mathbf{X} = [x_1^T, x_2^T, \ldots, x_{N_p}^T]^T$ and $\mathbf{U} = [u_0^T, u_1^T, \ldots, u_{N_c-1}^T]^T$. + +**State propagation matrix** $\Psi$ ($N_p n \times n$): + +$$\Psi = \begin{bmatrix} A \\ A^2 \\ \vdots \\ A^{N_p} \end{bmatrix}$$ + +**Control-to-state matrix** $\Theta$ ($N_p n \times N_c m$): + +$$\Theta = \begin{bmatrix} B & 0 & \cdots & 0 \\ AB & B & \cdots & 0 \\ A^2B & AB & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ A^{N_p-1}B & A^{N_p-2}B & \cdots & A^{N_p-N_c}B \end{bmatrix}$$ + +### QP Formulation + +Substituting predictions into the cost yields a quadratic program in $\mathbf{U}$: + +$$J = \mathbf{U}^T H\, \mathbf{U} + 2\, x_0^T F^T \mathbf{U} + \text{const}$$ + +where: + +$$H = \Theta^T \bar{Q}\, \Theta + \bar{R}$$ +$$F = \Theta^T \bar{Q}\, \Psi$$ + +$\bar{Q}$ is block-diagonal with $Q$ on the first $N_p - 1$ blocks and $P$ on the last block. $\bar{R}$ is block-diagonal with $R$ repeated $N_c$ times. + +### Unconstrained Solution + +Setting $\nabla_{\mathbf{U}} J = 0$: + +$$\mathbf{U}^* = -H^{-1} F\, x_0$$ + +Solved via Gaussian elimination ($H\, \mathbf{U}^* = -F\, x_0$) rather than explicit matrix inversion. + +### Box Constraints + +For control input constraints $u_{\min} \leq u_k \leq u_{\max}$, a simple projected approach clamps each element of the unconstrained solution. This is a first-order approximation; for tight constraints or state constraints, a full QP solver would be required. + +## Complexity Analysis + +| Phase | Time | Space | Notes | +|----------|----------------------|------------------------------------|----------------------------------------------------| +| Offline | $O(N_p^2 \cdot n^3)$ | $O((N_c m)^2 + N_p n \cdot N_c m)$ | Prediction matrices, Hessian, gradient precomputed | +| Online | $O((N_c m)^3)$ | $O((N_c m)^2)$ | Gaussian elimination to solve $H\mathbf{U}=-Fx$ | +| Per step | $O(N_c m \cdot n)$ | $O(N_c m)$ | Matrix-vector product $Fx$ + constraint clamping | + +For typical embedded use ($n=2, m=1, N_c=10$): the online solve is a $10 \times 10$ linear system, well within real-time budgets. + +## Step-by-Step Walkthrough + +**System:** Double integrator with $dt = 0.1$ s + +$$A = \begin{bmatrix} 1 & 0.1 \\ 0 & 1 \end{bmatrix}, \quad B = \begin{bmatrix} 0.005 \\ 0.1 \end{bmatrix}$$ + +$$Q = \begin{bmatrix} 10 & 0 \\ 0 & 1 \end{bmatrix}, \quad R = [0.1], \quad N_p = N_c = 3$$ + +**Step 1 — Build $\Psi$:** + +$$\Psi = \begin{bmatrix} A \\ A^2 \\ A^3 \end{bmatrix} = \begin{bmatrix} 1 & 0.1 \\ 0 & 1 \\ 1 & 0.2 \\ 0 & 1 \\ 1 & 0.3 \\ 0 & 1 \end{bmatrix}$$ + +**Step 2 — Build $\Theta$:** + +$$\Theta = \begin{bmatrix} 0.005 & 0 & 0 \\ 0.1 & 0 & 0 \\ 0.015 & 0.005 & 0 \\ 0.2 & 0.1 & 0 \\ 0.03 & 0.015 & 0.005 \\ 0.3 & 0.2 & 0.1 \end{bmatrix}$$ + +**Step 3 — Compute $H$ and $F$:** + +$H = \Theta^T \bar{Q} \Theta + \bar{R}$ produces a $3 \times 3$ positive definite matrix. + +$F = \Theta^T \bar{Q} \Psi$ produces a $3 \times 2$ matrix. + +**Step 4 — Online solve for $x_0 = [1, 0]^T$:** + +Solve $H\, \mathbf{U}^* = -F \cdot [1, 0]^T$ via Gaussian elimination. + +Apply first element $u_0^*$ to the plant. + +## Pitfalls & Edge Cases + +- **Horizon too short:** If $N_p$ is too small, the controller is myopic and may produce oscillatory or unstable behavior. Use DARE terminal cost $P$ to mitigate. +- **Ill-conditioned Hessian:** Very large $Q/R$ ratios create poorly conditioned $H$. Keep $Q$ and $R$ within 3–4 orders of magnitude of each other. +- **Constraint infeasibility:** Box constraints that are too tight for the required control effort will clamp every step, degrading performance. Monitor constraint activity. +- **Fixed-point overflow:** For Q15/Q31 types, the Hessian elements grow with horizon length. Keep $N_c \cdot m$ small and scale weights carefully. +- **Stack usage:** All matrices are stack-allocated. A system with $n=3, m=2, N_c=10$ creates a $20 \times 20$ Hessian (1600 bytes for float). Monitor stack budget. +- **Terminal cost omission:** Without terminal cost $P$, the controller ignores cost-to-go beyond the horizon, leading to suboptimal or unstable behavior for short horizons. + +## Variants & Generalizations + +| Variant | Key Difference | Use Case | +|----------------------|-------------------------------------------------------------|-----------------------------------| +| Nonlinear MPC (NMPC) | Nonlinear prediction model, requires iterative optimization | Nonlinear plants, high-accuracy | +| Explicit MPC | Precomputes control law as piecewise affine function | Very fast online evaluation | +| Move-Blocking MPC | Constrains control moves to change only at specific steps | Reduces QP size | +| Adaptive MPC | Updates plant model online | Time-varying or uncertain systems | +| Distributed MPC | Decomposes problem across subsystems | Large-scale multi-agent systems | +| Robust MPC | Accounts for bounded disturbances in constraints | Safety-critical applications | + +## Applications + +- **Autonomous vehicles:** Path tracking with steering and acceleration limits +- **Process control:** Chemical reactor temperature/pressure regulation with valve constraints +- **Robotics:** Joint torque-constrained trajectory tracking +- **Power electronics:** Voltage/current regulation in converters with switching constraints +- **HVAC systems:** Energy-efficient building climate control with comfort bounds +- **Quadrotor control:** Attitude and position control with thrust limits + +## Connections to Other Algorithms + +```mermaid +graph LR + DARE["Discrete Algebraic
Riccati Equation"] -->|terminal cost P| MPC["Model Predictive
Controller"] + GE["Gaussian
Elimination"] -->|solves H·U = -F·x| MPC + LQR["LQR Controller"] -.->|special case
N→∞, no constraints| MPC + MPC -->|first control move| Plant["Plant Model"] + Plant -->|state measurement| MPC +``` + +- **LQR** is the infinite-horizon, unconstrained special case of MPC. As $N_p \to \infty$ with DARE terminal cost, the MPC gain converges to the LQR gain. +- **DARE** computes the terminal cost matrix $P$, ensuring the finite-horizon problem approximates the infinite-horizon solution. +- **Gaussian Elimination** solves the dense linear system $H\mathbf{U} = -Fx$ at each step. For constrained problems, iterative QP solvers could replace this. +- **Kalman Filter** provides state estimates when full state measurement is unavailable (MPC + KF = output-feedback MPC). + +## References & Further Reading + +- Maciejowski, J.M., *Predictive Control with Constraints*, Prentice Hall, 2002. +- Rawlings, J.B. and Mayne, D.Q., *Model Predictive Control: Theory and Design*, Nob Hill Publishing, 2009. +- Camacho, E.F. and Bordons, C., *Model Predictive Control*, 2nd ed., Springer, 2007. +- Borrelli, F., Bemporad, A., and Morari, M., *Predictive Control for Linear and Hybrid Systems*, Cambridge University Press, 2017. +- Wang, L., *Model Predictive Control System Design and Implementation Using MATLAB*, Springer, 2009. diff --git a/doc/controllers/README.md b/doc/controllers/README.md index f48d1081..97b62354 100644 --- a/doc/controllers/README.md +++ b/doc/controllers/README.md @@ -8,3 +8,4 @@ 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 | +| [MPC Controller](Mpc.md) | Model Predictive Controller — receding-horizon optimal control with constraint handling | diff --git a/numerical/controllers/implementations/CMakeLists.txt b/numerical/controllers/implementations/CMakeLists.txt index 0f9e7a20..a1dab84f 100644 --- a/numerical/controllers/implementations/CMakeLists.txt +++ b/numerical/controllers/implementations/CMakeLists.txt @@ -13,6 +13,8 @@ target_link_libraries(numerical.controllers.implementations PUBLIC target_sources(numerical.controllers.implementations PRIVATE Lqr.cpp Lqr.hpp + Mpc.cpp + Mpc.hpp PidIncremental.cpp PidIncremental.hpp ) diff --git a/numerical/controllers/implementations/Mpc.cpp b/numerical/controllers/implementations/Mpc.cpp new file mode 100644 index 00000000..5b4f2410 --- /dev/null +++ b/numerical/controllers/implementations/Mpc.cpp @@ -0,0 +1,9 @@ +#include "numerical/controllers/implementations/Mpc.hpp" + +namespace controllers +{ + template class Mpc; + template class Mpc; + template class Mpc; + template class Mpc; +} diff --git a/numerical/controllers/implementations/Mpc.hpp b/numerical/controllers/implementations/Mpc.hpp new file mode 100644 index 00000000..7191f556 --- /dev/null +++ b/numerical/controllers/implementations/Mpc.hpp @@ -0,0 +1,260 @@ +#pragma once + +#include "infra/util/Optional.hpp" +#include "numerical/controllers/interfaces/MpcController.hpp" +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/solvers/GaussianElimination.hpp" +#include + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +namespace controllers +{ + template + struct MpcWeights + { + math::SquareMatrix Q; + math::SquareMatrix R; + infra::Optional> terminalP; + }; + + template + struct MpcConstraints + { + infra::Optional> uMin; + infra::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 MpcController + { + using Base = MpcController; + + 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 InputWeightMatrix = math::SquareMatrix; + + using HessianMatrix = math::SquareMatrix; + using GradientMatrix = math::Matrix; + + Mpc(const StateMatrix& A, const InputMatrix& B, + 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; + + void SetReference(const StateVector& reference); + void ClearReference(); + + [[nodiscard]] const HessianMatrix& GetHessian() const; + [[nodiscard]] const GradientMatrix& GetGradientMatrix() const; + + private: + using PredictionStateMatrix = math::Matrix; + using PredictionInputMatrix = math::Matrix; + using AugmentedStateWeight = math::SquareMatrix; + using AugmentedInputWeight = math::SquareMatrix; + using ControlVector = math::Vector; + + PredictionStateMatrix BuildPsi(const StateMatrix& A) const; + PredictionInputMatrix BuildTheta(const StateMatrix& A, const InputMatrix& B) const; + void BuildCostMatrices(const MpcWeights& weights, + const StateMatrix& A, const InputMatrix& B); + void ApplyConstraints(ControlVector& u) const; + + HessianMatrix hessian; + GradientMatrix gradientMatrix; + MpcConstraints constraints; + ControlSequence controlSequence; + infra::Optional reference; + }; + + template + Mpc::Mpc( + const StateMatrix& A, const InputMatrix& B, + const MpcWeights& weights, + const MpcConstraints& constraints) + : constraints(constraints) + { + BuildCostMatrices(weights, A, B); + } + + template + Mpc::Mpc( + const HessianMatrix& precomputedH, const GradientMatrix& precomputedF, + const MpcConstraints& constraints) + : hessian(precomputedH) + , gradientMatrix(precomputedF) + , constraints(constraints) + {} + + template + OPTIMIZE_FOR_SPEED auto Mpc::BuildPsi( + const StateMatrix& A) const -> PredictionStateMatrix + { + PredictionStateMatrix psi; + auto Apow = StateMatrix::Identity(); + + for (std::size_t k = 0; k < PredictionHorizon; ++k) + { + Apow = Apow * A; + detail::SetBlock(psi, Apow, k * StateSize, 0); + } + + return psi; + } + + template + OPTIMIZE_FOR_SPEED auto Mpc::BuildTheta( + const StateMatrix& A, const InputMatrix& B) const -> PredictionInputMatrix + { + 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); + } + } + + return theta; + } + + template + OPTIMIZE_FOR_SPEED void Mpc::BuildCostMatrices( + const MpcWeights& weights, + const StateMatrix& A, const InputMatrix& B) + { + auto psi = BuildPsi(A); + auto theta = BuildTheta(A, B); + + AugmentedStateWeight qBar; + for (std::size_t k = 0; k < PredictionHorizon; ++k) + { + const auto& Qk = (k == PredictionHorizon - 1 && weights.terminalP) + ? *weights.terminalP + : weights.Q; + + detail::SetBlock(qBar, 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); + + auto thetaT = theta.Transpose(); + hessian = thetaT * qBar * theta + rBar; + gradientMatrix = thetaT * qBar * psi; + } + + template + OPTIMIZE_FOR_SPEED void Mpc::ApplyConstraints(ControlVector& u) const + { + if (!constraints.uMin && !constraints.uMax) + return; + + for (std::size_t k = 0; k < ControlHorizon; ++k) + { + for (std::size_t i = 0; i < InputSize; ++i) + { + if (constraints.uMin) + u.at(k * InputSize + i, 0) = std::max(u.at(k * InputSize + i, 0), constraints.uMin->at(i, 0)); + if (constraints.uMax) + u.at(k * InputSize + i, 0) = std::min(u.at(k * InputSize + i, 0), constraints.uMax->at(i, 0)); + } + } + } + + template + OPTIMIZE_FOR_SPEED + typename Mpc::InputVector + Mpc::ComputeControl(const StateVector& state) + { + 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 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); + + return controlSequence[0]; + } + + template + const typename Mpc::ControlSequence& + Mpc::GetControlSequence() const + { + return controlSequence; + } + + template + void Mpc::SetReference(const StateVector& ref) + { + reference = ref; + } + + template + void Mpc::ClearReference() + { + reference = infra::none; + } + + template + const typename Mpc::HessianMatrix& + Mpc::GetHessian() const + { + return hessian; + } + + template + const typename Mpc::GradientMatrix& + Mpc::GetGradientMatrix() const + { + return gradientMatrix; + } + + extern template class Mpc; + extern template class Mpc; + extern template class Mpc; + extern template class Mpc; +} diff --git a/numerical/controllers/implementations/test/CMakeLists.txt b/numerical/controllers/implementations/test/CMakeLists.txt index 6848af2e..cefd5feb 100644 --- a/numerical/controllers/implementations/test/CMakeLists.txt +++ b/numerical/controllers/implementations/test/CMakeLists.txt @@ -10,5 +10,6 @@ target_link_libraries(numerical.controllers_test PUBLIC target_sources(numerical.controllers_test PRIVATE TestLqr.cpp + TestMpc.cpp TestPidIncremental.cpp ) diff --git a/numerical/controllers/implementations/test/TestMpc.cpp b/numerical/controllers/implementations/test/TestMpc.cpp new file mode 100644 index 00000000..ad82e7f2 --- /dev/null +++ b/numerical/controllers/implementations/test/TestMpc.cpp @@ -0,0 +1,732 @@ +#include "numerical/controllers/implementations/Lqr.hpp" +#include "numerical/controllers/implementations/Mpc.hpp" +#include + +namespace +{ + class TestMpc : public ::testing::Test + { + }; +} + +TEST_F(TestMpc, compute_control_returns_zero_for_zero_state) +{ + math::SquareMatrix A{ + { 1.0f, 1.0f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f }, + { 1.0f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + math::Vector zeroState{ 0.0f, 0.0f }; + auto u = mpc.ComputeControl(zeroState); + + EXPECT_NEAR(u.at(0, 0), 0.0f, 1e-4f); +} + +TEST_F(TestMpc, compute_control_produces_nonzero_for_nonzero_state) +{ + math::SquareMatrix A{ + { 1.0f, 1.0f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f }, + { 1.0f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + 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); +} + +TEST_F(TestMpc, compute_control_drives_state_toward_origin) +{ + math::SquareMatrix A{ + { 1.0f, 1.0f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f }, + { 1.0f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f }, + { 0.0f, 10.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + math::Vector state{ 5.0f, 0.0f }; + + for (int step = 0; step < 50; ++step) + { + auto u = mpc.ComputeControl(state); + state = A * state + B * u; + } + + EXPECT_NEAR(state.at(0, 0), 0.0f, 0.1f); + EXPECT_NEAR(state.at(1, 0), 0.0f, 0.1f); +} + +TEST_F(TestMpc, control_sequence_length_equals_control_horizon) +{ + math::SquareMatrix A{ + { 1.0f, 1.0f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f }, + { 1.0f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + math::Vector state{ 1.0f, 0.0f }; + mpc.ComputeControl(state); + + auto seq = mpc.GetControlSequence(); + EXPECT_EQ(seq.size(), 5u); +} + +TEST_F(TestMpc, box_constraints_clamp_control_input) +{ + math::SquareMatrix A{ + { 1.0f, 1.0f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f }, + { 1.0f } + }; + + 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.5f }; + constraints.uMax = math::Vector{ 0.5f }; + + controllers::Mpc mpc(A, B, weights, constraints); + + math::Vector state{ 10.0f, 0.0f }; + auto u = mpc.ComputeControl(state); + + EXPECT_GE(u.at(0, 0), -0.5f); + EXPECT_LE(u.at(0, 0), 0.5f); + + auto seq = mpc.GetControlSequence(); + for (std::size_t k = 0; k < seq.size(); ++k) + { + EXPECT_GE(seq[k].at(0, 0), -0.5f); + EXPECT_LE(seq[k].at(0, 0), 0.5f); + } +} + +TEST_F(TestMpc, precomputed_constructor_matches_online_computation) +{ + math::SquareMatrix A{ + { 1.0f, 1.0f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f }, + { 1.0f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 1.0f, 0.0f }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpcOnline(A, B, weights); + + auto H = mpcOnline.GetHessian(); + auto F = mpcOnline.GetGradientMatrix(); + + controllers::Mpc mpcPrecomputed(H, F); + + math::Vector state{ 2.0f, -1.0f }; + auto uOnline = mpcOnline.ComputeControl(state); + auto uPrecomputed = mpcPrecomputed.ComputeControl(state); + + EXPECT_NEAR(uOnline.at(0, 0), uPrecomputed.at(0, 0), 1e-4f); +} + +TEST_F(TestMpc, double_integrator_regulation) +{ + // Double integrator: x1 = position, x2 = velocity + // x1[k+1] = x1[k] + dt * x2[k] + // x2[k+1] = x2[k] + dt * u[k] + float dt = 0.1f; + + math::SquareMatrix A{ + { 1.0f, dt }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f * dt * dt }, + { dt } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + math::Vector state{ 1.0f, 0.0f }; + + for (int step = 0; step < 100; ++step) + { + auto u = mpc.ComputeControl(state); + state = A * state + B * u; + } + + EXPECT_NEAR(state.at(0, 0), 0.0f, 0.01f); + EXPECT_NEAR(state.at(1, 0), 0.0f, 0.01f); +} + +TEST_F(TestMpc, unconstrained_mpc_approaches_lqr_with_long_horizon) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.005f }, + { 0.1f } + }; + + math::SquareMatrix Q{ + { 10.0f, 0.0f }, + { 0.0f, 1.0f } + }; + math::SquareMatrix R{ + { 0.1f } + }; + + // MPC with DARE terminal cost and long horizon should approximate LQR + controllers::MpcWeights weights; + weights.Q = Q; + weights.R = R; + + // Compute terminal cost via DARE + solvers::DiscreteAlgebraicRiccatiEquation dare; + auto P = dare.Solve(A, B, Q, R); + weights.terminalP = P; + + controllers::Mpc mpc(A, B, weights); + controllers::Lqr lqr(A, B, Q, R); + + math::Vector state{ 1.0f, 0.5f }; + + auto uMpc = mpc.ComputeControl(state); + auto uLqr = lqr.ComputeControl(state); + + // MPC with DARE terminal cost and sufficient horizon should be close to LQR + EXPECT_NEAR(math::ToFloat(uMpc.at(0, 0)), math::ToFloat(uLqr.at(0, 0)), 0.1f); +} + +TEST_F(TestMpc, reference_tracking_drives_state_to_reference) +{ + float dt = 0.1f; + + math::SquareMatrix A{ + { 1.0f, dt }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f * dt * dt }, + { dt } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + math::Vector ref{ 3.0f, 0.0f }; + mpc.SetReference(ref); + + math::Vector state{ 0.0f, 0.0f }; + + for (int step = 0; step < 200; ++step) + { + auto u = mpc.ComputeControl(state); + state = A * state + B * u; + } + + EXPECT_NEAR(state.at(0, 0), 3.0f, 0.05f); + EXPECT_NEAR(state.at(1, 0), 0.0f, 0.05f); +} + +TEST_F(TestMpc, clear_reference_reverts_to_origin_regulation) +{ + float dt = 0.1f; + + math::SquareMatrix A{ + { 1.0f, dt }, + { 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.5f * dt * dt }, + { dt } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + auto ref = math::Vector{ 5.0f, 0.0f }; + mpc.SetReference(ref); + + auto state = math::Vector{ 0.0f, 0.0f }; + auto u1 = mpc.ComputeControl(state); + EXPECT_GT(u1.at(0, 0), 0.0f); + + mpc.ClearReference(); + + auto u2 = mpc.ComputeControl(state); + EXPECT_NEAR(u2.at(0, 0), 0.0f, 1e-4f); +} + +TEST_F(TestMpc, three_state_system_regulation) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f, 0.0f }, + { 0.0f, 1.0f, 0.1f }, + { 0.0f, 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.0f }, + { 0.1f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + auto state = math::Vector{ 1.0f, 0.0f, 0.0f }; + + for (int step = 0; step < 200; ++step) + { + auto u = mpc.ComputeControl(state); + state = A * state + B * u; + } + + EXPECT_NEAR(state.at(0, 0), 0.0f, 0.1f); + EXPECT_NEAR(state.at(1, 0), 0.0f, 0.1f); + EXPECT_NEAR(state.at(2, 0), 0.0f, 0.1f); +} + +TEST_F(TestMpc, three_state_system_with_constraints) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f, 0.0f }, + { 0.0f, 1.0f, 0.1f }, + { 0.0f, 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.0f }, + { 0.1f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::MpcConstraints constraints; + constraints.uMin = math::Vector{ -0.3f }; + constraints.uMax = math::Vector{ 0.3f }; + + controllers::Mpc mpc(A, B, weights, constraints); + + auto state = math::Vector{ 2.0f, 0.0f, 0.0f }; + auto u = mpc.ComputeControl(state); + + EXPECT_GE(u.at(0, 0), -0.3f); + EXPECT_LE(u.at(0, 0), 0.3f); +} + +TEST_F(TestMpc, three_state_system_reference_tracking) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f, 0.0f }, + { 0.0f, 1.0f, 0.1f }, + { 0.0f, 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.0f }, + { 0.1f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + auto ref = math::Vector{ 2.0f, 0.0f, 0.0f }; + mpc.SetReference(ref); + + auto state = math::Vector{ 0.0f, 0.0f, 0.0f }; + + for (int step = 0; step < 300; ++step) + { + auto u = mpc.ComputeControl(state); + state = A * state + B * u; + } + + EXPECT_NEAR(state.at(0, 0), 2.0f, 0.2f); +} + +TEST_F(TestMpc, three_state_precomputed_constructor) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f, 0.0f }, + { 0.0f, 1.0f, 0.1f }, + { 0.0f, 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.0f }, + { 0.1f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpcOnline(A, B, weights); + + auto H = mpcOnline.GetHessian(); + auto F = mpcOnline.GetGradientMatrix(); + + controllers::Mpc mpcPrecomputed(H, F); + + auto state = math::Vector{ 1.0f, -0.5f, 0.2f }; + auto uOnline = mpcOnline.ComputeControl(state); + auto uPrecomputed = mpcPrecomputed.ComputeControl(state); + + EXPECT_NEAR(uOnline.at(0, 0), uPrecomputed.at(0, 0), 1e-3f); +} + +TEST_F(TestMpc, different_prediction_and_control_horizons_with_constraints) +{ + 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 } + }; + + controllers::MpcConstraints constraints; + constraints.uMin = math::Vector{ -1.0f }; + constraints.uMax = math::Vector{ 1.0f }; + + controllers::Mpc mpc(A, B, weights, constraints); + + auto state = math::Vector{ 5.0f, 0.0f }; + auto u = mpc.ComputeControl(state); + + EXPECT_GE(u.at(0, 0), -1.0f); + EXPECT_LE(u.at(0, 0), 1.0f); + + auto seq = mpc.GetControlSequence(); + EXPECT_EQ(seq.size(), 5u); +} + +TEST_F(TestMpc, different_prediction_and_control_horizons_reference_tracking) +{ + 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 } + }; + + controllers::Mpc mpc(A, B, weights); + + auto ref = math::Vector{ 2.0f, 0.0f }; + mpc.SetReference(ref); + + auto state = math::Vector{ 0.0f, 0.0f }; + + for (int step = 0; step < 200; ++step) + { + auto u = mpc.ComputeControl(state); + state = A * state + B * u; + } + + EXPECT_NEAR(state.at(0, 0), 2.0f, 0.1f); +} + +TEST_F(TestMpc, different_prediction_and_control_horizons_precomputed) +{ + 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 } + }; + + controllers::Mpc mpcOnline(A, B, weights); + + auto H = mpcOnline.GetHessian(); + auto F = mpcOnline.GetGradientMatrix(); + + controllers::Mpc mpcPrecomputed(H, F); + + auto state = math::Vector{ 3.0f, -1.0f }; + auto uOnline = mpcOnline.ComputeControl(state); + auto uPrecomputed = mpcPrecomputed.ComputeControl(state); + + EXPECT_NEAR(uOnline.at(0, 0), uPrecomputed.at(0, 0), 1e-3f); +} + +TEST_F(TestMpc, ten_horizon_precomputed_with_constraints) +{ + 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 } + }; + + controllers::Mpc mpcOnline(A, B, weights); + + auto H = mpcOnline.GetHessian(); + auto F = mpcOnline.GetGradientMatrix(); + + controllers::MpcConstraints constraints; + constraints.uMin = math::Vector{ -0.5f }; + constraints.uMax = math::Vector{ 0.5f }; + + controllers::Mpc mpcPrecomputed(H, F, constraints); + + auto state = math::Vector{ 5.0f, -1.0f }; + auto u = mpcPrecomputed.ComputeControl(state); + + EXPECT_GE(u.at(0, 0), -0.5f); + EXPECT_LE(u.at(0, 0), 0.5f); + + auto seq = mpcPrecomputed.GetControlSequence(); + EXPECT_EQ(seq.size(), 10u); +} + +TEST_F(TestMpc, three_state_clear_reference_and_get_sequence) +{ + math::SquareMatrix A{ + { 1.0f, 0.1f, 0.0f }, + { 0.0f, 1.0f, 0.1f }, + { 0.0f, 0.0f, 1.0f } + }; + math::Matrix B{ + { 0.0f }, + { 0.0f }, + { 0.1f } + }; + + controllers::MpcWeights weights; + weights.Q = math::SquareMatrix{ + { 10.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { 0.1f } + }; + + controllers::Mpc mpc(A, B, weights); + + auto ref = math::Vector{ 1.0f, 0.0f, 0.0f }; + mpc.SetReference(ref); + + auto state = math::Vector{ 0.0f, 0.0f, 0.0f }; + auto u1 = mpc.ComputeControl(state); + EXPECT_NE(u1.at(0, 0), 0.0f); + + mpc.ClearReference(); + + auto u2 = mpc.ComputeControl(state); + EXPECT_NEAR(u2.at(0, 0), 0.0f, 1e-4f); + + auto seq = mpc.GetControlSequence(); + EXPECT_EQ(seq.size(), 10u); +} + +TEST_F(TestMpc, different_horizons_clear_reference) +{ + 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 } + }; + + controllers::Mpc mpc(A, B, weights); + + auto ref = math::Vector{ 5.0f, 0.0f }; + mpc.SetReference(ref); + + auto state = math::Vector{ 0.0f, 0.0f }; + auto u1 = mpc.ComputeControl(state); + EXPECT_GT(u1.at(0, 0), 0.0f); + + mpc.ClearReference(); + + auto u2 = mpc.ComputeControl(state); + EXPECT_NEAR(u2.at(0, 0), 0.0f, 1e-4f); +} diff --git a/numerical/controllers/interfaces/CMakeLists.txt b/numerical/controllers/interfaces/CMakeLists.txt index 9ca2b6ff..de3f0ad2 100644 --- a/numerical/controllers/interfaces/CMakeLists.txt +++ b/numerical/controllers/interfaces/CMakeLists.txt @@ -12,6 +12,7 @@ target_link_libraries(numerical.controllers.interfaces INTERFACE target_sources(numerical.controllers.interfaces PRIVATE LqrController.hpp + MpcController.hpp PidController.hpp PidDriver.hpp ) diff --git a/numerical/controllers/interfaces/MpcController.hpp b/numerical/controllers/interfaces/MpcController.hpp new file mode 100644 index 00000000..1a90a167 --- /dev/null +++ b/numerical/controllers/interfaces/MpcController.hpp @@ -0,0 +1,33 @@ +#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/simulator/controllers/CMakeLists.txt b/simulator/controllers/CMakeLists.txt index cf389373..14033367 100644 --- a/simulator/controllers/CMakeLists.txt +++ b/simulator/controllers/CMakeLists.txt @@ -1 +1,2 @@ +add_subdirectory(Mpc) add_subdirectory(PidController) diff --git a/simulator/controllers/Mpc/CMakeLists.txt b/simulator/controllers/Mpc/CMakeLists.txt new file mode 100644 index 00000000..2cb10579 --- /dev/null +++ b/simulator/controllers/Mpc/CMakeLists.txt @@ -0,0 +1,24 @@ +find_package(Qt6 REQUIRED COMPONENTS Widgets) + +add_subdirectory(application) +add_subdirectory(view) + +add_executable(numerical.simulator.controllers.mpc) +emil_build_for(numerical.simulator.controllers.mpc HOST All PREREQUISITE_BOOL NUMERICAL_TOOLBOX_BUILD_SIMULATOR) + +target_link_libraries(numerical.simulator.controllers.mpc PRIVATE + numerical.simulator.controllers.mpc.application + numerical.simulator.controllers.mpc.view +) + +target_sources(numerical.simulator.controllers.mpc PRIVATE + Main.cpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.mpc PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.mpc PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/Mpc/Main.cpp b/simulator/controllers/Mpc/Main.cpp new file mode 100644 index 00000000..18e7db57 --- /dev/null +++ b/simulator/controllers/Mpc/Main.cpp @@ -0,0 +1,12 @@ +#include "simulator/controllers/Mpc/view/MpcMainWindow.hpp" +#include + +int main(int argc, char* argv[]) +{ + QApplication app(argc, argv); + + simulator::controllers::view::MpcMainWindow window; + window.show(); + + return app.exec(); +} diff --git a/simulator/controllers/Mpc/application/CMakeLists.txt b/simulator/controllers/Mpc/application/CMakeLists.txt new file mode 100644 index 00000000..4650f93d --- /dev/null +++ b/simulator/controllers/Mpc/application/CMakeLists.txt @@ -0,0 +1,26 @@ +add_library(numerical.simulator.controllers.mpc.application STATIC) + +target_include_directories(numerical.simulator.controllers.mpc.application PUBLIC + "$" + "$" +) + +target_link_libraries(numerical.simulator.controllers.mpc.application PUBLIC + numerical.controllers.implementations + numerical.solver +) + +target_sources(numerical.simulator.controllers.mpc.application PRIVATE + MpcSimulator.cpp + MpcSimulator.hpp + StateSpacePlant.cpp + StateSpacePlant.hpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.mpc.application PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.mpc.application PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/Mpc/application/MpcSimulator.cpp b/simulator/controllers/Mpc/application/MpcSimulator.cpp new file mode 100644 index 00000000..8dae0fb6 --- /dev/null +++ b/simulator/controllers/Mpc/application/MpcSimulator.cpp @@ -0,0 +1,85 @@ +#include "simulator/controllers/Mpc/application/MpcSimulator.hpp" +#include "numerical/controllers/implementations/Mpc.hpp" +#include + +namespace simulator::controllers +{ + void MpcSimulator::Configure(const StateSpacePlant& plant, const Configuration& config) + { + this->plant = plant; + configuration = config; + } + + MpcTimeResponse MpcSimulator::ComputeStepResponse() + { + return Simulate(false); + } + + MpcTimeResponse MpcSimulator::ComputeConstrainedResponse() + { + return Simulate(true); + } + + MpcTimeResponse MpcSimulator::Simulate(bool enableConstraints) + { + auto dt = configuration.simulation.sampleTime; + 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 }, + { 0.0f, 1.0f } + }; + weights.R = math::SquareMatrix{ + { configuration.weights.controlWeight } + }; + + auto constraints = ::controllers::MpcConstraints{}; + if (enableConstraints && configuration.constraints.enabled) + { + constraints.uMin = math::Vector{ configuration.constraints.uMin }; + constraints.uMax = math::Vector{ configuration.constraints.uMax }; + } + + auto mpc = ::controllers::Mpc(A, B, weights, constraints); + + auto ref = math::Vector{ configuration.referencePosition, 0.0f }; + mpc.SetReference(ref); + + auto state = math::Vector{ 0.0f, 0.0f }; + + auto response = MpcTimeResponse{}; + response.states.resize(2); + + for (std::size_t i = 0; i < numSamples; ++i) + { + response.time.push_back(static_cast(i) * dt); + response.states[0].push_back(state.at(0, 0)); + response.states[1].push_back(state.at(1, 0)); + + auto u = mpc.ComputeControl(state); + response.control.push_back(u.at(0, 0)); + + auto posError = state.at(0, 0) - configuration.referencePosition; + auto velError = state.at(1, 0); + auto costStep = configuration.weights.stateWeight * posError * posError + + velError * velError + + configuration.weights.controlWeight * u.at(0, 0) * u.at(0, 0); + response.cost.push_back(costStep); + + state = A * state + B * u; + } + + return response; + } +} diff --git a/simulator/controllers/Mpc/application/MpcSimulator.hpp b/simulator/controllers/Mpc/application/MpcSimulator.hpp new file mode 100644 index 00000000..1df13d24 --- /dev/null +++ b/simulator/controllers/Mpc/application/MpcSimulator.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include "simulator/controllers/Mpc/application/StateSpacePlant.hpp" +#include + +namespace simulator::controllers +{ + struct MpcSimulationConfig + { + float duration = 10.0f; + float sampleTime = 0.1f; + }; + + struct MpcWeightsConfig + { + float stateWeight = 10.0f; + float controlWeight = 0.1f; + }; + + struct MpcConstraintsConfig + { + bool enabled = false; + float uMin = -1.0f; + float uMax = 1.0f; + }; + + struct MpcTimeResponse + { + std::vector time; + std::vector> states; + std::vector control; + std::vector cost; + }; + + class MpcSimulator + { + public: + struct Configuration + { + MpcWeightsConfig weights; + MpcConstraintsConfig constraints; + MpcSimulationConfig simulation; + float referencePosition = 1.0f; + }; + + void Configure(const StateSpacePlant& plant, const Configuration& config); + MpcTimeResponse ComputeStepResponse(); + MpcTimeResponse ComputeConstrainedResponse(); + + private: + MpcTimeResponse Simulate(bool enableConstraints); + + StateSpacePlant plant; + Configuration configuration; + }; +} diff --git a/simulator/controllers/Mpc/application/StateSpacePlant.cpp b/simulator/controllers/Mpc/application/StateSpacePlant.cpp new file mode 100644 index 00000000..5a6afbd0 --- /dev/null +++ b/simulator/controllers/Mpc/application/StateSpacePlant.cpp @@ -0,0 +1,28 @@ +#include "simulator/controllers/Mpc/application/StateSpacePlant.hpp" +#include + +namespace simulator::controllers +{ + StateSpacePlant MakeDoubleIntegrator(float dt) + { + return StateSpacePlant{ + .A = { { 1.0f, dt }, { 0.0f, 1.0f } }, + .B = { { 0.5f * dt * dt }, { dt } }, + .stateSize = 2, + .inputSize = 1 + }; + } + + StateSpacePlant 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 + }; + } +} diff --git a/simulator/controllers/Mpc/application/StateSpacePlant.hpp b/simulator/controllers/Mpc/application/StateSpacePlant.hpp new file mode 100644 index 00000000..a1ff16dc --- /dev/null +++ b/simulator/controllers/Mpc/application/StateSpacePlant.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include + +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); +} diff --git a/simulator/controllers/Mpc/view/CMakeLists.txt b/simulator/controllers/Mpc/view/CMakeLists.txt new file mode 100644 index 00000000..90d1577b --- /dev/null +++ b/simulator/controllers/Mpc/view/CMakeLists.txt @@ -0,0 +1,32 @@ +add_library(numerical.simulator.controllers.mpc.view STATIC) + +target_include_directories(numerical.simulator.controllers.mpc.view PUBLIC + "$" + "$" +) + +target_link_libraries(numerical.simulator.controllers.mpc.view PUBLIC + numerical.simulator.controllers.mpc.application + Qt6::Widgets +) + +set_target_properties(numerical.simulator.controllers.mpc.view PROPERTIES + AUTOMOC ON +) + +target_sources(numerical.simulator.controllers.mpc.view PRIVATE + MpcChartWidget.cpp + MpcChartWidget.hpp + MpcConfigurationPanel.cpp + MpcConfigurationPanel.hpp + MpcMainWindow.cpp + MpcMainWindow.hpp +) + +if(MSVC) + target_compile_options(numerical.simulator.controllers.mpc.view PRIVATE /W4 /wd4244 /wd4100) +else() + target_compile_options(numerical.simulator.controllers.mpc.view PRIVATE + -Wno-error + ) +endif() diff --git a/simulator/controllers/Mpc/view/MpcChartWidget.cpp b/simulator/controllers/Mpc/view/MpcChartWidget.cpp new file mode 100644 index 00000000..fcfafeda --- /dev/null +++ b/simulator/controllers/Mpc/view/MpcChartWidget.cpp @@ -0,0 +1,183 @@ +#include "simulator/controllers/Mpc/view/MpcChartWidget.hpp" +#include +#include +#include +#include + +namespace simulator::controllers::view +{ + MpcTimeResponseWidget::MpcTimeResponseWidget(const QString& title, QWidget* parent) + : QWidget(parent) + , chartTitle(title) + { + setMinimumSize(400, 500); + setBackgroundRole(QPalette::Base); + setAutoFillBackground(true); + } + + void MpcTimeResponseWidget::SetData(const MpcTimeResponse& result, float refPos) + { + time = result.time; + states = result.states; + control = result.control; + cost = result.cost; + referencePosition = refPos; + + maxTime = time.empty() ? 0.0f : time.back(); + maxState = 0.0f; + minState = 0.0f; + maxControl = 0.0f; + minControl = 0.0f; + maxCost = 0.0f; + + for (const auto& s : states) + for (auto v : s) + { + maxState = std::max(maxState, v); + minState = std::min(minState, v); + } + + maxState = std::max(maxState, refPos); + minState = std::min(minState, refPos); + + for (auto v : control) + { + maxControl = std::max(maxControl, v); + minControl = std::min(minControl, v); + } + + for (auto v : cost) + maxCost = std::max(maxCost, v); + + float statePad = (maxState - minState) * 0.1f; + if (statePad < 0.1f) + statePad = 0.1f; + maxState += statePad; + minState -= statePad; + + float ctrlPad = (maxControl - minControl) * 0.1f; + if (ctrlPad < 0.1f) + ctrlPad = 0.1f; + maxControl += ctrlPad; + minControl -= ctrlPad; + + maxCost *= 1.1f; + if (maxCost < 0.1f) + maxCost = 0.1f; + + update(); + } + + void MpcTimeResponseWidget::paintEvent(QPaintEvent* /*event*/) + { + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + + if (time.empty()) + { + painter.drawText(rect(), Qt::AlignCenter, "No data - press Compute"); + return; + } + + int margin = 50; + int chartHeight = (height() - 4 * margin) / 3; + if (chartHeight < 50) + return; + + painter.setPen(QPen(Qt::black, 1)); + painter.drawText(QRect(0, 5, width(), 20), Qt::AlignCenter, chartTitle); + + QRect stateArea(margin, margin, width() - 2 * margin, chartHeight); + QRect controlArea(margin, margin + chartHeight + margin / 2, width() - 2 * margin, chartHeight); + QRect costArea(margin, margin + 2 * (chartHeight + margin / 2), width() - 2 * margin, chartHeight); + + DrawStateChart(painter, stateArea); + DrawControlChart(painter, controlArea); + DrawCostChart(painter, costArea); + } + + void MpcTimeResponseWidget::DrawAxes(QPainter& painter, const QRect& plotArea) + { + painter.setPen(QPen(Qt::black, 1)); + painter.drawRect(plotArea); + } + + void MpcTimeResponseWidget::DrawStateChart(QPainter& painter, const QRect& plotArea) + { + DrawAxes(painter, plotArea); + painter.drawText(plotArea.topLeft() + QPointF(-45, plotArea.height() / 2.0), "State"); + + if (time.size() < 2) + return; + + float stateRange = maxState - minState; + if (stateRange < 1e-6f) + stateRange = 1.0f; + + // Draw reference line + painter.setPen(QPen(Qt::gray, 1, Qt::DashLine)); + float refY = plotArea.bottom() - (referencePosition - minState) / stateRange * plotArea.height(); + painter.drawLine(QPointF(plotArea.left(), refY), QPointF(plotArea.right(), refY)); + + // Draw states + QColor colors[] = { Qt::blue, Qt::red, Qt::darkGreen, Qt::magenta }; + QString labels[] = { "Position", "Velocity", "State 3", "State 4" }; + + for (std::size_t s = 0; s < states.size() && s < 4; ++s) + { + painter.setPen(QPen(colors[s], 2)); + for (std::size_t i = 1; i < time.size() && i < states[s].size(); ++i) + { + float x1 = plotArea.left() + time[i - 1] / maxTime * plotArea.width(); + float y1 = plotArea.bottom() - (states[s][i - 1] - minState) / stateRange * plotArea.height(); + float x2 = plotArea.left() + time[i] / maxTime * plotArea.width(); + float y2 = plotArea.bottom() - (states[s][i] - minState) / stateRange * plotArea.height(); + painter.drawLine(QPointF(x1, y1), QPointF(x2, y2)); + } + + painter.drawText(plotArea.right() - 80, plotArea.top() + 15 + static_cast(s) * 15, labels[s]); + } + } + + void MpcTimeResponseWidget::DrawControlChart(QPainter& painter, const QRect& plotArea) + { + DrawAxes(painter, plotArea); + painter.drawText(plotArea.topLeft() + QPointF(-45, plotArea.height() / 2.0), "Control"); + + if (time.size() < 2) + return; + + float ctrlRange = maxControl - minControl; + if (ctrlRange < 1e-6f) + ctrlRange = 1.0f; + + painter.setPen(QPen(Qt::darkCyan, 2)); + for (std::size_t i = 1; i < time.size() && i < control.size(); ++i) + { + float x1 = plotArea.left() + time[i - 1] / maxTime * plotArea.width(); + float y1 = plotArea.bottom() - (control[i - 1] - minControl) / ctrlRange * plotArea.height(); + float x2 = plotArea.left() + time[i] / maxTime * plotArea.width(); + float y2 = plotArea.bottom() - (control[i] - minControl) / ctrlRange * plotArea.height(); + painter.drawLine(QPointF(x1, y1), QPointF(x2, y2)); + } + } + + void MpcTimeResponseWidget::DrawCostChart(QPainter& painter, const QRect& plotArea) + { + DrawAxes(painter, plotArea); + painter.drawText(plotArea.topLeft() + QPointF(-45, plotArea.height() / 2.0), "Cost"); + + if (time.size() < 2) + return; + + painter.setPen(QPen(Qt::darkRed, 2)); + for (std::size_t i = 1; i < time.size() && i < cost.size(); ++i) + { + float x1 = plotArea.left() + time[i - 1] / maxTime * plotArea.width(); + float y1 = plotArea.bottom() - cost[i - 1] / maxCost * plotArea.height(); + float x2 = plotArea.left() + time[i] / maxTime * plotArea.width(); + float y2 = plotArea.bottom() - cost[i] / maxCost * plotArea.height(); + painter.drawLine(QPointF(x1, y1), QPointF(x2, y2)); + } + } +} diff --git a/simulator/controllers/Mpc/view/MpcChartWidget.hpp b/simulator/controllers/Mpc/view/MpcChartWidget.hpp new file mode 100644 index 00000000..c7127ded --- /dev/null +++ b/simulator/controllers/Mpc/view/MpcChartWidget.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include "simulator/controllers/Mpc/application/MpcSimulator.hpp" +#include +#include + +class QPainter; + +namespace simulator::controllers::view +{ + class MpcTimeResponseWidget + : public QWidget + { + Q_OBJECT + + public: + explicit MpcTimeResponseWidget(const QString& title, QWidget* parent = nullptr); + + void SetData(const MpcTimeResponse& result, float referencePosition); + + protected: + void paintEvent(QPaintEvent* event) override; + + private: + void DrawAxes(QPainter& painter, const QRect& plotArea); + void DrawStateChart(QPainter& painter, const QRect& plotArea); + void DrawControlChart(QPainter& painter, const QRect& plotArea); + void DrawCostChart(QPainter& painter, const QRect& plotArea); + + QString chartTitle; + std::vector time; + std::vector> states; + std::vector control; + std::vector cost; + float referencePosition = 0.0f; + + float maxTime = 0.0f; + float maxState = 0.0f; + float minState = 0.0f; + float maxControl = 0.0f; + float minControl = 0.0f; + float maxCost = 0.0f; + }; + + class MpcStepResponseWidget : public MpcTimeResponseWidget + { + public: + explicit MpcStepResponseWidget(QWidget* parent = nullptr) + : MpcTimeResponseWidget("Step Response", parent) + { + } + }; + + class MpcConstrainedResponseWidget : public MpcTimeResponseWidget + { + public: + explicit MpcConstrainedResponseWidget(QWidget* parent = nullptr) + : MpcTimeResponseWidget("Constrained Response", parent) + { + } + }; +} diff --git a/simulator/controllers/Mpc/view/MpcConfigurationPanel.cpp b/simulator/controllers/Mpc/view/MpcConfigurationPanel.cpp new file mode 100644 index 00000000..0b6e3fb3 --- /dev/null +++ b/simulator/controllers/Mpc/view/MpcConfigurationPanel.cpp @@ -0,0 +1,121 @@ +#include "simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp" +#include +#include +#include + +namespace simulator::controllers::view +{ + MpcConfigurationPanel::MpcConfigurationPanel(QWidget* parent) + : QWidget(parent) + { + SetupUi(); + } + + void MpcConfigurationPanel::SetupUi() + { + auto* mainLayout = new QVBoxLayout(this); + + auto addSpinRow = [&](QVBoxLayout* layout, const QString& label, QDoubleSpinBox*& spinBox, double min, double max, double value, int decimals, const QString& suffix = "") + { + auto* row = new QHBoxLayout(); + row->addWidget(new QLabel(label, this)); + spinBox = new QDoubleSpinBox(this); + spinBox->setRange(min, max); + spinBox->setValue(value); + spinBox->setDecimals(decimals); + if (!suffix.isEmpty()) + spinBox->setSuffix(suffix); + row->addWidget(spinBox); + layout->addLayout(row); + }; + + auto* weightsGroup = new QGroupBox("MPC Weights", this); + auto* weightsLayout = new QVBoxLayout(weightsGroup); + addSpinRow(weightsLayout, "Q (state):", stateWeightSpinBox, 0.01, 1000.0, 10.0, 2); + addSpinRow(weightsLayout, "R (control):", controlWeightSpinBox, 0.001, 100.0, 0.1, 3); + mainLayout->addWidget(weightsGroup); + + auto* constraintGroup = new QGroupBox("Constraints", this); + auto* constraintLayout = new QVBoxLayout(constraintGroup); + constraintsEnabled = new QCheckBox("Enable control constraints", this); + constraintLayout->addWidget(constraintsEnabled); + addSpinRow(constraintLayout, "u_min:", uMinSpinBox, -100.0, 0.0, -2.0, 2); + addSpinRow(constraintLayout, "u_max:", uMaxSpinBox, 0.0, 100.0, 2.0, 2); + mainLayout->addWidget(constraintGroup); + + auto* plantGroup = new QGroupBox("Plant Model", this); + auto* plantLayout = new QVBoxLayout(plantGroup); + auto* plantRow = new QHBoxLayout(); + plantRow->addWidget(new QLabel("Type:", this)); + plantCombo = new QComboBox(this); + plantCombo->addItem("Double Integrator"); + plantCombo->addItem("1st Order + Integrator"); + plantRow->addWidget(plantCombo); + plantLayout->addLayout(plantRow); + + firstOrderGroup = new QGroupBox("Plant Parameters", this); + auto* firstOrderLayout = new QVBoxLayout(firstOrderGroup); + addSpinRow(firstOrderLayout, "Gain:", plantGainSpinBox, 0.01, 100.0, 1.0, 2); + addSpinRow(firstOrderLayout, "Time Const:", plantTimeConstantSpinBox, 0.01, 100.0, 1.0, 2, " s"); + firstOrderGroup->setVisible(false); + plantLayout->addWidget(firstOrderGroup); + + mainLayout->addWidget(plantGroup); + + auto* simGroup = new QGroupBox("Simulation", this); + auto* simLayout = new QVBoxLayout(simGroup); + addSpinRow(simLayout, "Duration:", durationSpinBox, 0.1, 100.0, 10.0, 1, " s"); + addSpinRow(simLayout, "Sample Time:", sampleTimeSpinBox, 0.001, 1.0, 0.1, 3, " s"); + addSpinRow(simLayout, "Reference:", referenceSpinBox, -100.0, 100.0, 1.0, 2); + mainLayout->addWidget(simGroup); + + computeButton = new QPushButton("Compute", this); + computeButton->setMinimumHeight(40); + mainLayout->addWidget(computeButton); + + mainLayout->addStretch(); + + connect(plantCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int index) + { + firstOrderGroup->setVisible(index == 1); + }); + connect(computeButton, &QPushButton::clicked, this, &MpcConfigurationPanel::ComputeRequested); + } + + MpcSimulator::Configuration MpcConfigurationPanel::GetConfiguration() const + { + MpcSimulator::Configuration config; + + config.weights.stateWeight = static_cast(stateWeightSpinBox->value()); + config.weights.controlWeight = static_cast(controlWeightSpinBox->value()); + + config.constraints.enabled = constraintsEnabled->isChecked(); + config.constraints.uMin = static_cast(uMinSpinBox->value()); + config.constraints.uMax = static_cast(uMaxSpinBox->value()); + + config.simulation.duration = static_cast(durationSpinBox->value()); + config.simulation.sampleTime = static_cast(sampleTimeSpinBox->value()); + + config.referencePosition = static_cast(referenceSpinBox->value()); + + return config; + } + + StateSpacePlant MpcConfigurationPanel::CreatePlant() const + { + float dt = static_cast(sampleTimeSpinBox->value()); + + if (plantCombo->currentIndex() == 0) + return MakeDoubleIntegrator(dt); + + return MakeFirstOrderWithIntegrator( + static_cast(plantGainSpinBox->value()), + static_cast(plantTimeConstantSpinBox->value()), + dt); + } + + QString MpcConfigurationPanel::GetPlantDescription() const + { + return plantCombo->currentText(); + } +} diff --git a/simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp b/simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp new file mode 100644 index 00000000..a5bf10f5 --- /dev/null +++ b/simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp @@ -0,0 +1,50 @@ +#pragma once + +#include "simulator/controllers/Mpc/application/MpcSimulator.hpp" +#include "simulator/controllers/Mpc/application/StateSpacePlant.hpp" +#include +#include +#include +#include +#include +#include + +namespace simulator::controllers::view +{ + class MpcConfigurationPanel + : public QWidget + { + Q_OBJECT + + public: + explicit MpcConfigurationPanel(QWidget* parent = nullptr); + + MpcSimulator::Configuration GetConfiguration() const; + StateSpacePlant CreatePlant() const; + QString GetPlantDescription() const; + + signals: + void ComputeRequested(); + + private: + void SetupUi(); + + QDoubleSpinBox* stateWeightSpinBox; + QDoubleSpinBox* controlWeightSpinBox; + + QCheckBox* constraintsEnabled; + QDoubleSpinBox* uMinSpinBox; + QDoubleSpinBox* uMaxSpinBox; + + QComboBox* plantCombo; + QDoubleSpinBox* sampleTimeSpinBox; + QDoubleSpinBox* durationSpinBox; + QDoubleSpinBox* referenceSpinBox; + + QDoubleSpinBox* plantGainSpinBox; + QDoubleSpinBox* plantTimeConstantSpinBox; + QGroupBox* firstOrderGroup; + + QPushButton* computeButton; + }; +} diff --git a/simulator/controllers/Mpc/view/MpcMainWindow.cpp b/simulator/controllers/Mpc/view/MpcMainWindow.cpp new file mode 100644 index 00000000..59b6cb92 --- /dev/null +++ b/simulator/controllers/Mpc/view/MpcMainWindow.cpp @@ -0,0 +1,65 @@ +#include "simulator/controllers/Mpc/view/MpcMainWindow.hpp" +#include +#include +#include + +namespace simulator::controllers::view +{ + MpcMainWindow::MpcMainWindow(QWidget* parent) + : QMainWindow(parent) + { + setWindowTitle("MPC Controller Simulator"); + resize(1280, 900); + + auto* splitter = new QSplitter(Qt::Horizontal, this); + + configPanel = new MpcConfigurationPanel(splitter); + configPanel->setMaximumWidth(350); + + tabWidget = new QTabWidget(splitter); + + stepChart = new MpcStepResponseWidget(tabWidget); + constrainedChart = new MpcConstrainedResponseWidget(tabWidget); + + tabWidget->addTab(stepChart, "Step Response"); + tabWidget->addTab(constrainedChart, "Constrained Response"); + + splitter->addWidget(configPanel); + splitter->addWidget(tabWidget); + splitter->setStretchFactor(0, 0); + splitter->setStretchFactor(1, 1); + + setCentralWidget(splitter); + + statusBar()->showMessage("Configure MPC parameters and press Compute"); + + connect(configPanel, &MpcConfigurationPanel::ComputeRequested, this, &MpcMainWindow::OnComputeRequested); + } + + void MpcMainWindow::OnComputeRequested() + { + try + { + auto config = configPanel->GetConfiguration(); + auto plant = configPanel->CreatePlant(); + mpcSimulator.Configure(plant, config); + + auto stepResult = mpcSimulator.ComputeStepResponse(); + stepChart->SetData(stepResult, config.referencePosition); + + auto constrainedResult = mpcSimulator.ComputeConstrainedResponse(); + constrainedChart->SetData(constrainedResult, config.referencePosition); + + statusBar()->showMessage( + QString("MPC: Q=%1 R=%2 | Plant: %3") + .arg(static_cast(config.weights.stateWeight), 0, 'f', 2) + .arg(static_cast(config.weights.controlWeight), 0, 'f', 3) + .arg(configPanel->GetPlantDescription())); + } + catch (const std::exception& e) + { + QMessageBox::warning(this, "Computation Error", e.what()); + statusBar()->showMessage("Computation failed"); + } + } +} diff --git a/simulator/controllers/Mpc/view/MpcMainWindow.hpp b/simulator/controllers/Mpc/view/MpcMainWindow.hpp new file mode 100644 index 00000000..675e2e4e --- /dev/null +++ b/simulator/controllers/Mpc/view/MpcMainWindow.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include "simulator/controllers/Mpc/application/MpcSimulator.hpp" +#include "simulator/controllers/Mpc/view/MpcChartWidget.hpp" +#include "simulator/controllers/Mpc/view/MpcConfigurationPanel.hpp" +#include +#include +#include + +namespace simulator::controllers::view +{ + class MpcMainWindow + : public QMainWindow + { + Q_OBJECT + + public: + explicit MpcMainWindow(QWidget* parent = nullptr); + + private: + void OnComputeRequested(); + + MpcSimulator mpcSimulator; + MpcConfigurationPanel* configPanel; + QTabWidget* tabWidget; + MpcStepResponseWidget* stepChart; + MpcConstrainedResponseWidget* constrainedChart; + }; +}