Algorithm Search⌘K

Algorithmresearch

Tube MPC

Also called tube-based MPC.

Plans a nominal trajectory with tightened constraints and adds an ancillary feedback that keeps the true state in a tube around it despite bounded disturbances.

Time
O(I L^2) worst
Space
O(L^2) extra
Where
I = the number of simplex pivots; L = the number of variables and rows of the online LP, of order N (n + m + q) + r for q constraint rows per step and r facet rows of the error set; N = the horizon; m = the number of inputs; n = the number of states
Properties
deterministicexactonlineiterative
Origin
David Q. Mayne, María M. Seron, Saša V. Raković, 2005

Tube MPC is a robust form of model predictive control for a linear plant with a bounded additive disturbance. It splits the input into two parts: a nominal input vv from an MPC problem for the plant without disturbance, and an ancillary feedback K(x−z)K (x - z) on the error between the true state xx and the nominal state zz. With A+BKA + B K Schur, the error stays in a fixed robust positively invariant set ZZ, so the true state stays in a tube zk⊕Zz_k \oplus Z around the nominal trajectory. The nominal problem uses constraints tightened by ZZ, so every state in the tube meets the true constraints. The online problem has the size of a nominal MPC problem, it does not grow with the number of disturbance vertices, and the closed loop stays feasible and converges to ZZ.

In plain words

Plan the path as if there were no disturbance, but keep a safety distance from every limit. Then follow the plan with a simple correction: when the real state drifts from the plan, push it back in proportion to the drift. Because the disturbance is bounded and the correction is fixed, the drift never leaves a known region around the plan, which you can work out once, ahead of time. So the safety distance is that region's size, and the real state never crosses a limit. Each step only solves the small plan without disturbance, which is fast. The cost is a more cautious plan, because the safety distance is always kept.

The problem

Input: matrices A∈Rn×nA \in \mathbb{R}^{n \times n} and B∈Rn×mB \in \mathbb{R}^{n \times m}, a gain KK with AK=A+BKA_K = A + B K Schur, a disturbance set WW (a zonotope that contains 0 in its interior), state and input constraints XX and UU (polyhedra), a horizon NN, weights QQ and RR, and the current state xx.

The plant is xk+1=Axk+Buk+wkx_{k+1} = A x_k + B u_k + w_k with wk∈Ww_k \in W.

Output: an input u∈Uu \in U such that, when the same rule is applied at every sample, xk∈Xx_k \in X and uk∈Uu_k \in U for every disturbance sequence in WW, the problem stays feasible, and xkx_k tends to the error set ZZ.

The algorithm

  1. TUBE-MPC(A, B, K, W, X, U, N, Q, R, x₀)
  2. 1find s, α with A_Kˢ W ⊆ α W; Z ← (1 - α)⁻¹ (W ⊕ A_K W ⊕ ... ⊕ A_Kˢ⁻¹ W) ▷ offline
  3. 2X̄ ← X ⊖ Z, Ū ← U ⊖ K Z (each row bound b becomes b - h_Z(a)) ▷ offline
  4. 3for k = 0, 1, 2, ... do measure x
  5. 4rows: x - z₀ ∈ Z, z_{j+1} = A z_j + B v_j, z_j ∈ X̄, v_j ∈ Ū, z_N = 0
  6. 5solve the LP: minimize Σ_{j<N} (‖Q z_j‖₁ + ‖R v_j‖₁) over z₀, v₀, ..., v_{N-1}
  7. 6apply u = v₀ + K (x - z₀)

Line L1 follows Raković, Kerrigan, Kouramas and Mayne (2005). The Minkowski sum of zonotopes is the list of all their generators, so ZZ is a zonotope too. The test AKsW⊆αWA_K^s W \subseteq \alpha W compares support functions on the facet normals of WW. A smaller α\alpha gives a tighter ZZ and needs a larger ss.

Line L2 subtracts the support function of ZZ (or of KZK Z) from each row bound. For a zonotope, hZ(a)=∑j∣aTgj∣h_Z(a) = \sum_j |a^T g_j| over its generators.

Line L4 makes the first nominal state z0z_0 a free variable that only has to be within ZZ of the measured state. The rows of ZZ come from its facets: in Rn\mathbb{R}^n, each facet normal is orthogonal to n−1n - 1 generators. The terminal constraint zN=0z_N = 0 is the simplest choice; a larger terminal set that is positively invariant for the nominal loop works as well. With 1-norm costs the problem is an LP; with quadratic costs it is a QP of the same size.

Example

Take the double integrator with sample time 1, A=[1101]A = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}, B=[0.51]B = \begin{bmatrix} 0.5 \\ 1 \end{bmatrix}, with ∣w1∣≤0.1|w_1| \le 0.1 and ∣w2∣≤0.1|w_2| \le 0.1. The constraints are ∣x1∣≤5|x_1| \le 5, ∣x2∣≤1|x_2| \le 1 and ∣u∣≤1|u| \le 1. Choose the deadbeat gain K=[−1, −1.5]K = [-1, \ -1.5], so that

AK=[0.50.25−1−0.5],AK2=0.A_K = \begin{bmatrix} 0.5 & 0.25 \\ -1 & -0.5 \end{bmatrix}, \quad A_K^2 = 0.

The error set. Since AK2W={0}A_K^2 W = \{0\}, line L1 stops at s=2s = 2 with α=0\alpha = 0, and Z=W⊕AKWZ = W \oplus A_K W is exactly the minimal invariant set. It has the four generators (0.1,0)(0.1, 0), (0,0.1)(0, 0.1), (0.05,−0.1)(0.05, -0.1) and (0.025,−0.05)(0.025, -0.05), so ∣e1∣≤0.175|e_1| \le 0.175, ∣e2∣≤0.25|e_2| \le 0.25 and ∣Ke∣≤0.4|K e| \le 0.4 on ZZ. The tightened constraints are ∣z1∣≤4.825|z_1| \le 4.825, ∣z2∣≤0.75|z_2| \le 0.75 and ∣v∣≤0.6|v| \le 0.6.

One problem. With Q=IQ = I, R=1R = 1, N=6N = 6 and x=(−3,0)x = (-3, 0), the LP value is 51/451/4, and the first nominal state is z0=(−2.925,0.15)z_0 = (-2.925, 0.15), not xx itself. The nominal input is v0=0.6v_0 = 0.6 and the applied input is u=0.6+K(x−z0)=0.6+0.075+0.225=0.9u = 0.6 + K (x - z_0) = 0.6 + 0.075 + 0.225 = 0.9. With N=4N = 4 the problem is infeasible from this state: with ∣v∣≤0.6|v| \le 0.6 and ∣z2∣≤0.75|z_2| \le 0.75, the nominal state cannot reach the origin in 4 steps.

Closed loop. With no disturbance, the values are 12.7512.75, 8.6258.625, 5.06255.0625, 2.3752.375, 0.31250.3125, and then 0: the state reaches the origin at k=5k = 5. With the constant disturbance w=(0.1,0.1)w = (0.1, 0.1), z0z_0 becomes 0 at k=4k = 4 and the state settles at (0.175,−0.05)(0.175, -0.05), a point of ZZ. Under random vertex disturbances the state and the input stay within their limits at every step, and the state enters ZZ and stays there.

A gain that is not deadbeat. With K=[−0.5, −1]K = [-0.5, \ -1] the set ZZ is not finitely determined, and the choice of α\alpha trades the size of ZZ against the number of generators:

αmax⁡\alpha_{\max} ss α\alpha max ∣e1∣\lvert e_1 \rvert max ∣e2∣\lvert e_2 \rvert max ∣Ke∣\lvert K e \rvert
0.5 3 0.344 0.448 0.324 0.329
0.1 5 0.065 0.343 0.275 0.269
0.01 8 0.0084 0.336 0.268 0.258

This gain is softer than the deadbeat one: it needs less input margin, but the tube is wider in the position.

Correctness

The proof is in proofs/correctness.md. The error e=x−ze = x - z follows e+=AKe+we^+ = A_K e + w, whatever the nominal input is. The set of Raković and coauthors satisfies AKZ⊕W⊆ZA_K Z \oplus W \subseteq Z, because AKsW⊆αWA_K^s W \subseteq \alpha W lets the last term of the sum be absorbed into the scale factor. So once x−z0∈Zx - z_0 \in Z, the error stays in ZZ. A nominal state in X⊖ZX \ominus Z then gives a true state in XX, and the same holds for the input. At the next sample, the old plan shifted by one step, with v=0v = 0 appended, is feasible: its first state z1z_1 is within ZZ of the new measured state, and zN=0z_N = 0 stays at 0. So the problem stays feasible, and its value drops by at least the first stage cost. The sum of the stage costs is therefore finite, the first nominal state tends to 0, and the true state approaches ZZ.

Proof: The error set is robustly invariant, so the tube controller meets the constraints for every disturbance, stays feasible, and drives the state to the error setfull

Setting. The plant is x+=Ax+Bu+wx^+ = A x + B u + w with w∈Ww \in W, where W={∑jξjgj:∣ξj∣≤1}W = \{\sum_j \xi_j g_j : |\xi_j| \le 1\} is a zonotope whose generators gjg_j span Rn\mathbb{R}^n. The gain KK makes AK=A+BKA_K = A + B K Schur. The constraints are polyhedra X={x:aTx≤b for each row}X = \{x : a^T x \le b \text{ for each row}\} and U={u:aTu≤b}U = \{u : a^T u \le b\}. For a set SS and a vector aa, the support function is hS(a)=max⁡s∈SaTsh_S(a) = \max_{s \in S} a^T s. For zonotopes, hS(a)=∑j∣aTgj∣h_S(a) = \sum_j |a^T g_j|, hS1⊕S2=hS1+hS2h_{S_1 \oplus S_2} = h_{S_1} + h_{S_2}, hλS=λhSh_{\lambda S} = \lambda h_S for λ≥0\lambda \ge 0, and hMS(a)=hS(MTa)h_{M S}(a) = h_S(M^T a).

Part 1: the facet rows of a zonotope

Lemma 1. Let ZZ be a zonotope in Rn\mathbb{R}^n whose generators span Rn\mathbb{R}^n. The rows (c,hZ(c))(c, h_Z(c)) and (−c,hZ(c))(-c, h_Z(c)), where cc runs over the nonzero cofactor vectors of the (n−1)(n-1)-subsets of generators, describe ZZ exactly. For n=1n = 1, Z=[−hZ(1),hZ(1)]Z = [-h_Z(1), h_Z(1)].

Proof. Each row is valid for ZZ, since cTz≤hZ(c)c^T z \le h_Z(c) on ZZ by the definition of hZh_Z. So ZZ lies in the intersection. ZZ is a full-dimensional polytope, so it equals the intersection of the halfspaces of its facets. Let FF be a facet with outer normal dd. The points of ZZ that maximize dTzd^T z are ∑dTgj≠0sign(dTgj)gj+{∑dTgj=0ξjgj:∣ξj∣≤1}\sum_{d^T g_j \ne 0} \mathrm{sign}(d^T g_j) g_j + \{\sum_{d^T g_j = 0} \xi_j g_j : |\xi_j| \le 1\}. This set has dimension n−1n - 1, so the generators with dTgj=0d^T g_j = 0 span the (n−1)(n-1)-dimensional subspace d⊥d^\perp. Choose n−1n - 1 linearly independent ones. Their cofactor vector cc (the generalized cross product) is nonzero and orthogonal to all of them, so cc is parallel to dd, and one of ±c\pm c is a positive multiple of dd. The row for that sign is the facet inequality of FF, scaled. Hence the rows cut out exactly ZZ. □\square

Part 2: the error set

Lemma 2 (Raković, Kerrigan, Kouramas and Mayne 2005). Let s≥1s \ge 1 and α∈[0,1)\alpha \in [0, 1) satisfy AKsW⊆αWA_K^s W \subseteq \alpha W, and let Z=(1−α)−1⨁i=0s−1AKiWZ = (1 - \alpha)^{-1} \bigoplus_{i=0}^{s-1} A_K^i W. Then AKZ⊕W⊆ZA_K Z \oplus W \subseteq Z, and ZZ contains ⨁i=0t−1AKiW\bigoplus_{i=0}^{t-1} A_K^i W for every tt.

Proof. Write Fs=⨁i<sAKiWF_s = \bigoplus_{i<s} A_K^i W. Then

AKZ⊕W=(1−α)−1⨁i=1sAKiW⊕W⊆(1−α)−1(⨁i=1s−1AKiW⊕αW)⊕W=(1−α)−1⨁i=1s−1AKiW⊕(1−α)−1W=Z,A_K Z \oplus W = (1 - \alpha)^{-1} \bigoplus_{i=1}^{s} A_K^i W \oplus W \subseteq (1 - \alpha)^{-1} \Big(\bigoplus_{i=1}^{s-1} A_K^i W \oplus \alpha W\Big) \oplus W = (1 - \alpha)^{-1} \bigoplus_{i=1}^{s-1} A_K^i W \oplus (1 - \alpha)^{-1} W = Z,

where the middle step uses α1−αW⊕W=11−αW\frac{\alpha}{1 - \alpha} W \oplus W = \frac{1}{1 - \alpha} W, which holds because WW is convex. For the second claim, 0∈W0 \in W gives 0∈Z0 \in Z, and applying e↦AKe+we \mapsto A_K e + w tt times from 00 reaches every point of ⨁i<tAKiW\bigoplus_{i<t} A_K^i W and stays in ZZ by the first claim. □\square

The test in line L1. WW is symmetric with 00 in its interior, so by Lemma 1 it is {w:cTw≤bc}\{w : c^T w \le b_c\} with all bc>0b_c > 0. Then AKsW⊆αWA_K^s W \subseteq \alpha W if and only if hAKsW(c)≤αbch_{A_K^s W}(c) \le \alpha b_c for every row, and the least such α\alpha is max⁡chAKsW(c)/bc\max_c h_{A_K^s W}(c) / b_c, which rpi_outer computes. Since AKA_K is Schur, AKs→0A_K^s \to 0, so this α\alpha tends to 0, and the loop stops for any alpha_max >0> 0 (and also for alpha_max =0= 0 when AKA_K is nilpotent). The returned generators are those of ZZ.

Part 3: the tube

Let Xˉ\bar X and Uˉ\bar U be the rows of XX and UU with bb replaced by b−hZ(a)b - h_Z(a) and b−hZ(KTa)b - h_Z(K^T a) (line L2); these are X⊖ZX \ominus Z and U⊖KZU \ominus K Z.

Lemma 3. If x−z∈Zx - z \in Z, u=v+K(x−z)u = v + K (x - z), z+=Az+Bvz^+ = A z + B v and x+=Ax+Bu+wx^+ = A x + B u + w with w∈Ww \in W, then x+−z+∈Zx^+ - z^+ \in Z. If moreover z∈Xˉz \in \bar X and v∈Uˉv \in \bar U, then x∈Xx \in X and u∈Uu \in U.

Proof. x+−z+=A(x−z)+BK(x−z)+w=AK(x−z)+w∈AKZ⊕W⊆Zx^+ - z^+ = A (x - z) + B K (x - z) + w = A_K (x - z) + w \in A_K Z \oplus W \subseteq Z by Lemma 2. For a row aa of XX, aTx=aTz+aT(x−z)≤(b−hZ(a))+hZ(a)=ba^T x = a^T z + a^T (x - z) \le (b - h_Z(a)) + h_Z(a) = b. For a row of UU, aTu=aTv+(KTa)T(x−z)≤(b−hZ(KTa))+hZ(KTa)=ba^T u = a^T v + (K^T a)^T (x - z) \le (b - h_Z(K^T a)) + h_Z(K^T a) = b. □\square

Part 4: the nominal LP

From the measured state xx, tube_mpc solves

V(x)=min⁡z0,v0,…,vN−1∑k=0N−1(∥Qzk∥1+∥Rvk∥1)V(x) = \min_{z_0, v_0, \dots, v_{N-1}} \sum_{k=0}^{N-1} \left(\|Q z_k\|_1 + \|R v_k\|_1\right)

subject to x−z0∈Zx - z_0 \in Z (the rows of Lemma 1), zk+1=Azk+Bvkz_{k+1} = A z_k + B v_k, zk∈Xˉz_k \in \bar X and vk∈Uˉv_k \in \bar U for k<Nk < N, and zN=0z_N = 0. The states zkz_k are affine in (z0,v)(z_0, v) and are substituted. Each ∣⋅∣|\cdot| is an epigraph variable σ≥0\sigma \ge 0 with σ≥±(⋅)\sigma \ge \pm(\cdot); for fixed (z0,v)(z_0, v) the least feasible sum of the epigraph variables is the cost, so the LP value is V(x)V(x). The LP is solved by the two-phase simplex method with Bland's rule, which ends after finitely many pivots and is exact for rational data and tol = 0; the cost is a sum of nonnegative variables, so it is bounded below and never unbounded.

Write ℓ(z,v)=∥Qz∥1+∥Rv∥1\ell(z, v) = \|Q z\|_1 + \|R v\|_1 and assume 0∈Xˉ0 \in \bar X and 0∈Uˉ0 \in \bar U (the tightened bounds are nonnegative).

Theorem. If the LP is feasible at x0x_0, then for every disturbance sequence in WW:

  1. the LP is feasible at every sample;
  2. xk∈Xx_k \in X and uk∈Uu_k \in U for all kk;
  3. V(xk+1)≤V(xk)−ℓ(z0∗(xk),v0∗(xk))V(x_{k+1}) \le V(x_k) - \ell(z_0^*(x_k), v_0^*(x_k));
  4. if QQ has full column rank, then z0∗(xk)→0z_0^*(x_k) \to 0 and the distance from xkx_k to ZZ tends to 0.

Proof. Let (z0∗,v0∗,…,vN−1∗)(z_0^*, v_0^*, \dots, v_{N-1}^*) be optimal at xx, with states zk∗z_k^* and zN∗=0z_N^* = 0. The applied input is u=v0∗+K(x−z0∗)u = v_0^* + K (x - z_0^*) (line L6). Consider at x+x^+ the candidate z0′=z1∗z_0' = z_1^* and v′=(v1∗,…,vN−1∗,0)v' = (v_1^*, \dots, v_{N-1}^*, 0). Its states are zk′=zk+1∗z_k' = z_{k+1}^* for k<Nk < N and zN′=AzN∗+B⋅0=0z_N' = A z_N^* + B \cdot 0 = 0.

  • x+−z0′=x+−z1∗∈Zx^+ - z_0' = x^+ - z_1^* \in Z by Lemma 3 with z=z0∗z = z_0^*, v=v0∗v = v_0^*.
  • zk′=zk+1∗∈Xˉz_k' = z_{k+1}^* \in \bar X for k≤N−2k \le N - 2, and zN−1′=zN∗=0∈Xˉz_{N-1}' = z_N^* = 0 \in \bar X.
  • vk′=vk+1∗∈Uˉv_k' = v_{k+1}^* \in \bar U for k≤N−2k \le N - 2, and vN−1′=0∈Uˉv_{N-1}' = 0 \in \bar U.

So the candidate is feasible, which proves (1) by induction, and its cost is V(x)−ℓ(z0∗,v0∗)+ℓ(0,0)=V(x)−ℓ(z0∗,v0∗)V(x) - \ell(z_0^*, v_0^*) + \ell(0, 0) = V(x) - \ell(z_0^*, v_0^*), which proves (3). Lemma 3 with z=z0∗∈Xˉz = z_0^* \in \bar X and v=v0∗∈Uˉv = v_0^* \in \bar U gives (2). Summing (3) gives ∑kℓ(z0∗(xk),v0∗(xk))≤V(x0)<∞\sum_k \ell(z_0^*(x_k), v_0^*(x_k)) \le V(x_0) < \infty, so ℓ(z0∗(xk),⋅)→0\ell(z_0^*(x_k), \cdot) \to 0. If QQ has full column rank, ∥Qz∥1≥μ∥z∥\|Q z\|_1 \ge \mu \|z\| for some μ>0\mu > 0, so z0∗(xk)→0z_0^*(x_k) \to 0. Since xk∈z0∗(xk)⊕Zx_k \in z_0^*(x_k) \oplus Z, the distance from xkx_k to ZZ is at most ∥z0∗(xk)∥\|z_0^*(x_k)\|, which tends to 0. □\square

Part 5: what the code computes

  • Line L1 is rpi_outer, the test and the set of Part 2.
  • Line L2 is tighten, the sets Xˉ\bar X and Uˉ\bar U of Part 3.
  • Line L3 is the loop over the samples in closed_loop.
  • Line L4 writes the rows of Part 4: x−z0∈Zx - z_0 \in Z by the rows of Lemma 1, the tightened state and input rows, the equality zN=0z_N = 0, and the epigraph rows.
  • Line L5 solves the LP.
  • Line L6 applies u=v0∗+K(x−z0∗)u = v_0^* + K (x - z_0^*) and updates the plant.

Complexity

The online LP has n+Nmn + N m decision variables, NN times the epigraph variables of the cost, and of order Nq+rN q + r rows, where qq is the number of constraint rows per step and rr the number of facet rows of ZZ. Its size LL is linear in the horizon, and the dense simplex method costs O(L2)O(L^2) per pivot. The disturbance set enters only through ZZ, computed once offline: ZZ has ss times as many generators as WW, and in Rn\mathbb{R}^n the number of facet rows can grow like the number of (n−1)(n-1)-subsets of generators. This is the main gain over min-max MPC, whose LP grows like VNV^N for VV vertices of WW.

Properties

  • Robust constraint satisfaction for every disturbance sequence in WW.
  • Recursive feasibility, by the shifted nominal plan.
  • Convergence to the error set. The value is a Lyapunov function for the nominal state, and the true state approaches ZZ. Mayne, Seron and Raković (2005) show robust exponential stability of ZZ for the quadratic cost version.
  • Small online problem, the size of a nominal MPC problem, which grows linearly with the horizon.
  • Conservative, since the full tube ZZ is reserved at every step of the horizon, even where the actual error is small. The feasible region is smaller than that of feedback min-max MPC.
  • The choice of KK matters. A fast KK gives a small ZZ in the state but a large KZK Z, which eats the input range.

Variants and improvements

  • Fixed initial state. Setting z0=xz_0 = x is simpler, but then the shifted plan is not feasible in general, and the stability argument needs more care.
  • Constraint tightening along the horizon. Tighten step jj only by ⨁i<jAKiW\bigoplus_{i<j} A_K^i W, which grows with jj. This is less conservative early in the horizon.
  • Homothetic and elastic tubes. Let the tube be zk⊕βkZz_k \oplus \beta_k Z with scales βk\beta_k as decision variables, so the tube shrinks where the disturbance allows.
  • Output feedback. Add an observer and a second tube for the estimation error.
  • Nonlinear plants. Use a nonlinear ancillary controller that tracks the nominal trajectory, and bound the tube by an incremental Lyapunov function.
  • Stochastic tubes. Replace the robust tightening by a probabilistic one, as in stochastic MPC.

When to use it

Use tube MPC for a linear plant with a bounded disturbance and hard constraints, when min-max MPC is too large to solve online. It is a good default for robust linear MPC: the online problem is a standard QP or LP, and the offline work is a set computation. If the disturbance is large compared to the constraints, the tightened sets can be empty; then a less conservative method or a different KK is needed. If constraint violations with small probability are acceptable, stochastic MPC uses the constraint range better.

Pitfalls

  • Empty tightened sets. If ZZ is larger than XX in some direction, or KZK Z larger than UU, the method has no feasible point at all. Check the tightened bounds first, and change KK if they are negative.
  • Too large an α\alpha. The bound ZZ is (1−α)−1(1 - \alpha)^{-1} times a partial sum, so a crude α\alpha wastes constraint range.
  • Wrong disturbance set. The guarantees hold only for w∈Ww \in W. In practice WW should include model errors, which are often larger than the measured noise.
  • Numerical facets. In higher dimensions, the number of facet rows of a zonotope grows fast. Remove redundant rows, or use a box or a polytope that contains ZZ.
  • Applying vv alone. The applied input must include the ancillary term K(x−z0)K (x - z_0). Without it, the error is not bounded by ZZ.

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.

tube_mpc.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tube-mpc/. The authors are listed in prov/ZNT0ZQ.jsonl.

"""Tube MPC for x+ = A x + B u + w with w in a zonotope W.

The control is u = v + K (x - z), where z, v are the nominal state and input
and A + B K is Schur. The error e = x - z then stays in a robust positively
invariant set Z, an outer bound of the minimal one by the method of Rakovic,
Kerrigan, Kouramas and Mayne (2005). The nominal plan uses the tightened sets
X - Z and U - K Z, the terminal constraint z_N = 0, and the 1-norm cost
sum (|Q z_k|_1 + |R v_k|_1), so each sample solves one linear program. The
first nominal state z_0 is a decision variable with x - z_0 in Z.

Matrices are lists of rows, vectors flat lists. Sets are zonotopes given by a
list of generators (centered at 0) or polyhedra given by rows (a, b) for
a . x <= b. The LP solver is a dense two-phase simplex method with Bland's
rule; with Fraction data and tol = 0 everything is exact.
"""

import itertools
from fractions import Fraction

__all__ = ["lp_min", "support", "zonotope_rows", "rpi_outer", "tighten", "tube_mpc", "closed_loop"]


def _pivot(T, obj, r, c):
    p = T[r][c]
    if isinstance(p, int):
        p = Fraction(p)  # int / int would give a float
    prow = [v / p for v in T[r]]
    T[r] = prow
    nzj = [j for j, v in enumerate(prow) if v != 0]
    for row in T + [obj]:
        if row is not prow and row[c] != 0:
            f = row[c]
            for j in nzj:
                row[j] -= f * prow[j]


def _simplex(T, obj, basis, tol, limit):
    while True:
        enter = next((j for j in range(limit) if obj[j] < -tol), None)
        if enter is None:
            return True
        leave, best = None, None
        for i, row in enumerate(T):
            if row[enter] > tol:
                ratio = row[-1] / row[enter]
                if best is None or ratio < best - tol or (abs(ratio - best) <= tol and basis[i] < basis[leave]):
                    leave, best = i, ratio
        if leave is None:
            return False
        _pivot(T, obj, leave, enter)
        basis[leave] = enter


def lp_min(c, G, g, E=(), e=(), nonneg=(), tol=1e-9):
    """Minimize c . z subject to G z <= g and E z = e; variables in nonneg are >= 0.

    Returns (value, z), or None if infeasible. Raises ValueError if unbounded.
    With tol = 0 the data are used as given (exact for Fractions); otherwise
    they are converted to floats, since mixed Fraction and float arithmetic is slow.
    """
    if tol:
        c, g, e = [float(v) for v in c], [float(v) for v in g], [float(v) for v in e]
        G, E = [[float(v) for v in r] for r in G], [[float(v) for v in r] for r in E]
    n = len(c)
    nonneg = set(nonneg)
    free = [j for j in range(n) if j not in nonneg]
    neg_col = {j: n + i for i, j in enumerate(free)}
    nz = n + len(free)
    ns = len(G)
    rows = [(a, b, True) for a, b in zip(G, g)] + [(a, b, False) for a, b in zip(E, e)]
    need_art = [i for i, (a, b, ineq) in enumerate(rows) if b < 0 or not ineq]
    art_col = {i: nz + ns + k for k, i in enumerate(need_art)}
    ncol = nz + ns + len(need_art)
    T, basis = [], []
    for i, (a, b, ineq) in enumerate(rows):
        row = [0] * (ncol + 1)
        for j in range(n):
            row[j] = a[j]
            if j in neg_col:
                row[neg_col[j]] = -a[j]
        if ineq:
            row[nz + i] = 1
        row[-1] = b
        if b < 0:
            row = [-v for v in row]
        if i in art_col:
            row[art_col[i]] = 1
        T.append(row)
        basis.append(art_col.get(i, nz + i))
    if need_art:
        obj = [0] * (ncol + 1)
        for i in need_art:
            for j in range(ncol + 1):
                if j < nz + ns or j == ncol:
                    obj[j] -= T[i][j]
        _simplex(T, obj, basis, tol, ncol)
        if -obj[-1] > tol * max(1, len(need_art)):
            return None
        keep = []
        for i in range(len(T)):
            if basis[i] >= nz + ns:
                j = next((j for j in range(nz + ns) if abs(T[i][j]) > tol), None)
                if j is None:
                    continue
                _pivot(T, obj, i, j)
                basis[i] = j
            keep.append(i)
        T = [T[i][:nz + ns] + [T[i][-1]] for i in keep]
        basis = [basis[i] for i in keep]
    else:
        T = [row[:nz + ns] + [row[-1]] for row in T]
    cost = list(c) + [-c[j] for j in free] + [0] * ns
    obj = cost + [0]
    for i, j in enumerate(basis):
        if cost[j] != 0:
            f = cost[j]
            obj = [o - f * t for o, t in zip(obj, T[i])]
    if not _simplex(T, obj, basis, tol, nz + ns):
        raise ValueError("the LP is unbounded")
    val = [0] * (nz + ns)
    for i, j in enumerate(basis):
        val[j] = T[i][-1]
    z = [val[j] - (val[neg_col[j]] if j in neg_col else 0) for j in range(n)]
    return sum(ci * zi for ci, zi in zip(c, z)), z


def _matvec(M, x):
    return [sum(a * b for a, b in zip(row, x)) for row in M]


def _matmul(M, N):
    return [[sum(M[i][k] * N[k][j] for k in range(len(N))) for j in range(len(N[0]))] for i in range(len(M))]


def _det(M):
    M = [list(r) for r in M]
    n, d = len(M), 1
    for c in range(n):
        p = next((r for r in range(c, n) if M[r][c] != 0), None)
        if p is None:
            return 0
        if p != c:
            M[c], M[p] = M[p], M[c]
            d = -d
        d = d * M[c][c]
        for r in range(c + 1, n):
            f = M[r][c] / (Fraction(M[c][c]) if isinstance(M[c][c], int) else M[c][c])
            M[r] = [x - f * y for x, y in zip(M[r], M[c])]
    return d


def support(gens, a):
    """Support function of the zonotope with these generators: max a . z over the set."""
    return sum(abs(sum(ai * gi for ai, gi in zip(a, g))) for g in gens)


def zonotope_rows(gens, n):
    """Rows (c, b) with c . z <= b that describe the zonotope; one pair per facet normal."""
    if n == 1:
        b = support(gens, [1])
        return [([1], b), ([-1], b)]
    rows = []
    for S in itertools.combinations(gens, n - 1):
        # Normal of the hyperplane spanned by S: the cofactors of the n x (n - 1) matrix [S].
        c = [(-1) ** i * _det([[g[r] for g in S] for r in range(n) if r != i]) for i in range(n)]
        if any(ci != 0 for ci in c):
            b = support(gens, c)
            rows += [(c, b), ([-ci for ci in c], b)]
    return rows


def rpi_outer(AK, W, alpha_max=Fraction(1, 10), s_max=200):
    """Return (s, alpha, Z) with A_K^s W in alpha W and Z = (1 - alpha)^-1 (W + A_K W + ... + A_K^(s-1) W)."""
    n = len(AK)
    Wrows = zonotope_rows(W, n)
    P = [[1 if i == j else 0 for j in range(n)] for i in range(n)]  # A_K^s
    for s in range(1, s_max + 1):  # @line L1
        P = _matmul(AK, P)
        AsW = [_matvec(P, g) for g in W]
        alpha = max(support(AsW, c) / b for c, b in Wrows)
        if alpha <= alpha_max:
            scale = 1 / (1 - Fraction(alpha) if not isinstance(alpha, float) else 1 - alpha)
            Z, Pi = [], [[1 if i == j else 0 for j in range(n)] for i in range(n)]
            for _ in range(s):
                Z += [[scale * v for v in _matvec(Pi, g)] for g in W]
                Pi = _matmul(AK, Pi)
            return s, alpha, Z
    raise ValueError("A_K^s W is not inside alpha_max W for s <= s_max")


def tighten(rows, Z, M=None):
    """Rows of S - M Z for S = {a . y <= b}: each b becomes b - h_Z(M^T a)."""
    out = []
    for a, b in rows:  # @line L2
        aa = a if M is None else [sum(a[i] * M[i][j] for i in range(len(M))) for j in range(len(M[0]))]
        out.append((a, b - support(Z, aa)))
    return out


def tube_mpc(A, B, Z, Zrows, x, N, Q, R, Xbar, Ubar, tol=1e-9):
    """Solve the nominal LP from the measured state x. Returns (value, z0, vs, zs) or None."""
    n, m = len(A), len(B[0])
    nv = n + N * m  # decision variables z0 and v_0..v_(N-1); the z_k are affine in them
    # z_k = Phi_k z0 + sum_j Gam_(k,j) v_j, stored as rows over the nv variables.
    zs_aff = [[[1 if c == i else 0 for c in range(nv)] for i in range(n)]]
    for k in range(N):
        prev = zs_aff[-1]
        nxt = []
        for i in range(n):
            r = [sum(A[i][l] * prev[l][c] for l in range(n)) for c in range(nv)]
            for j in range(m):
                r[n + k * m + j] += B[i][j]
            nxt.append(r)
        zs_aff.append(nxt)
    # Epigraph variables come after the nv variables.
    ne = N * (len(Q) + len(R))
    tot = nv + ne
    pad = [0] * ne

    G, g, E, e = [], [], [], []
    # @line L4
    for c, b in Zrows:  # x - z0 in Z
        G.append([-ci for ci in c] + [0] * (N * m) + pad)
        g.append(b - sum(ci * xi for ci, xi in zip(c, x)))
    for k in range(N):
        for a, b in Xbar:
            G.append([sum(a[i] * zs_aff[k][i][col] for i in range(n)) for col in range(nv)] + pad)
            g.append(b)
        for a, b in Ubar:
            r = [0] * tot
            for j in range(m):
                r[n + k * m + j] = a[j]
            G.append(r)
            g.append(b)
    for i in range(n):  # z_N = 0
        E.append(zs_aff[N][i] + pad)
        e.append(0)
    col = nv
    for k in range(N):
        for W_, isQ in ((Q, True), (R, False)):
            for wr in W_:
                for sg in (1, -1):
                    r = [0] * tot
                    if isQ:
                        for i in range(n):
                            for cc in range(nv):
                                r[cc] += sg * wr[i] * zs_aff[k][i][cc]
                    else:
                        for j in range(m):
                            r[n + k * m + j] += sg * wr[j]
                    r[col] = -1
                    G.append(r)
                    g.append(0)
                col += 1
    cost = [0] * nv + [1] * ne
    # @line L5
    sol = lp_min(cost, G, g, E, e, range(nv, tot), tol)
    if sol is None:
        return None
    val, zz = sol
    z0 = zz[:n]
    vs = [zz[n + k * m:n + (k + 1) * m] for k in range(N)]
    zs = [[sum(r[cc] * zz[cc] for cc in range(nv)) for r in zs_aff[k]] for k in range(N + 1)]
    return val, z0, vs, zs


def closed_loop(A, B, K, Z, Zrows, x0, N, Q, R, Xbar, Ubar, disturbances, tol=1e-9):
    """Run the tube controller. Returns (xs, us, z0s, values)."""
    x = list(x0)
    xs, us, z0s, vals = [list(x)], [], [], []
    for w in disturbances:  # @line L3
        sol = tube_mpc(A, B, Z, Zrows, x, N, Q, R, Xbar, Ubar, tol)
        if sol is None:
            raise RuntimeError("the nominal problem is infeasible")
        val, z0, vs, _ = sol
        # @line L6
        u = [vj + sum(K[j][i] * (x[i] - z0[i]) for i in range(len(x))) for j, vj in enumerate(vs[0])]
        x = [a + b + wi for a, b, wi in zip(_matvec(A, x), _matvec(B, u), w)]
        xs.append(x)
        us.append(u)
        z0s.append(z0)
        vals.append(val)
    return xs, us, z0s, vals
test_tube_mpc.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tube-mpc/. The authors are listed in prov/ZNT0ZQ.jsonl.

import itertools
import random
from fractions import Fraction as Fr

import pytest

from tube_mpc import closed_loop, lp_min, rpi_outer, support, tighten, tube_mpc, zonotope_rows

# The example of the page: a double integrator with a deadbeat ancillary gain.
A = [[1, 1], [0, 1]]
B = [[Fr(1, 2)], [1]]
K = [[-1, Fr(-3, 2)]]
W = [[Fr(1, 10), 0], [0, Fr(1, 10)]]
X = [([1, 0], 5), ([-1, 0], 5), ([0, 1], 1), ([0, -1], 1)]
U = [([1], 1), ([-1], 1)]
Q = [[1, 0], [0, 1]]
R = [[1]]


def closed(Kg):
    return [[A[i][j] + B[i][0] * Kg[0][j] for j in range(2)] for i in range(2)]


def inside(rows, p, tol=0):
    return all(sum(ci * pi for ci, pi in zip(c, p)) <= b + tol for c, b in rows)


def test_lp_small_cases():
    val, z = lp_min([1, 1], [[-1, -1]], [-1], [[1, -1]], [Fr(1, 3)], tol=0)
    assert val == 1 and z == [Fr(2, 3), Fr(1, 3)]
    assert lp_min([1], [[1], [-1]], [-1, -1], tol=0) is None
    with pytest.raises(ValueError):
        lp_min([1], [[1]], [1], tol=0)


def test_zonotope_rows_and_support():
    rng = random.Random(3)
    for n in (2, 3):
        for _ in range(4):
            gens = [[Fr(rng.randint(-5, 5), 4) for _ in range(n)] for _ in range(n + 1)]
            rows = zonotope_rows(gens, n)
            verts = [[sum(s * g[i] for s, g in zip(signs, gens)) for i in range(n)]
                     for signs in itertools.product((-1, 1), repeat=len(gens))]
            a = [rng.randint(-3, 3) for _ in range(n)]
            assert support(gens, a) == max(sum(ai * vi for ai, vi in zip(a, v)) for v in verts)
            for _ in range(15):
                p = [Fr(rng.randint(-12, 12), 4) for _ in range(n)]
                # p is in the zonotope iff gens xi = p for some |xi| <= 1.
                k = len(gens)
                Gb = [[1 if j == i else 0 for j in range(k)] for i in range(k)]
                Gb += [[-1 if j == i else 0 for j in range(k)] for i in range(k)]
                Eq = [[g[i] for g in gens] for i in range(n)]
                lp = lp_min([0] * k, Gb, [1] * (2 * k), Eq, p, tol=0)
                assert inside(rows, p) == (lp is not None)


def test_example_sets_are_exact():
    s, alpha, Z = rpi_outer(closed(K), W)
    assert (s, alpha) == (2, 0)
    # A_K is nilpotent, so Z = W + A_K W is the minimal robust positively invariant set.
    assert support(Z, [1, 0]) == Fr(7, 40) and support(Z, [0, 1]) == Fr(1, 4)
    assert [b for _, b in tighten(X, Z)] == [Fr(193, 40)] * 2 + [Fr(3, 4)] * 2
    assert [b for _, b in tighten(U, Z, K)] == [Fr(3, 5)] * 2
    Zrows = zonotope_rows(Z, 2)
    val, z0, vs, zs = tube_mpc(A, B, Z, Zrows, [-3, 0], 6, Q, R, tighten(X, Z), tighten(U, Z, K), tol=0)
    assert val == Fr(51, 4) and z0 == [Fr(-117, 40), Fr(3, 20)] and zs[-1] == [0, 0]
    assert tube_mpc(A, B, Z, Zrows, [-3, 0], 4, Q, R, tighten(X, Z), tighten(U, Z, K), tol=0) is None


def test_rpi_outer_bound_is_invariant():
    rng = random.Random(8)
    for _ in range(5):
        while True:
            M = [[Fr(rng.randint(-8, 8), 10) for _ in range(2)] for _ in range(2)]
            tr, det = M[0][0] + M[1][1], M[0][0] * M[1][1] - M[0][1] * M[1][0]
            if abs(det) < 1 and abs(tr) < 1 + det - Fr(1, 10):  # Jury test: Schur with a margin
                break
        s, alpha, Z = rpi_outer(M, W, Fr(1, 5))
        rows = zonotope_rows(Z, 2)
        # A_K Z + W is inside Z: compare support functions on the facet normals of Z.
        AZ = [[sum(M[i][j] * g[j] for j in range(2)) for i in range(2)] for g in Z]
        assert all(support(AZ + W, c) <= b for c, b in rows)
        # Z contains every partial sum W + A_K W + ... of the minimal invariant set.
        P, Fs = [[1, 0], [0, 1]], []
        for _ in range(25):
            Fs += [[sum(P[i][j] * g[j] for j in range(2)) for i in range(2)] for g in W]
            P = [[sum(M[i][k] * P[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
        assert all(support(Fs, c) <= b for c, b in rows)


def run_case(Kg, alpha_max, seed, steps):
    s, alpha, Z = rpi_outer(closed(Kg), W, alpha_max)
    Zrows = zonotope_rows(Z, 2)
    Xb, Ub = tighten(X, Z), tighten(U, Z, Kg)
    rng = random.Random(seed)
    ws = [[rng.choice([-0.1, 0.1]), rng.choice([-0.1, 0.1])] for _ in range(steps)]
    xs, us, z0s, vals = closed_loop(A, B, Kg, Z, Zrows, [-3.0, 0.0], 8, Q, R, Xb, Ub, ws)
    return Zrows, xs, us, z0s, vals


@pytest.mark.parametrize("Kg, seed", [(K, 1), ([[Fr(-1, 2), -1]], 2)])
def test_constraints_hold_for_vertex_disturbances(Kg, seed):
    Zrows, xs, us, z0s, vals = run_case(Kg, Fr(1, 10), seed, 18)
    for k, (x, u, z0) in enumerate(zip(xs, us, z0s)):
        assert abs(x[0]) <= 5 + 1e-9 and abs(x[1]) <= 1 + 1e-9 and abs(u[0]) <= 1 + 1e-9
        assert inside(Zrows, [x[0] - z0[0], x[1] - z0[1]], 1e-9)
    # The value drops by at least the first stage cost of the nominal plan.
    for k in range(len(vals) - 1):
        z0 = z0s[k]
        v0 = us[k][0] - sum(Kg[0][i] * (xs[k][i] - z0[i]) for i in range(2))
        assert vals[k + 1] <= vals[k] - (abs(z0[0]) + abs(z0[1]) + abs(v0)) + 1e-7
    assert vals[-1] < 1e-9


def test_no_disturbance_reaches_the_origin():
    s, alpha, Z = rpi_outer(closed(K), W)
    Zrows = zonotope_rows(Z, 2)
    xs, us, z0s, vals = closed_loop(A, B, K, Z, Zrows, [-3.0, 0.0], 6, Q, R, tighten(X, Z), tighten(U, Z, K), [[0.0, 0.0]] * 7)
    expect = [51 / 4, 69 / 8, 81 / 16, 19 / 8, 5 / 16, 0, 0]
    assert all(abs(v - e) < 1e-9 for v, e in zip(vals, expect))
    assert all(abs(c) < 1e-9 for x in xs[5:] for c in x)

History

Earlier robust MPC schemes already combined a fixed linear feedback with constraint tightening along the horizon. Mayne, Seron and Raković (2005) made the first nominal state a decision variable, which gives a clean proof of recursive feasibility and robust exponential stability of the error set. In the same year Raković, Kerrigan, Kouramas and Mayne (2005) showed how to compute outer bounds of the minimal robust positively invariant set to any accuracy. Later work extended tubes to output feedback, nonlinear plants, homothetic and elastic tubes, and stochastic tubes, and the book of Rawlings, Mayne and Diehl presents tube MPC as a standard method of robust MPC.

References

  1. David Q. Mayne, María M. Seron and Saša V. Raković, Robust model predictive control of constrained linear systems with bounded disturbances, Automatica 41(2), 219-224, 2005, the tube controller with the initial nominal state as a decision variable, recursive feasibility, and robust stability of the error set
  2. Saša V. Raković, Eric C. Kerrigan, Konstantinos I. Kouramas and David Q. Mayne, Invariant approximations of the minimal robust positively invariant set, IEEE Transactions on Automatic Control 50(3), 406-410, 2005, the outer bound of the minimal robust positively invariant set from A_K^s W inside alpha W
  3. James B. Rawlings, David Q. Mayne and Moritz M. Diehl, Model Predictive Control, Theory, Computation, and Design, 2nd edition, Nob Hill Publishing, 2017, the chapter on robust MPC, tube-based MPC for linear systems

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.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