Algorithm Search⌘K

Algorithmcore

Linear MPC as a quadratic program

Also called linear model predictive control, linear quadratic MPC.

For a linear model, a quadratic cost and linear constraints, each MPC step is a convex QP in the N m future inputs; the controller applies the first input and repeats.

Time
O(t (c N m + N^2 m^2)) worstO(N^3 (n + m)^3) offline
Space
O(N^2 m^2 + c (N m + n)) extra
Where
N = the horizon; c = the number of constraint rows, 2 N m + 2 N n plus the terminal rows for box limits; m = the number of inputs; n = the number of states; t = the number of QP iterations at one sampling instant
Properties
deterministicexactonlineiterative
Origin
Carlos E. García, A. M. Morshedi, Kenneth R. Muske, James B. Rawlings, 1986

Linear MPC is model predictive control for the linear model xk+1=Axk+Bukx_{k+1} = A x_k + B u_k with a quadratic cost and linear constraints on inputs and states. At each sampling instant the controller measures xx, solves a convex quadratic program (QP) in the future inputs u0,…,uN−1u_0, \dots, u_{N-1}, applies u0u_0, and repeats at the next instant. When the states are eliminated, the QP has NmN m variables and a positive definite Hessian that does not depend on xx; only the linear term and the right-hand side of the constraints change with xx. This page builds that condensed QP, solves it with the dual active set method of Goldfarb and Idnani (1983), and checks the result with the KKT conditions. Without active constraints and with the DARE solution as terminal cost, the law is the infinite-horizon LQR gain u=−Kxu = -K x.

In plain words

The controller has a model that says how the system moves for each input. At each tick it looks at the present state and plans the inputs for the next few ticks. It picks the plan that keeps the states small and uses little input, and it respects the limits on inputs and states. For this kind of model and cost, the best plan is the answer to a standard and well understood optimization problem, a quadratic program, with one unique solution. The controller sends only the first input of the plan. At the next tick it measures again and makes a new plan. So the plan always starts from the real state, and errors of the model do not build up along the plan.

The problem

Input: matrices A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m}, weights Q≥0Q \ge 0, R>0R > 0 and a terminal weight P≥0P \ge 0, a horizon N≥1N \ge 1, bounds umin⁡≤uk≤umax⁡u_{\min} \le u_k \le u_{\max} for k=0,…,N−1k = 0, \dots, N - 1, bounds xmin⁡≤xk≤xmax⁡x_{\min} \le x_k \le x_{\max} for k=1,…,Nk = 1, \dots, N, an optional terminal set Xf={x:Hfx≤hf}\mathbb{X}_f = \{x : H_f x \le h_f\}, and the current state xx.

Output: the input u0∗(x)u_0^*(x), the first part of the minimizer of

VN(x)=min⁡u0,…,uN−1∑k=0N−1(xkTQxk+ukTRuk)+xNTPxNV_N(x) = \min_{u_0, \dots, u_{N-1}} \sum_{k=0}^{N-1} \left(x_k^T Q x_k + u_k^T R u_k\right) + x_N^T P x_N

subject to x0=xx_0 = x, xk+1=Axk+Bukx_{k+1} = A x_k + B u_k and the constraints, or the report that no input sequence meets the constraints. The map κN(x)=u0∗(x)\kappa_N(x) = u_0^*(x) is the MPC law. The set of xx for which the problem has a solution is the feasible set XN\mathcal{X}_N.

Condensed form. Stack U=(u0,…,uN−1)∈RNmU = (u_0, \dots, u_{N-1}) \in \mathbb{R}^{Nm} and X=(x1,…,xN)X = (x_1, \dots, x_N). The model gives X=Φx+ΓUX = \Phi x + \Gamma U, where block row kk of Φ\Phi is AkA^k and block (k,j)(k, j) of Γ\Gamma is Ak−1−jBA^{k-1-j} B for j<kj < k and 0 otherwise. With Qˉ=diag(Q,…,Q,P)\bar Q = \mathrm{diag}(Q, \dots, Q, P) and Rˉ=diag(R,…,R)\bar R = \mathrm{diag}(R, \dots, R),

J=UTHU+2(Fx)TU+xT(Q+ΦTQˉΦ)x,H=ΓTQˉΓ+Rˉ,F=ΓTQˉΦ.J = U^T H U + 2 (F x)^T U + x^T (Q + \Phi^T \bar Q \Phi) x, \qquad H = \Gamma^T \bar Q \Gamma + \bar R, \qquad F = \Gamma^T \bar Q \Phi.

All constraints become GU≤w+ExG U \le w + E x, with one row per bound. So each sampling instant solves

min⁡U 12UTHU+(Fx)TUsubject toGU≤w+Ex,\min_U \ \tfrac12 U^T H U + (F x)^T U \quad \text{subject to} \quad G U \le w + E x,

which has the same minimizer as JJ. H≥Rˉ>0H \ge \bar R > 0, so the QP is strictly convex and has exactly one solution when it is feasible.

Sparse form. Keep the states as variables instead. The QP then has N(n+m)N (n + m) variables, the NnN n equality constraints xk+1=Axk+Bukx_{k+1} = A x_k + B u_k, and the bounds as simple bounds. Its KKT matrix is block banded, which is the reason that large horizons use this form.

The algorithm

  1. LINEAR-MPC-SETUP(A, B, Q, R, P, N, bounds, H_f, h_f) ▷ once, offline
  2. 1(Φ, Γ) ← prediction matrices, X = Φ x + Γ U
  3. 2H ← Γᵀ Q̄ Γ + R̄; F ← Γᵀ Q̄ Φ ▷ H is Nm × Nm and positive definite
  4. 3(G, w, E) ← one row per bound: G U ≤ w + E x
  5. MPC-STEP(x) ▷ at each sampling instant
  6. 4f ← F x; b ← w + E x
  7. 5(U, λ) ← QP-SOLVE(H, f, G, b)
  8. 6if QP-SOLVE reports infeasible then raise Infeasible
  9. 7return u_0 = U[1..m]
  10. QP-SOLVE(H, f, G, b) ▷ dual active set, Goldfarb and Idnani
  11. 8z ← -H⁻¹ f; W ← ∅; λ_W ← () ▷ unconstrained minimum
  12. 9repeat
  13. 10p ← the row with the largest violation s_p = g_pᵀ z - b_p
  14. 11if s_p ≤ tol then return (z, λ, W) ▷ z is primal feasible
  15. 12λ_p ← 0
  16. 13repeat
  17. 14r ← (N_Wᵀ H⁻¹ N_W)⁻¹ N_Wᵀ H⁻¹ g_p; d ← H⁻¹ (g_p - N_W r)
  18. 15t₁ ← min over k in W with r_k > 0 of λ_k / r_k ▷ partial step, ∞ if none
  19. 16t₂ ← (g_pᵀ z - b_p) / (g_pᵀ d) if g_pᵀ d > 0, else ∞ ▷ full step
  20. 17if t₁ = t₂ = ∞ then raise Infeasible
  21. 18t ← min(t₁, t₂); z ← z - t d; λ_W ← λ_W - t r; λ_p ← λ_p + t
  22. 19if t = t₂ then add p to W with λ_p and leave the inner loop
  23. 20else drop from W the row k that reached λ_k = 0

Lines L1 to L3 run once, because HH, FF, GG, ww and EE do not depend on the state. Line L4 is the only place where the measured state enters: it moves the linear term and the right-hand side. The columns of NWN_W are the rows gjg_j of GG for j∈Wj \in W.

The QP solver keeps a pair (z,W)(z, W) in which zz is the minimizer of the objective subject to the rows in WW held as equalities, with nonnegative multipliers λW\lambda_W. Line L8 starts at the unconstrained minimizer with WW empty, which is such a pair. Each pass of the outer loop picks a violated row pp (line L10). The inner loop moves zz along −d-d, the direction that reduces the violation of row pp and keeps the rows in WW as equalities, while it raises λp\lambda_p and changes λW\lambda_W along −r-r. The full step t2t_2 makes row pp hold with equality; the partial step t1t_1 stops when an active multiplier reaches 0, and that row is dropped (line L20). If neither step is finite, the violated row cannot be met together with the rows in WW, and the QP is infeasible (line L17). The method needs no feasible start, which is the reason it suits MPC: the unconstrained minimizer is the LQR plan, and in most instants only a few constraints are active.

Example

Take the double integrator sampled with h=1h = 1 s by zero-order hold: A=[1101]A = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}, B=[0.51]B = \begin{bmatrix} 0.5 \\ 1 \end{bmatrix}, with Q=IQ = I, R=1R = 1 and N=5N = 5. The terminal weight PP is the DARE solution

P=[2.3671011.1180341.1180342.587483],P12=5/2,K=[0.4344831.028466].P = \begin{bmatrix} 2.367101 & 1.118034 \\ 1.118034 & 2.587483 \end{bmatrix}, \qquad P_{12} = \sqrt 5 / 2, \qquad K = \begin{bmatrix} 0.434483 & 1.028466 \end{bmatrix}.

The constraints are ∣uk∣≤1|u_k| \le 1 and ∣xk,i∣≤5|x_{k,i}| \le 5, and the terminal set Xf\mathbb{X}_f is the maximal positively invariant set of x+=(A−BK)xx^+ = (A - BK) x inside these limits:

∣x1∣≤5,∣0.434483 x1+1.028466 x2∣≤1,∣0.106756 x1−0.181781 x2∣≤1.|x_1| \le 5, \qquad |0.434483\, x_1 + 1.028466\, x_2| \le 1, \qquad |0.106756\, x_1 - 0.181781\, x_2| \le 1.

QP size. The condensed QP has Nm=5N m = 5 variables and 36 rows: 10 input bounds, 20 state bounds and 6 terminal rows. The sparse form has 15 variables, 10 equalities and the same 36 inequalities. For N=3N = 3 the condensed QP has 3 variables and 24 rows; for N=10N = 10 it has 10 variables and 66 rows. The first row of HH is (86.5836,65.0636,45.5436,28.0236,13.5036)(86.5836, 65.0636, 45.5436, 28.0236, 13.5036).

One QP from x=(−5,3)x = (-5, 3). Line L8 gives the unconstrained plan z=(−0.9130,−1.0791,−0.6416,−0.2803,−0.0903)z = (-0.9130, -1.0791, -0.6416, -0.2803, -0.0903). Its first entry is the LQR input −Kx=−0.9130-K x = -0.9130, as it must be with PP from the DARE. Only one row is violated: u1≥−1u_1 \ge -1, by 0.07910.0791. One full step (lines L14 to L19) makes it active with λ=0.1643\lambda = 0.1643, and the next pass finds no violation. The result is

U∗=(−0.9516,−1,−0.6753,−0.2896,−0.0910),V5(x)=48.9369.U^* = (-0.9516, -1, -0.6753, -0.2896, -0.0910), \qquad V_5(x) = 48.9369.

The MPC input −0.9516-0.9516 differs from the LQR input −0.9130-0.9130: the plan knows that u1u_1 will saturate and pushes a little harder now. The KKT residual of the result is below 10−910^{-9}.

Other states. From x=(3,2)x = (3, 2) the unconstrained plan starts with u0=−3.3604u_0 = -3.3604. The solution has u0,u1,u2u_0, u_1, u_2 at −1-1, with multipliers 36.0336.03, 18.2418.24 and 6.216.21: U∗=(−1,−1,−1,−0.9267,0.6622)U^* = (-1, -1, -1, -0.9267, 0.6622) and V5=102.709V_5 = 102.709. From x=(−4.5,2)x = (-4.5, 2) no row is active, and the input is the LQR input −0.1018-0.1018 with V5=38.1591V_5 = 38.1591. From x=(4,2)x = (4, 2) the QP is infeasible: even u0=−1u_0 = -1 gives x1,1=4+2−0.5=5.5>5x_{1,1} = 4 + 2 - 0.5 = 5.5 > 5.

Closed loop from (−5,3)(-5, 3). Applying u0u_0 and solving again at each instant gives (measurement of the implementation):

kk xkx_k uku_k V5(xk)V_5(x_k) active rows
0 (−5,3)(-5, 3) −0.9516-0.9516 48.9369 u1≥−1u_1 \ge -1
1 (−2.4758,2.0484)(-2.4758, 2.0484) −1-1 14.0313 u0≥−1u_0 \ge -1
2 (−0.9274,1.0484)(-0.9274, 1.0484) −0.6753-0.6753 2.7058 none
3 (−0.2167,0.3731)(-0.2167, 0.3731) −0.2896-0.2896 0.2906 none
4 (0.0116,0.0835)(0.0116, 0.0835) −0.0910-0.0910 0.0205 none

From k=2k = 2 on no constraint is active and uk=−Kxku_k = -K x_k. Each value drops by at least the stage cost xkTQxk+ukTRukx_k^T Q x_k + u_k^T R u_k, as the MPC stability theorem says, and the state goes to the origin while every constraint holds.

Correctness

The full proofs are in proofs/correctness.md. There are three parts.

  1. The condensed QP is the MPC problem. By induction on kk, xk=Akx+∑j<kAk−1−jBujx_k = A^k x + \sum_{j<k} A^{k-1-j} B u_j, which is block row kk of Φx+ΓU\Phi x + \Gamma U. Substituting it into the cost and the constraints gives the formulas for HH, FF, GG, ww and EE above. H≥Rˉ>0H \ge \bar R > 0 because ΓTQˉΓ≥0\Gamma^T \bar Q \Gamma \ge 0. So the QP has at most one minimizer, and JJ and the QP objective differ by a positive factor and a constant.
  2. The QP solver returns the minimizer or a correct infeasibility report. The invariant is that zz minimizes the objective subject to the rows in WW as equalities, with λW≥0\lambda_W \ge 0. A full step adds row pp and keeps the invariant, a partial step drops a row whose multiplier reached 0, and each full step increases the dual objective strictly, so no active set repeats and the method stops. When it stops at line L11, zz is feasible and the pair (z,λ)(z, \lambda) meets the KKT conditions, which for a convex QP prove optimality. When it stops at line L17, a Farkas-type argument shows that the rows in WW and row pp have no common point. This is the proof of Goldfarb and Idnani (1983), written out in the proof file. The tests check the KKT residual at random states, and compare the solver with a brute force over all active sets on small random QPs.
  3. The closed loop. If Xf\mathbb{X}_f is positively invariant under u=−Kxu = -K x, the constraints hold in it, and PP satisfies P=Q+KTRK+(A−BK)TP(A−BK)P = Q + K^T R K + (A - BK)^T P (A - BK), then the shifted plan (u1∗,…,uN−1∗,−KxN∗)(u_1^*, \dots, u_{N-1}^*, -K x_N^*) is feasible at the next state and VN(x+)≤VN(x)−xTQx−u0TRu0V_N(x^+) \le V_N(x) - x^T Q x - u_0^T R u_0. This is the argument of the MPC stability theorem, and it gives recursive feasibility. The DARE solution PP with its gain KK meets the Lyapunov identity.
Proof: The condensed QP is the MPC problem, the dual active set method solves it or proves it infeasible, and the receding horizon loop decreases the valuefull

The plant is xk+1=Axk+Bukx_{k+1} = A x_k + B u_k with x∈Rnx \in \mathbb{R}^n and u∈Rmu \in \mathbb{R}^m. The weights are Q=QT≥0Q = Q^T \ge 0, R=RT>0R = R^T > 0 and P=PT≥0P = P^T \ge 0. The horizon cost of the input sequence U=(u0,…,uN−1)U = (u_0, \dots, u_{N-1}) from x0x_0 is

J(x0,U)=∑k=0N−1(xkTQxk+ukTRuk)+xNTPxN.J(x_0, U) = \sum_{k=0}^{N-1} (x_k^T Q x_k + u_k^T R u_k) + x_N^T P x_N.

The proof has three parts. Part 1 shows that the QP built in lines L1 to L4 is the MPC problem. Part 2 shows that the QP solver of lines L8 to L20 returns the unique minimizer or correctly reports that no feasible point exists. Part 3 shows what the receding horizon loop of lines L5 to L7 gives when the terminal ingredients are chosen as on the page. Parts 1 and 2 are in exact arithmetic; the code adds a tolerance to each sign test.

Part 1: the condensed form

Lemma 1. Let X=(x1,…,xN)X = (x_1, \dots, x_N). Then X=Φx0+ΓUX = \Phi x_0 + \Gamma U, where block row kk of Φ\Phi is AkA^k and block (k,j)(k, j) of Γ\Gamma is Ak−1−jBA^{k-1-j} B for j<kj < k and 0 otherwise.

Proof. Induction on kk: x1=Ax0+Bu0x_1 = A x_0 + B u_0, and if xk=Akx0+∑j<kAk−1−jBujx_k = A^k x_0 + \sum_{j<k} A^{k-1-j} B u_j then xk+1=Axk+Buk=Ak+1x0+∑j<k+1Ak−jBujx_{k+1} = A x_k + B u_k = A^{k+1} x_0 + \sum_{j<k+1} A^{k-j} B u_j. □\square

Lemma 2. With Qˉ=diag(Q,…,Q,P)\bar Q = \mathrm{diag}(Q, \dots, Q, P), Rˉ=diag(R,…,R)\bar R = \mathrm{diag}(R, \dots, R), H=ΓTQˉΓ+RˉH = \Gamma^T \bar Q \Gamma + \bar R and F=ΓTQˉΦF = \Gamma^T \bar Q \Phi,

J(x0,U)=UTHU+2(Fx0)TU+x0T(Q+ΦTQˉΦ)x0,J(x_0, U) = U^T H U + 2 (F x_0)^T U + x_0^T (Q + \Phi^T \bar Q \Phi) x_0,

and HH is positive definite.

Proof. J=x0TQx0+XTQˉX+UTRˉUJ = x_0^T Q x_0 + X^T \bar Q X + U^T \bar R U. Substitute Lemma 1 and expand (Φx0+ΓU)TQˉ(Φx0+ΓU)(\Phi x_0 + \Gamma U)^T \bar Q (\Phi x_0 + \Gamma U). For HH: UTHU=(ΓU)TQˉ(ΓU)+UTRˉU≥UTRˉU>0U^T H U = (\Gamma U)^T \bar Q (\Gamma U) + U^T \bar R U \ge U^T \bar R U > 0 for U≠0U \ne 0, since Qˉ≥0\bar Q \ge 0 and Rˉ>0\bar R > 0. □\square

The last term does not depend on UU. So minimizing J(x0,⋅)J(x_0, \cdot) is the same as minimizing 12UTHU+(Fx0)TU\frac12 U^T H U + (F x_0)^T U, which is the objective of line L5 with f=Fx0f = F x_0 from line L4.

Lemma 3. The rows built in line L3 describe the constraints: UU satisfies umin⁡≤uk≤umax⁡u_{\min} \le u_k \le u_{\max} for k<Nk < N, xmin⁡≤xk≤xmax⁡x_{\min} \le x_k \le x_{\max} for 1≤k≤N1 \le k \le N and HfxN≤hfH_f x_N \le h_f if and only if GU≤w+Ex0G U \le w + E x_0.

Proof. The input rows are the coordinate rows of UU with E=0E = 0. For the state rows, row rr of XX is Φrx0+ΓrU\Phi_r x_0 + \Gamma_r U by Lemma 1, so Xr≤xmax⁡,iX_r \le x_{\max, i} is ΓrU≤xmax⁡,i−Φrx0\Gamma_r U \le x_{\max, i} - \Phi_r x_0, which is the row stored; the lower bound is the same with the signs changed. The terminal rows use the last block row of Φ\Phi and Γ\Gamma in the same way. □\square

Part 2: the dual active set method

Write the QP as: minimize ϕ(z)=12zTHz+fTz\phi(z) = \frac12 z^T H z + f^T z subject to giTz≤big_i^T z \le b_i for i=1,…,qi = 1, \dots, q, with H>0H > 0. The KKT conditions are

Hz+f+∑iλigi=0,giTz≤bi,λi≥0,λi(bi−giTz)=0.H z + f + \textstyle\sum_i \lambda_i g_i = 0, \quad g_i^T z \le b_i, \quad \lambda_i \ge 0, \quad \lambda_i (b_i - g_i^T z) = 0.

Because ϕ\phi is strictly convex and the constraints are affine, a point satisfies them if and only if it is the unique minimizer.

For a set WW of constraint indices with linearly independent rows, let NWN_W be the matrix with the columns gjg_j, j∈Wj \in W. Call (z,W)(z, W) a solution pair if gjTz=bjg_j^T z = b_j for j∈Wj \in W and Hz+f+NWλW=0H z + f + N_W \lambda_W = 0 with λW≥0\lambda_W \ge 0. Then zz is the minimizer of ϕ\phi on the affine set {z:gjTz=bj,j∈W}\{z : g_j^T z = b_j, j \in W\}, so ϕ(z)\phi(z) depends on WW only. Line L8 starts with the solution pair (−H−1f,∅)(-H^{-1} f, \emptyset).

Invariant of the inner loop. At line L13 the current values satisfy

Hz+f+NWλW+λpgp=0,gjTz=bj (j∈W),λW≥0,λp≥0,gpTz>bp,H z + f + N_W \lambda_W + \lambda_p g_p = 0, \quad g_j^T z = b_j \ (j \in W), \quad \lambda_W \ge 0, \quad \lambda_p \ge 0, \quad g_p^T z > b_p,

and the columns of NWN_W are linearly independent. At the first entry λp=0\lambda_p = 0 (line L12) and this is the solution pair condition plus the choice of a violated pp (lines L10 and L11).

Lemma 4 (the step). Line L14 computes r=(NWTH−1NW)−1NWTH−1gpr = (N_W^T H^{-1} N_W)^{-1} N_W^T H^{-1} g_p and d=H−1(gp−NWr)d = H^{-1}(g_p - N_W r). Then NWTd=0N_W^T d = 0, Hd+NWr=gpH d + N_W r = g_p and gpTd=(gp−NWr)TH−1(gp−NWr)≥0g_p^T d = (g_p - N_W r)^T H^{-1} (g_p - N_W r) \ge 0, with equality if and only if gpg_p is a combination of the columns of NWN_W, and then d=0d = 0. For every t≥0t \ge 0, the update z←z−tdz \leftarrow z - t d, λW←λW−tr\lambda_W \leftarrow \lambda_W - t r, λp←λp+t\lambda_p \leftarrow \lambda_p + t keeps the stationarity equation and the equalities on WW, and changes the objective by

ϕ(z−td)−ϕ(z)=t gpTd (λp+t/2).\phi(z - t d) - \phi(z) = t \, g_p^T d \, (\lambda_p + t/2).

Proof. The matrix NWTH−1NWN_W^T H^{-1} N_W is positive definite because the columns are independent, so rr exists. NWTd=NWTH−1gp−(NWTH−1NW)r=0N_W^T d = N_W^T H^{-1} g_p - (N_W^T H^{-1} N_W) r = 0. The identity Hd+NWr=gpH d + N_W r = g_p is the definition of dd. Since NWTd=0N_W^T d = 0, gpTd=(gp−NWr)Tdg_p^T d = (g_p - N_W r)^T d, which is the stated quadratic form; it is 0 only if gp=NWrg_p = N_W r, and then d=H−10=0d = H^{-1} 0 = 0. The stationarity residual changes by −t(Hd+NWr−gp)=0-t (H d + N_W r - g_p) = 0, and gjT(z−td)=gjTzg_j^T (z - t d) = g_j^T z for j∈Wj \in W. For the objective, ∇ϕ(z)=Hz+f=−NWλW−λpgp\nabla \phi(z) = H z + f = -N_W \lambda_W - \lambda_p g_p, so

ϕ(z−td)−ϕ(z)=−tdT∇ϕ(z)+12t2dTHd=tλpgpTd+12t2gpTd,\phi(z - t d) - \phi(z) = -t d^T \nabla \phi(z) + \tfrac12 t^2 d^T H d = t \lambda_p g_p^T d + \tfrac12 t^2 g_p^T d,

using dTNW=0d^T N_W = 0 and dTHd=dT(gp−NWr)=gpTdd^T H d = d^T (g_p - N_W r) = g_p^T d. □\square

The step length (lines L15 to L18) is t=min⁡(t1,t2)t = \min(t_1, t_2), where t1=min⁡{λk/rk:rk>0}t_1 = \min\{\lambda_k / r_k : r_k > 0\} is the largest step that keeps λW≥0\lambda_W \ge 0, and t2=(gpTz−bp)/gpTdt_2 = (g_p^T z - b_p) / g_p^T d is the step that makes constraint pp active (t2=∞t_2 = \infty if gpTd=0g_p^T d = 0). The value gpTz−bpg_p^T z - b_p decreases by t gpTdt \, g_p^T d, so for t≤t2t \le t_2 constraint pp stays violated or becomes active, and the invariant holds after the update, except for the last condition when t=t2t = t_2.

Lemma 5 (infeasibility). If t1=t2=∞t_1 = t_2 = \infty (line L17), the QP has no feasible point.

Proof. t2=∞t_2 = \infty means gpTd=0g_p^T d = 0, so gp=NWrg_p = N_W r by Lemma 4. t1=∞t_1 = \infty means rk≤0r_k \le 0 for all kk. Let z^\hat z be any point with gjTz^≤bjg_j^T \hat z \le b_j for j∈Wj \in W. Then

gpTz^=∑krkgkTz^≥∑krkbk=∑krkgkTz=gpTz>bp,g_p^T \hat z = \textstyle\sum_{k} r_k g_k^T \hat z \ge \sum_k r_k b_k = \sum_k r_k g_k^T z = g_p^T z > b_p,

where the inequality uses rk≤0r_k \le 0, the middle equality uses gkTz=bkg_k^T z = b_k on WW, and the last step is the invariant. So no point satisfies the constraints in W∪{p}W \cup \{p\}. □\square

Lemma 6 (the two kinds of step). If t=t2t = t_2 (a full step, line L19), then pp joins WW, the columns stay independent, and (z,W∪{p})(z, W \cup \{p\}) is a solution pair with a strictly larger objective than the solution pair at the start of the outer iteration. If t=t1<t2t = t_1 < t_2 (a partial step, line L20), the index k1k_1 with λk1=0\lambda_{k_1} = 0 leaves WW, the invariant still holds, and ∣W∣|W| decreases.

Proof. Full step: t2<∞t_2 < \infty gives gpTd>0g_p^T d > 0, so gpg_p is not in the span of NWN_W, and the new columns are independent. After the step gpTz=bpg_p^T z = b_p, $\lambda_p = $ old λp+t≥0\lambda_p + t \ge 0 and λW≥0\lambda_W \ge 0 by t≤t1t \le t_1; stationarity holds by Lemma 4, so this is a solution pair. Along the inner loop the objective never decreases by Lemma 4, since t≥0t \ge 0, gpTd≥0g_p^T d \ge 0 and λp≥0\lambda_p \ge 0. In the full step t=t2>0t = t_2 > 0 because constraint pp is violated before it, and gpTd>0g_p^T d > 0, so this step increases ϕ\phi strictly. Partial step: λk1−t1rk1=0\lambda_{k_1} - t_1 r_{k_1} = 0, so removing k1k_1 from WW does not change NWλWN_W \lambda_W, and the stationarity equation, the equalities on the remaining set and the signs still hold. A subset of independent columns is independent. □\square

Theorem. In exact arithmetic the method stops after finitely many steps. It either reports infeasibility, and then the QP has no feasible point, or returns (z,λ)(z, \lambda) satisfying the KKT conditions, so zz is the unique minimizer.

Proof. Each inner loop ends with a full step or with the infeasible report after at most ∣W∣≤|W| \le (number of variables) partial steps, by Lemma 6. Each full step gives a solution pair whose objective is strictly larger than the previous one. The objective of a solution pair depends only on its set WW, so no set repeats, and there are finitely many sets. So the outer loop runs finitely often. The infeasible report is correct by Lemma 5. When the outer loop stops at line L11, no constraint is violated, so zz is feasible; the solution pair gives stationarity and λ≥0\lambda \ge 0 with λi=0\lambda_i = 0 off WW and giTz=big_i^T z = b_i on WW, which is complementarity. □\square

Part 3: the receding horizon loop

Line L7 returns the first mm entries of the minimizer U∗(x)U^*(x), so the controller is κN(x)=u0∗(x)\kappa_N(x) = u_0^*(x) and the value is VN(x)=J(x,U∗(x))V_N(x) = J(x, U^*(x)). Let KK and PP come from the DARE P=ATPA−ATPB(R+BTPB)−1BTPA+QP = A^T P A - A^T P B (R + B^T P B)^{-1} B^T P A + Q with K=(R+BTPB)−1BTPAK = (R + B^T P B)^{-1} B^T P A and AK=A−BKA_K = A - B K Schur. Let Xf={x:Hfx≤hf}X_f = \{x : H_f x \le h_f\} be a set with AKXf⊆XfA_K X_f \subseteq X_f, and such that every x∈Xfx \in X_f satisfies the state box and −Kx-K x satisfies the input box (the maximal positively invariant set of AKA_K under these constraints is such a set).

Lemma 7. If the QP is feasible at xx, then it is feasible at x+=Ax+BκN(x)x^+ = A x + B \kappa_N(x) and

VN(x+)≤VN(x)−(xTQx+κN(x)TRκN(x)).V_N(x^+) \le V_N(x) - (x^T Q x + \kappa_N(x)^T R \kappa_N(x)).

Proof. Let U∗=(u0∗,…,uN−1∗)U^* = (u_0^*, \dots, u_{N-1}^*) with states x0=x,x1,…,xN∈Xfx_0 = x, x_1, \dots, x_N \in X_f. From x+=x1x^+ = x_1 take the shifted sequence U~=(u1∗,…,uN−1∗,−KxN)\tilde U = (u_1^*, \dots, u_{N-1}^*, -K x_N). Its states are x2,…,xN,AKxNx_2, \dots, x_N, A_K x_N. The inputs u1∗,…,uN−1∗u_1^*, \dots, u_{N-1}^* and the states x2,…,xNx_2, \dots, x_N satisfy the constraints because they did for U∗U^*. The input −KxN-K x_N and the state xNx_N satisfy the boxes because xN∈Xfx_N \in X_f, and AKxN∈XfA_K x_N \in X_f by invariance, so it also satisfies the state box and the terminal rows. So U~\tilde U is feasible and

J(x+,U~)=VN(x)−(xTQx+u0∗TRu0∗)+[xNTQxN+xNTKTRKxN+xNTAKTPAKxN−xNTPxN].J(x^+, \tilde U) = V_N(x) - (x^T Q x + u_0^{*T} R u_0^*) + \big[x_N^T Q x_N + x_N^T K^T R K x_N + x_N^T A_K^T P A_K x_N - x_N^T P x_N\big].

The DARE can be written P=Q+KTRK+AKTPAKP = Q + K^T R K + A_K^T P A_K, so the bracket is 0. Then VN(x+)≤J(x+,U~)V_N(x^+) \le J(x^+, \tilde U) gives the claim. □\square

So the set of states where the QP is feasible is positively invariant for the closed loop (recursive feasibility), and VNV_N decreases at each sampling instant by at least the stage cost. If Q>0Q > 0, summing the decrease gives ∑kxkTQxk≤VN(x0)<∞\sum_k x_k^T Q x_k \le V_N(x_0) < \infty, so xk→0x_k \to 0. The full stability statement, with the bounds on VNV_N needed for asymptotic stability, is on the MPC stability theorem page.

Complexity

Costs are in the real-RAM model, with nn states, mm inputs, horizon NN and cc constraint rows. For box limits on inputs and states, c=2Nm+2Nnc = 2 N m + 2 N n plus the terminal rows.

  • Offline (lines L1 to L3). The powers AkA^k cost O(Nn3)O(N n^3). ΓTQˉΓ\Gamma^T \bar Q \Gamma and ΓTQˉΦ\Gamma^T \bar Q \Phi cost O(N3n2m)O(N^3 n^2 m) by direct products, and a Cholesky factorization of HH costs O(N3m3)O(N^3 m^3). Together this is O(N3(n+m)3)O(N^3 (n + m)^3) at most.
  • Per sampling instant (lines L4 to L7). Line L4 costs O(Nmn+cn)O(N m n + c n). The QP is the main cost. With factorizations that are updated when a row enters or leaves WW, as in the Goldfarb and Idnani method, one iteration costs O(N2m2)O(N^2 m^2) for the update and O(cNm)O(c N m) to find the most violated row, so tt iterations cost O(t(cNm+N2m2))O(t (c N m + N^2 m^2)) per sampling instant. Finite termination is a theorem; the paper gives no polynomial bound on the number of iterations. For MPC the count is usually close to the number of rows that are active at the solution (rule of thumb). In the example below, one QP needs one full step.
  • The simple code. The implementation recomputes NWTH−1NWN_W^T H^{-1} N_W in every inner step, which costs O(∣W∣2N2m2)O(|W|^2 N^2 m^2) per step. That is enough for the small QPs of the examples.
  • Sparse form. With N(n+m)N(n+m) variables, a block banded factorization of the KKT matrix costs O(N(n+m)3)O(N (n + m)^3), linear in NN. An interior point method on the sparse form therefore costs O(N(n+m)3)O(N (n + m)^3) per iteration, and its number of iterations has a bound that grows with c\sqrt{c} and log⁡(1/ϵ)\log(1/\epsilon) for accuracy ϵ\epsilon.

Space: HH needs O(N2m2)O(N^2 m^2) and the constraint data O(c(Nm+n))O(c (N m + n)).

Properties

  • Strict convexity. For R>0R > 0 the QP has a unique solution for every feasible xx (theorem, from H>0H > 0).
  • Piecewise affine law. κN\kappa_N is continuous and piecewise affine on a partition of XN\mathcal{X}_N into polyhedra, and VNV_N is convex and piecewise quadratic (theorem, Bemporad, Morari, Dua and Pistikopoulos 2002; see explicit MPC and multiparametric quadratic programming).
  • LQR near the origin. If PP is the DARE solution and no constraint is active at the unconstrained plan, then κN(x)=−Kx\kappa_N(x) = -K x (theorem: the unconstrained plan of the finite horizon problem with terminal cost PP is uk=−Kxku_k = -K x_k, by the principle of optimality). In the example this holds from k=2k = 2.
  • Feasible set. XN\mathcal{X}_N is a polyhedron, the projection of the feasible set of (x,U)(x, U) on xx. It grows with NN when Xf\mathbb{X}_f is control invariant.
  • Closed-loop guarantees. They need the terminal ingredients: see MPC stability theorem and recursive feasibility. Without them a finite horizon MPC can lose feasibility or give a closed loop that is not asymptotically stable.

Variants and improvements

  • Sparse QP with a structured solver. Keep the states as variables and exploit the banded KKT matrix. The cost per iteration is linear in NN. Use it for long horizons or many states.
  • Interior point and first order methods. An interior point method has a polynomial iteration bound. Projected or accelerated gradient methods suit box constraints on inputs only, where the projection is a clip.
  • Warm start. Start an active set method from the active set of the previous instant, shifted by one step. It often saves iterations, because the active set changes little between instants (rule of thumb, no bound).
  • Explicit MPC. Solve the QP for all xx offline as a multiparametric QP, and evaluate a piecewise affine function online. See explicit MPC.
  • Input moves and tracking. Use Δuk=uk−uk−1\Delta u_k = u_k - u_{k-1} as variables and penalize them, or track a reference with the state and input targets of offset-free MPC.
  • Soft state constraints. Add slack variables with a linear and a quadratic penalty. An ℓ1\ell_1 penalty with a weight larger than the largest multiplier of the hard problem gives the hard solution whenever the hard problem is feasible (exact penalty theorem), and the QP stays feasible when it is not.
  • Robust variants. Tube MPC and min-max MPC handle bounded disturbances.

When to use it

Use it for a plant with a good linear model near the operating point, a few to a few hundred states, and hard limits on inputs or states that matter for performance. The sampling period must be long enough to solve the QP in the worst case; measure the solve time of the chosen solver on the target hardware. If no constraint is ever active, the infinite-horizon LQR gives the same law at a lower cost. If the model is nonlinear far from one operating point, use nonlinear MPC. For a step response model of an asymptotically stable plant, as in process control, DMC is the older form of the same idea.

Pitfalls

  • Infeasibility at run time. A disturbance can push the state out of XN\mathcal{X}_N, and the QP then has no solution. Plan for it: soften the state constraints, or keep a backup input. The example state (4,2)(4, 2) shows the case.
  • No terminal ingredients. With P=QP = Q and no terminal set, a short horizon can give a closed loop that is not asymptotically stable, even with no constraint active. Use the DARE terminal cost and an invariant terminal set, or check the closed loop.
  • Conditioning of the condensed form. For an AA that is not Schur, the powers AkA^k grow, HH becomes badly conditioned for long NN, and the condensed QP loses accuracy. Use the sparse form, or prestabilize with u=−Kx+vu = -K x + v and optimize vv.
  • Trusting the solver's flag. Check the result with the KKT conditions when you test a solver, as the tests here do. A solver that stops at its iteration limit can return a point that is not optimal.
  • State constraints at k=0k = 0. The current state is measured, not chosen. Constraints apply from k=1k = 1; a constraint at k=0k = 0 only makes the QP infeasible when it is violated.
  • Sampling time and delay. The QP takes time. If the solve uses a large part of the period, the input acts late. Model the delay as an extra state, or compute the plan for the predicted next state.
  • Constraint scaling. Rows with very different scales make the tolerance test at line L11 meaningless for some rows. Scale the constraints to similar magnitudes.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
linear_mpc.py 224 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-mpc/. The authors are listed in prov/R448P7.jsonl.

"""Linear MPC as a quadratic program, with a dual active set QP solver.

Plant: x_(k+1) = A x_k + B u_k, with x in R^n and u in R^m.
Cost over the horizon N:

    J = sum_(k=0)^(N-1) (x_k^T Q x_k + u_k^T R u_k) + x_N^T P x_N

Constraints, all optional: umin <= u_k <= umax for k = 0..N-1,
xmin <= x_k <= xmax for k = 1..N, and a terminal polytope Hf x_N <= hf.

The condensed form eliminates the states. With U = (u_0, ..., u_(N-1)) and
X = (x_1, ..., x_N) = Phi x_0 + Gamma U, the cost is

    J = U^T H U + 2 (F x_0)^T U + const,  H = Gamma^T Qbar Gamma + Rbar,
    F = Gamma^T Qbar Phi,  Qbar = diag(Q, ..., Q, P),  Rbar = diag(R, ..., R),

and the constraints are G U <= w + E x_0. Each sampling instant solves the
QP min 1/2 U^T H U + (F x_0)^T U subject to G U <= w + E x_0 and applies
the first input u_0. H must be positive definite (R > 0 is enough).

The QP solver is the dual active set method of Goldfarb and Idnani (1983).
It starts from the unconstrained minimum and adds violated constraints one
at a time, keeping the multipliers of the active set nonnegative. It needs
no feasible starting point and it detects an infeasible QP.
"""

from ctlmat import mat_power, matvec, mul, solve, transpose, zeros

__all__ = ["condense", "constraints", "qp_solve", "LinearMPC", "Infeasible", "kkt_residual"]


class Infeasible(Exception):
    """The QP has no feasible point."""


def _blockdiag(blocks):
    size = sum(len(b) for b in blocks)
    out = zeros(size)
    o = 0
    for b in blocks:
        for i, row in enumerate(b):
            for j, v in enumerate(row):
                out[o + i][o + j] = v
        o += len(b)
    return out


def condense(A, B, Q, R, P, N):
    """Return Phi, Gamma, H and F of the condensed form (see the module notes)."""
    n, m = len(A), len(B[0])
    powers = [mat_power(A, k) for k in range(N + 1)]
    phi = [row for k in range(1, N + 1) for row in powers[k]]
    gamma = zeros(N * n, N * m)
    for k in range(1, N + 1):  # x_k = A^k x_0 + sum_(j<k) A^(k-1-j) B u_j
        for j in range(k):
            blk = mul(powers[k - 1 - j], B)
            for i in range(n):
                for c in range(m):
                    gamma[(k - 1) * n + i][j * m + c] = blk[i][c]
    qbar = _blockdiag([Q] * (N - 1) + [P])
    rbar = _blockdiag([R] * N)
    gq = mul(transpose(gamma), qbar)
    H = mul(gq, gamma)
    for i in range(N * m):
        for j in range(N * m):
            H[i][j] += rbar[i][j]
    F = mul(gq, phi)
    return phi, gamma, H, F


def constraints(A, B, N, umin=None, umax=None, xmin=None, xmax=None, Hf=None, hf=None):
    """Return G, w, E with the constraints written as G U <= w + E x_0."""
    n, m = len(A), len(B[0])
    phi, gamma, _, _ = condense(A, B, [[0] * n for _ in range(n)], [[0] * m for _ in range(m)],
                                [[0] * n for _ in range(n)], N)
    G, w, E = [], [], []
    zero_n = [0] * n
    for k in range(N):
        for c in range(m):
            e = [0] * (N * m)
            e[k * m + c] = 1
            if umax is not None:
                G.append(e)
                w.append(umax[c])
                E.append(zero_n)
            if umin is not None:
                G.append([-v for v in e])
                w.append(-umin[c])
                E.append(zero_n)
    for k in range(1, N + 1):
        for i in range(n):
            r = (k - 1) * n + i
            if xmax is not None:  # Gamma_r U + Phi_r x_0 <= xmax_i
                G.append(list(gamma[r]))
                w.append(xmax[i])
                E.append([-v for v in phi[r]])
            if xmin is not None:
                G.append([-v for v in gamma[r]])
                w.append(-xmin[i])
                E.append(list(phi[r]))
    if Hf is not None:
        gN = gamma[(N - 1) * n:]
        pN = phi[(N - 1) * n:]
        for row, h in zip(Hf, hf):
            G.append(matvec(transpose(gN), row))
            w.append(h)
            E.append([-v for v in matvec(transpose(pN), row)])
    return G, w, E


def qp_solve(H, f, G, b, tol=1e-10, max_iter=500):
    """Minimize 1/2 z^T H z + f^T z subject to G z <= b, with H > 0.

    Dual active set method of Goldfarb and Idnani. Returns (z, lam, active),
    where lam has one multiplier per row of G (0 off the active set).
    Raises Infeasible if the constraints have no common point.
    """
    nz = len(H)
    Hinv = solve(H, [[1.0 if i == j else 0.0 for j in range(nz)] for i in range(nz)])
    z = [-v for v in matvec(Hinv, f)]  # @line L8
    W, lamW = [], []
    for _ in range(max_iter):  # @line L9
        s = [sum(gi * zi for gi, zi in zip(G[i], z)) - b[i] for i in range(len(G))]
        p = max(range(len(G)), key=lambda i: s[i]) if G else None  # @line L10
        if p is None or s[p] <= tol * (1.0 + abs(b[p])):  # @line L11
            lam = [0.0] * len(G)
            for j, v in zip(W, lamW):
                lam[j] = v
            return z, lam, sorted(W)
        lam_p = 0.0  # @line L12
        while True:  # @line L13
            gp = G[p]
            hg = matvec(Hinv, gp)
            if W:  # @line L14
                Nt = [G[j] for j in W]
                M = [[sum(a * c for a, c in zip(G[i], matvec(Hinv, G[j]))) for j in W] for i in W]
                r = solve(M, [sum(a * c for a, c in zip(row, hg)) for row in Nt])
                Ntr = [sum(Nt[k][i] * r[k] for k in range(len(W))) for i in range(nz)]
                d = matvec(Hinv, [gp[i] - Ntr[i] for i in range(nz)])
            else:
                r = []
                d = hg
            t1, k1 = float("inf"), None  # @line L15
            for k, rk in enumerate(r):
                if rk > tol and lamW[k] / rk < t1:
                    t1, k1 = lamW[k] / rk, k
            gd = sum(a * c for a, c in zip(gp, d))
            viol = sum(a * c for a, c in zip(gp, z)) - b[p]
            t2 = viol / gd if gd > tol * tol else float("inf")  # @line L16
            if t1 == float("inf") and t2 == float("inf"):  # @line L17
                raise Infeasible("the QP constraints have no common point")
            t = min(t1, t2)  # @line L18
            if t2 < float("inf"):
                z = [zi - t * di for zi, di in zip(z, d)]
            lamW = [lk - t * rk for lk, rk in zip(lamW, r)]
            lam_p += t
            if t2 <= t1:  # @line L19
                W.append(p)
                lamW.append(lam_p)
                break
            del W[k1]  # @line L20
            del lamW[k1]
    raise RuntimeError("qp_solve: no convergence")


def kkt_residual(H, f, G, b, z, lam):
    """Return the largest violation of the KKT conditions of the QP.

    Stationarity H z + f + G^T lam = 0, primal feasibility G z <= b, dual
    feasibility lam >= 0, and complementarity lam_i (b_i - g_i^T z) = 0.
    """
    hz = matvec(H, z)
    gl = matvec(transpose(G), lam) if G else [0.0] * len(z)
    worst = max(abs(hz[i] + f[i] + gl[i]) for i in range(len(z)))
    for i in range(len(G)):
        slack = b[i] - sum(a * c for a, c in zip(G[i], z))
        worst = max(worst, -slack, -lam[i], abs(lam[i] * slack))
    return worst


class LinearMPC:
    """Receding horizon controller u = kappa_N(x) for a linear plant."""

    def __init__(self, A, B, Q, R, P, N, **cons):
        self.n, self.m, self.N = len(A), len(B[0]), N
        self.phi, self.gamma, H, F = condense(A, B, Q, R, P, N)  # @line L1
        self.H = [[float(v) for v in row] for row in H]  # @line L2
        self.F = [[float(v) for v in row] for row in F]
        G, w, E = constraints(A, B, N, **cons)  # @line L3
        self.G = [[float(v) for v in row] for row in G]
        self.w = [float(v) for v in w]
        self.E = [[float(v) for v in row] for row in E]

    def qp_data(self, x):
        """Return f and b of the QP for the current state x."""
        f = matvec(self.F, x)  # @line L4
        b = [wi + sum(e * xi for e, xi in zip(ei, x)) for wi, ei in zip(self.w, self.E)]
        return f, b

    def solve(self, x):
        """Return the optimal input sequence U and the multipliers for state x."""
        f, b = self.qp_data(x)
        z, lam, _ = qp_solve(self.H, f, self.G, b)  # @line L5
        return z, lam

    def step(self, x):
        """Return the first input u_0 of the optimal sequence (raise Infeasible if none)."""
        z, _ = self.solve(x)  # @line L6
        return z[: self.m]  # @line L7

    def cost(self, x, U, Q, R, P, A, B):
        """Return the horizon cost of the input sequence U from x."""
        n, m = self.n, self.m
        J = 0.0
        xk = list(x)
        for k in range(self.N):
            uk = U[k * m:(k + 1) * m]
            J += sum(xk[i] * Q[i][j] * xk[j] for i in range(n) for j in range(n))
            J += sum(uk[i] * R[i][j] * uk[j] for i in range(m) for j in range(m))
            xk = [a + c for a, c in zip(matvec(A, xk), matvec(B, uk))]
        return J + sum(xk[i] * P[i][j] * xk[j] for i in range(n) for j in range(n))
test_linear_mpc.py 198 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-mpc/. The authors are listed in prov/R448P7.jsonl.

import itertools
import random

import pytest

import ctlmat as cm
from linear_mpc import Infeasible, LinearMPC, condense, kkt_residual, qp_solve

# Double integrator sampled with h = 1 s (zero-order hold), Q = I, R = 1.
A = [[1.0, 1.0], [0.0, 1.0]]
B = [[0.5], [1.0]]
Q = [[1.0, 0.0], [0.0, 1.0]]
R = [[1.0]]


def dare(A, B, Q, R, iters=400):
    P = [row[:] for row in Q]
    for _ in range(iters):
        S = cm.add(R, cm.mul(cm.transpose(B), cm.mul(P, B)))
        K = cm.solve(S, cm.mul(cm.transpose(B), cm.mul(P, A)))
        P = cm.sub(cm.add(Q, cm.mul(cm.transpose(A), cm.mul(P, A))),
                   cm.mul(cm.transpose(A), cm.mul(cm.mul(P, B), K)))
    return P, K


P, K = dare(A, B, Q, R)
AK = cm.sub(A, cm.mul(B, K))
KA = cm.mul(K, AK)
# Terminal set: the maximal admissible set of x+ = (A - B K) x with |x_1| <= 5,
# |x_2| <= 5 and |K x| <= 1 (see the maximal-positively-invariant-set page).
HF = [[1.0, 0.0], [-1.0, 0.0], K[0], [-v for v in K[0]], KA[0], [-v for v in KA[0]]]
HFB = [5.0, 5.0, 1.0, 1.0, 1.0, 1.0]
CONS = dict(umin=[-1.0], umax=[1.0], xmin=[-5.0, -5.0], xmax=[5.0, 5.0], Hf=HF, hf=HFB)


def step(x, u):
    return [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]


def stage(x, u):
    return x[0] ** 2 + x[1] ** 2 + u[0] ** 2


def brute_qp(H, f, G, b, tol=1e-9):
    """Enumerate active sets; return the KKT point (unique because H > 0)."""
    nz = len(H)
    best = None
    for size in range(0, nz + 1):
        for S in itertools.combinations(range(len(G)), size):
            kkt = [H[i] + [G[j][i] for j in S] for i in range(nz)]
            kkt += [G[j] + [0.0] * size for j in S]
            rhs = [-v for v in f] + [b[j] for j in S]
            try:
                sol = cm.solve(kkt, rhs)
            except ValueError:
                continue
            z, lam = sol[:nz], sol[nz:]
            if any(l < -tol for l in lam):
                continue
            if any(sum(g * zi for g, zi in zip(G[i], z)) > b[i] + tol for i in range(len(G))):
                continue
            best = z
            return best
    return best


def test_condensed_prediction_matches_simulation():
    rng = random.Random(1)
    N = 6
    phi, gamma, H, F = condense(A, B, Q, R, P, N)
    for _ in range(20):
        x0 = [rng.uniform(-3, 3) for _ in range(2)]
        U = [rng.uniform(-1, 1) for _ in range(N)]
        X = [a + b for a, b in zip(cm.matvec(phi, x0), cm.matvec(gamma, U))]
        x = x0
        for k in range(N):
            x = step(x, [U[k]])
            assert abs(X[2 * k] - x[0]) < 1e-12 and abs(X[2 * k + 1] - x[1]) < 1e-12


def test_condensed_cost_is_the_horizon_cost():
    rng = random.Random(2)
    N = 4
    mpc = LinearMPC(A, B, Q, R, P, N)
    for _ in range(20):
        x0 = [rng.uniform(-3, 3) for _ in range(2)]
        U = [rng.uniform(-1, 1) for _ in range(N)]
        quad = sum(U[i] * mpc.H[i][j] * U[j] for i in range(N) for j in range(N))
        lin = 2 * sum(u * v for u, v in zip(U, cm.matvec(mpc.F, x0)))
        const = mpc.cost(x0, [0.0] * N, Q, R, P, A, B)
        assert abs(quad + lin + const - mpc.cost(x0, U, Q, R, P, A, B)) < 1e-9


def test_qp_against_brute_force_on_random_problems():
    rng = random.Random(3)
    for _ in range(60):
        nz = rng.randint(1, 3)
        M = [[rng.uniform(-1, 1) for _ in range(nz)] for _ in range(nz)]
        H = cm.add(cm.mul(cm.transpose(M), M), [[0.2 if i == j else 0.0 for j in range(nz)] for i in range(nz)])
        f = [rng.uniform(-2, 2) for _ in range(nz)]
        nc = rng.randint(1, 6)
        G = [[rng.uniform(-1, 1) for _ in range(nz)] for _ in range(nc)]
        b = [rng.uniform(0.0, 1.0) for _ in range(nc)]  # z = 0 is feasible
        z, lam, _ = qp_solve(H, f, G, b)
        assert kkt_residual(H, f, G, b, z, lam) < 1e-9
        zb = brute_qp(H, f, G, b)
        assert zb is not None
        assert max(abs(u - v) for u, v in zip(z, zb)) < 1e-7


def test_qp_detects_infeasible_constraints():
    H = [[1.0, 0.0], [0.0, 1.0]]
    f = [0.0, 0.0]
    G = [[1.0, 0.0], [-1.0, 0.0], [0.0, 1.0]]
    b = [-1.0, -1.0, 5.0]  # z_1 <= -1 and z_1 >= 1
    with pytest.raises(Infeasible):
        qp_solve(H, f, G, b)


def test_mpc_equals_lqr_near_the_origin():
    rng = random.Random(4)
    mpc = LinearMPC(A, B, Q, R, P, 5, **CONS)
    for _ in range(20):
        x0 = [rng.uniform(-0.5, 0.5) for _ in range(2)]
        u = mpc.step(x0)[0]
        assert abs(u + K[0][0] * x0[0] + K[0][1] * x0[1]) < 1e-9


def test_example_numbers():
    mpc = LinearMPC(A, B, Q, R, P, 5, **CONS)
    assert len(mpc.H) == 5 and len(mpc.G) == 36
    U, lam = mpc.solve([-5.0, 3.0])
    want = [-0.9516, -1.0, -0.6753, -0.2896, -0.0910]
    assert max(abs(u - w) for u, w in zip(U, want)) < 5e-5
    assert [i for i, l in enumerate(lam) if l > 1e-9] == [3]  # u_1 >= -1 is active
    assert abs(mpc.cost([-5.0, 3.0], U, Q, R, P, A, B) - 48.9369) < 5e-5
    assert abs(P[0][1] - 5 ** 0.5 / 2) < 1e-12


def test_kkt_conditions_at_random_states():
    rng = random.Random(5)
    mpc = LinearMPC(A, B, Q, R, P, 6, **CONS)
    solved = 0
    for _ in range(40):
        x0 = [rng.uniform(-5, 5), rng.uniform(-3, 3)]
        f, b = mpc.qp_data(x0)
        try:
            z, lam, _ = qp_solve(mpc.H, f, mpc.G, b)
        except Infeasible:
            continue
        solved += 1
        assert kkt_residual(mpc.H, f, mpc.G, b, z, lam) < 1e-8
    assert solved >= 20


def test_infeasible_state():
    mpc = LinearMPC(A, B, Q, R, P, 5, **CONS)
    with pytest.raises(Infeasible):
        mpc.step([4.0, 2.0])  # even u = -1 gives x_1 = 5.5 > 5


def test_terminal_set_is_admissible_and_invariant():
    # vertices of the polygon by brute force over pairs of rows
    verts = []
    for i, j in itertools.combinations(range(len(HF)), 2):
        a1, a2 = HF[i], HF[j]
        d = a1[0] * a2[1] - a1[1] * a2[0]
        if abs(d) < 1e-12:
            continue
        v = [(HFB[i] * a2[1] - HFB[j] * a1[1]) / d, (a1[0] * HFB[j] - a2[0] * HFB[i]) / d]
        if all(r[0] * v[0] + r[1] * v[1] <= h + 1e-9 for r, h in zip(HF, HFB)):
            verts.append(v)
    assert len(verts) >= 6
    for v in verts:
        u = -(K[0][0] * v[0] + K[0][1] * v[1])
        assert abs(u) <= 1 + 1e-9 and abs(v[1]) <= 5 + 1e-9
        w = cm.matvec(AK, v)
        assert all(r[0] * w[0] + r[1] * w[1] <= h + 1e-9 for r, h in zip(HF, HFB))


def test_closed_loop_constraints_cost_decrease_and_convergence():
    mpc = LinearMPC(A, B, Q, R, P, 5, **CONS)
    x = [-5.0, 3.0]
    U, _ = mpc.solve(x)
    V = mpc.cost(x, U, Q, R, P, A, B)
    for _ in range(40):
        u = U[:1]
        assert -1 - 1e-9 <= u[0] <= 1 + 1e-9
        xn = step(x, u)
        assert all(abs(v) <= 5 + 1e-9 for v in xn)
        Un, _ = mpc.solve(xn)
        Vn = mpc.cost(xn, Un, Q, R, P, A, B)
        assert Vn <= V - stage(x, u) + 1e-8
        x, U, V = xn, Un, Vn
    assert max(abs(v) for v in x) < 1e-6

History

Predictive control with a step response model and an online optimization came from the process industry in the late 1970s; see dynamic matrix control for that history. García and Morshedi (1986) wrote the constrained DMC move problem as a quadratic program, which is the form on this page. Muske and Rawlings (1993) put linear MPC in state-space form, with a terminal cost that makes the finite horizon problem equal to an infinite horizon one when no constraint is active. Mayne, Rawlings, Rao and Scokaert (2000) collected the conditions on the terminal cost and the terminal set that give closed-loop stability. The dual active set method used here is that of Goldfarb and Idnani (1983).

References

  1. Carlos E. García and A. M. Morshedi, Quadratic programming solution of dynamic matrix control (QDMC), Chemical Engineering Communications 46(1-3), 73-87, 1986, the move problem of DMC with input and output constraints written as a quadratic program
  2. Kenneth R. Muske and James B. Rawlings, Model predictive control with linear models, AIChE Journal 39(2), 262-287, 1993, linear MPC in state-space form with an infinite horizon cost replaced by a terminal penalty
  3. D. Goldfarb and A. Idnani, A numerically stable dual method for solving strictly convex quadratic programs, Mathematical Programming 27(1), 1-33, 1983, the dual active set method that starts at the unconstrained minimum and adds violated constraints one at a time
  4. D. Q. Mayne, J. B. Rawlings, C. V. Rao and P. O. M. Scokaert, Constrained model predictive control, stability and optimality, Automatica 36(6), 789-814, 2000, the terminal cost and terminal set conditions for linear MPC and the decrease of the optimal cost
  5. Alberto Bemporad, Manfred Morari, Vivek Dua and Efstratios N. Pistikopoulos, The explicit linear quadratic regulator for constrained systems, Automatica 38(1), 3-20, 2002, the MPC law is continuous and piecewise affine and the value function is convex and piecewise quadratic
  6. James B. Rawlings, David Q. Mayne and Moritz M. Diehl, Model Predictive Control, Theory, Computation, and Design, 2nd edition, Nob Hill Publishing, 2017, Chapter 2, regulation, the linear quadratic problem with constraints
  7. Francesco Borrelli, Alberto Bemporad and Manfred Morari, Predictive Control for Linear and Hybrid Systems, Cambridge University Press, 2017, the chapters on constrained optimal control of linear systems with a quadratic cost and on receding horizon control, with the batch (condensed) formulation

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.offline
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example