Algorithm Search⌘K

Algorithmadvanced

Min-max MPC

Also called min-max model predictive control.

Minimizes the worst case cost over all disturbance sequences in a bounded set, by open-loop or feedback min-max optimization.

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 LP, of order V^N (n + m + q) for q rows of the constraints; N = the horizon; V = the number of vertices of the disturbance set; m = the number of inputs; n = the number of states
Properties
deterministicexactonlineiterative
Origin
Pedro J. Campo, Manfred Morari, 1987

Min-max MPC is a form of model predictive control for a plant with a bounded disturbance. At each sample it solves a game: the controller picks the inputs, the disturbance picks the worst sequence in its set, and the controller minimizes that worst case cost subject to the constraints for every possible disturbance. In the open-loop form the inputs are a fixed sequence. In the feedback form each future input may depend on the disturbances seen so far, which is less conservative and can be feasible where the open-loop form is not. For a linear plant, a polytope of disturbances and 1-norm costs, the feedback problem is one linear program over a tree with one branch per vertex of the disturbance set, and it is exact for the whole polytope. Only the first input is applied, and the problem is solved again at the next sample.

In plain words

Plan the next few moves as if an opponent controls the disturbance and always does the most harmful thing. Pick the plan whose worst outcome is the best, and make sure that every limit holds whatever the opponent does. A good plan says what to do after each move of the opponent, not one fixed list of moves, because you will see the disturbance before you act again. For a linear plant it is enough to plan against the corners of the disturbance set, since anything in between is a mix of corners. The price is size: the plan has a branch for every corner at every step, so the number of branches grows very fast with the horizon.

The problem

Input: matrices A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m}, the vertices w1,…,wVw^1, \dots, w^V of the disturbance set WW, a horizon NN, weights QQ, RR, PP, bounds xˉ\bar x, uˉ\bar u, a terminal set Xf={x:Fx≤f}X_f = \{x : F x \le f\}, and the current state x0x_0.

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

J=∑k=0N−1(∥Qxk∥1+∥Ruk∥1)+∥PxN∥1.J = \sum_{k=0}^{N-1} \left(\|Q x_k\|_1 + \|R u_k\|_1\right) + \|P x_N\|_1.

Output: an input u0u_0 that is the first input of an optimal policy for

J∗(x0)=min⁡π max⁡w0,…,wN−1∈WJsubject to ∣xk∣≤xˉ, ∣uk∣≤uˉ, xN∈Xf for every disturbance sequence,J^*(x_0) = \min_{\pi} \ \max_{w_0, \dots, w_{N-1} \in W} J \quad \text{subject to } |x_k| \le \bar x, \ |u_k| \le \bar u, \ x_N \in X_f \text{ for every disturbance sequence},

where the policy π\pi chooses uku_k as a function of w0,…,wk−1w_0, \dots, w_{k-1} (feedback form) or as a constant (open-loop form). If no policy meets the constraints, report that the problem is infeasible.

The algorithm

  1. MIN-MAX-MPC(A, B, x₀, N, w¹..wⱽ, Q, R, P, x̄, ū, F, f)
  2. 1nodes ← all sequences s of vertex indices with |s| ≤ N ▷ the scenario tree
  3. 2variables: x_s for each node, u_s for each inner node (feedback) or one u per depth (open loop)
  4. 3for each node s and vertex i: x_{s i} = A x_s + B u_s + wⁱ
  5. 4|x_s| ≤ x̄ at each node, |u_s| ≤ ū at each inner node, F x_ℓ ≤ f at each leaf ℓ
  6. 5t ≥ (cost along the path to ℓ) for each leaf ℓ, with each |·| as an epigraph variable
  7. 6solve the LP: minimize t subject to L3 to L5
  8. 7return t and u_() at the root
  9. 8at each sample: measure x, set x₀ ← x, run L1 to L7, apply u_()

Line L5 writes each absolute value ∣aTz∣|a^T z| as a variable s≥0s \ge 0 with s≥aTzs \ge a^T z and s≥−aTzs \ge -a^T z, and bounds tt from below by the sum of these variables along each path. At the optimum each ss equals its absolute value, and tt equals the largest path cost. The code solves the LP with a two-phase simplex method and Bland's rule, in exact rational arithmetic when the data are rational.

The feedback form has a separate control at each inner node, so the input at depth kk can differ between branches that saw different disturbances. The open-loop form forces all nodes of one depth to share one control.

Example

Take the scalar plant xk+1=1.2 xk+uk+wkx_{k+1} = 1.2\, x_k + u_k + w_k with ∣wk∣≤0.2|w_k| \le 0.2, so the vertices are ±0.2\pm 0.2. The weights are Q=1Q = 1, R=0.1R = 0.1, P=3P = 3, the input bound is ∣u∣≤1|u| \le 1, and the terminal set is ∣xN∣≤0.5|x_N| \le 0.5. The plant alone is unstable.

From x0=0x_0 = 0 with N=2N = 2. In the feedback form, u0=0u_0 = 0, so x1=±0.2x_1 = \pm 0.2. On the branch x1=0.2x_1 = 0.2 the second input is u1=−0.24u_1 = -0.24, which cancels 1.2 x11.2\, x_1 and leaves x2=±0.2x_2 = \pm 0.2; the other branch is the mirror image. The worst path cost is 0+0+0.2+0.024+3⋅0.2=0.824=103/1250 + 0 + 0.2 + 0.024 + 3 \cdot 0.2 = 0.824 = 103/125. In the open-loop form, u1u_1 must be the same on both branches, the best choice is u1=0u_1 = 0, and the worst final state is 1.2⋅0.2+0.2=0.441.2 \cdot 0.2 + 0.2 = 0.44, so the value is 0.2+3⋅0.44=1.520.2 + 3 \cdot 0.44 = 1.52. Feedback cuts the worst case cost by almost half.

x0x_0, NN feedback value open-loop value first input
00, N=1N = 1 3/53/5 3/53/5 00
0.50.5, N=1N = 1 29/2529/25 29/2529/25 −0.6-0.6
00, N=2N = 2 103/125103/125 38/2538/25 00
0.50.5, N=2N = 2 173/125173/125 52/2552/25 −0.6-0.6
00, N=3N = 3 131/125131/125 infeasible 00

Where open loop fails. With a fixed input sequence, the spread of x3x_3 caused by the disturbances is ±0.2 (1.44+1.2+1)=±0.728\pm 0.2\,(1.44 + 1.2 + 1) = \pm 0.728, which does not fit in ∣x3∣≤0.5|x_3| \le 0.5. So the open-loop problem with N=3N = 3 is infeasible from every state. The feedback problem is feasible exactly for ∣x0∣≤13/12|x_0| \le 13/12, 113/72113/72 and 853/432853/432 for N=1,2,3N = 1, 2, 3: each extra step adds the states that one input of size at most 1 can bring into the previous region despite the disturbance.

In closed loop with N=2N = 2 from x0=1x_0 = 1 and w=0w = 0, the inputs are −1-1 and −0.24-0.24, and the state goes 1,0.2,01, 0.2, 0 and stays at 0. With random disturbances in [−0.2,0.2][-0.2, 0.2] every problem stays feasible, as Theorem 2 of the proof says, because the terminal set is robustly invariant under u=−1.2 xu = -1.2\, x: then x+=wx^+ = w, and ∣u∣≤0.6|u| \le 0.6.

Correctness

The proof is in proofs/correctness.md. Any admissible feedback policy, restricted to the vertex sequences, is a feasible point of the LP with a cost no larger than its worst case, so the LP value is at most the min-max value. Conversely, given an LP solution, write each disturbance as a convex combination of the vertices and mix the controls of the tree with the products of these weights. This policy is causal, and its trajectory under any disturbance sequence in the polytope is a convex combination of the leaf trajectories. The constraints are convex and the cost is convex, so the policy meets all constraints and its cost is at most the largest leaf cost. Hence the LP value equals the min-max value over the whole polytope, not only over the vertices. If the terminal set is robustly invariant under a local feedback inside the constraints, the shifted tree with that feedback appended is feasible at the next sample, so the receding horizon loop stays feasible.

Proof: The scenario tree LP solves the feedback min-max problem over the whole disturbance polytope, and the receding horizon loop stays feasiblefull

Setting. The plant is xk+1=Axk+Buk+wkx_{k+1} = A x_k + B u_k + w_k with wk∈W=conv{w1,…,wV}w_k \in W = \mathrm{conv}\{w^1, \dots, w^V\}. The horizon is N≥1N \ge 1. The constraints are xk∈X={x:∣xi∣≤xˉi}x_k \in X = \{x : |x_i| \le \bar x_i\} for 0≤k≤N0 \le k \le N, uk∈U={u:∣uj∣≤uˉj}u_k \in U = \{u : |u_j| \le \bar u_j\} for k<Nk < N, and xN∈Xf={x:Fx≤f}x_N \in X_f = \{x : F x \le f\}. The cost of one trajectory τ=(x0,u0,…,uN−1,xN)\tau = (x_0, u_0, \dots, u_{N-1}, x_N) is

J(τ)=∑k<N(∥Qxk∥1+∥Ruk∥1)+∥PxN∥1.J(\tau) = \sum_{k < N} \left(\|Q x_k\|_1 + \|R u_k\|_1\right) + \|P x_N\|_1.

JJ is a convex function of τ\tau, and the constraint set C={τ:xk∈X,uk∈U,xN∈Xf}\mathcal{C} = \{\tau : x_k \in X, u_k \in U, x_N \in X_f\} is convex.

A causal policy is a list of maps πk:Wk→Rm\pi_k : W^k \to \mathbb{R}^m, so that uk=πk(w0,…,wk−1)u_k = \pi_k(w_0, \dots, w_{k-1}). It is admissible from x0x_0 if the trajectory meets C\mathcal{C} for every (w0,…,wN−1)∈WN(w_0, \dots, w_{N-1}) \in W^N. The feedback min-max value is

J∗(x0)=inf⁡π admissible sup⁡w∈WNJ(τ(x0,π,w)).J^*(x_0) = \inf_{\pi \text{ admissible}} \ \sup_{w \in W^N} J(\tau(x_0, \pi, w)).

The open-loop value Jol∗(x0)J^*_{\rm ol}(x_0) is the same with each πk\pi_k a constant.

The tree. A node is a sequence s=(s0,…,sk−1)s = (s_0, \dots, s_{k-1}) of vertex indices with 0≤k≤N0 \le k \le N; its depth is ∣s∣=k|s| = k. The root is the empty sequence. A node of depth NN is a leaf. The LP of min_max_mpc (feedback form) has a state xsx_s at each node with x()=x0x_{()} = x_0, a control usu_s at each inner node, the constraints

xsi=Axs+Bus+wi,xs∈X,us∈U,xℓ∈Xf at each leaf ℓ,(1)x_{s i} = A x_s + B u_s + w^i, \quad x_s \in X, \quad u_s \in U, \quad x_\ell \in X_f \text{ at each leaf } \ell, \tag{1}

and the objective min⁡t\min t with t≥J(τℓ)t \ge J(\tau_\ell) for each leaf ℓ\ell, where τℓ\tau_\ell is the trajectory along the path from the root to ℓ\ell: τℓ=(x(),u(),xℓ:1,uℓ:1,…,xℓ)\tau_\ell = (x_{()}, u_{()}, x_{\ell_{:1}}, u_{\ell_{:1}}, \dots, x_\ell) with ℓ:k\ell_{:k} the prefix of length kk. In the open-loop form, all inner nodes of the same depth share one control.

Part 1: the epigraph rows

The code writes t≥J(τℓ)t \ge J(\tau_\ell) with nonnegative variables: sp,r≥±(P or Q)rxps_{p,r} \ge \pm (P \text{ or } Q)_r x_p for each node pp and row rr, ρp,r≥±Rrup\rho_{p,r} \ge \pm R_r u_p for each inner node, and t≥∑p on the path to ℓ(∑rsp,r+∑rρp,r)t \ge \sum_{p \text{ on the path to } \ell} \left(\sum_r s_{p,r} + \sum_r \rho_{p,r}\right) (line L5).

Lemma 1. For fixed (xs,us)(x_s, u_s) that meet (1), the least tt that is feasible with some choice of the epigraph variables is max⁡ℓJ(τℓ)\max_\ell J(\tau_\ell).

Proof. Each sp,r≥∣(⋅)rxp∣s_{p,r} \ge |(\cdot)_r x_p| and each ρp,r≥∣Rrup∣\rho_{p,r} \ge |R_r u_p|, so every feasible tt is at least J(τℓ)J(\tau_\ell) for each ℓ\ell. Setting every epigraph variable equal to its absolute value is feasible and gives t=max⁡ℓJ(τℓ)t = \max_\ell J(\tau_\ell). □\square

So the optimal value of the LP is

JLP(x0)=min⁡{max⁡ℓJ(τℓ):(xs,us) meet (1)},(2)J^{\rm LP}(x_0) = \min\left\{\max_\ell J(\tau_\ell) : (x_s, u_s) \text{ meet } (1)\right\}, \tag{2}

and the LP is infeasible exactly when (1) has no solution.

Part 2: the LP value is the min-max value

Lemma 2 (restriction). If π\pi is admissible from x0x_0, then us=π∣s∣(ws0,…,ws∣s∣−1)u_s = \pi_{|s|}(w^{s_0}, \dots, w^{s_{|s|-1}}) and the resulting states meet (1), and max⁡ℓJ(τℓ)≤sup⁡w∈WNJ(τ(x0,π,w))\max_\ell J(\tau_\ell) \le \sup_{w \in W^N} J(\tau(x_0, \pi, w)).

Proof. The path to a leaf ℓ\ell is the trajectory of π\pi under the vertex sequence (wℓ0,…,wℓN−1)∈WN(w^{\ell_0}, \dots, w^{\ell_{N-1}}) \in W^N. It meets C\mathcal{C} because π\pi is admissible, and its cost is one of the values in the supremum. Two nodes with the same prefix get the same control because π\pi is causal. □\square

Lemma 3 (interpolation). Let (xs,us)(x_s, u_s) meet (1). For each kk and each w∈Ww \in W fix weights λi(w)≥0\lambda_i(w) \ge 0 with ∑iλi(w)=1\sum_i \lambda_i(w) = 1 and ∑iλi(w)wi=w\sum_i \lambda_i(w) w^i = w. For a disturbance sequence w0,w1,…w_0, w_1, \dots, let μ(s)=∏j<∣s∣λsj(wj)\mu(s) = \prod_{j < |s|} \lambda_{s_j}(w_j) and define

πk(w0,…,wk−1)=∑∣s∣=kμ(s) us.\pi_k(w_0, \dots, w_{k-1}) = \sum_{|s| = k} \mu(s)\, u_s.

Then π\pi is causal, and for every w∈WNw \in W^N its trajectory is τ=∑ℓμ(ℓ) τℓ\tau = \sum_\ell \mu(\ell)\, \tau_\ell, a convex combination of the leaf trajectories. Hence π\pi is admissible and J(τ)≤max⁡ℓJ(τℓ)J(\tau) \le \max_\ell J(\tau_\ell).

Proof. πk\pi_k uses only w0,…,wk−1w_0, \dots, w_{k-1}. The weights μ(s)\mu(s) over the nodes of one depth are nonnegative and sum to 1, and summing μ\mu over the children sis i of ss gives μ(s)\mu(s). We show xk=∑∣s∣=kμ(s)xsx_k = \sum_{|s| = k} \mu(s) x_s by induction. It holds at k=0k = 0. If it holds at kk, then

xk+1=Axk+Buk+wk=∑∣s∣=kμ(s)(Axs+Bus)+∑iλi(wk)wi=∑∣s∣=k∑iμ(s)λi(wk)(Axs+Bus+wi)=∑∣s′∣=k+1μ(s′)xs′,x_{k+1} = A x_k + B u_k + w_k = \sum_{|s| = k} \mu(s) (A x_s + B u_s) + \sum_i \lambda_i(w_k) w^i = \sum_{|s| = k} \sum_i \mu(s) \lambda_i(w_k) (A x_s + B u_s + w^i) = \sum_{|s'| = k + 1} \mu(s') x_{s'},

using ∑iλi(wk)=1\sum_i \lambda_i(w_k) = 1, ∑sμ(s)=1\sum_s \mu(s) = 1 and (1). Since μ(s)=∑ℓ extends sμ(ℓ)\mu(s) = \sum_{\ell \text{ extends } s} \mu(\ell), both xkx_k and uku_k equal the sums over the leaves of μ(ℓ)\mu(\ell) times the entries of τℓ\tau_\ell, so τ=∑ℓμ(ℓ)τℓ\tau = \sum_\ell \mu(\ell) \tau_\ell. Every τℓ\tau_\ell is in the convex set C\mathcal{C}, so τ\tau is too. JJ is convex, so J(τ)≤∑ℓμ(ℓ)J(τℓ)≤max⁡ℓJ(τℓ)J(\tau) \le \sum_\ell \mu(\ell) J(\tau_\ell) \le \max_\ell J(\tau_\ell). □\square

Theorem 1. The LP is feasible if and only if an admissible causal policy exists, and then JLP(x0)=J∗(x0)J^{\rm LP}(x_0) = J^*(x_0). The infimum in J∗J^* is attained by the interpolated policy of Lemma 3 built from an optimal LP solution, and its first control is the u()u_{()} that the code returns. The same holds for the open-loop form with Jol∗J^*_{\rm ol}, and J∗(x0)≤Jol∗(x0)J^*(x_0) \le J^*_{\rm ol}(x_0).

Proof. Lemma 2 gives JLP≤sup⁡wJJ^{\rm LP} \le \sup_w J for every admissible π\pi, so JLP≤J∗J^{\rm LP} \le J^*. Lemma 3 applied to an optimal LP solution gives an admissible policy with sup⁡wJ≤JLP\sup_w J \le J^{\rm LP}, so J∗≤JLPJ^* \le J^{\rm LP} and the infimum is attained. At k=0k = 0 the sum in Lemma 3 has the one term u()u_{()}. In the open-loop form, the controls at one depth are equal, so the interpolated policy is constant, and Lemma 2 applied to a constant policy gives a point that meets the extra equalities; the same two inequalities follow. An open-loop policy is a causal policy, so J∗≤Jol∗J^* \le J^*_{\rm ol}. □\square

Part 3: the LP solver

lp_min splits each free variable into a difference of two nonnegative ones, adds a slack to each inequality, and multiplies a row by −1-1 when its right side is negative. A row that is an inequality with a nonnegative right side starts with its slack in the basis; every other row gets an artificial variable. Phase 1 minimizes the sum of the artificial variables; the LP is feasible exactly when this minimum is 0. An artificial variable that is still basic at level 0 is pivoted out on any nonzero entry outside the artificial columns; if its row has none, the row is a linear combination of the other rows and is dropped. Phase 2 starts from the resulting feasible basis with the true cost. Both phases use Bland's rule (the entering column is the first one with a negative reduced cost, and ties in the ratio test go to the smallest basic index), which ends after finitely many pivots (Bland 1977). Phase 2 ends at an optimal basis or finds a column with a negative reduced cost and no positive entry, which is a ray along which the cost decreases without bound. In the MPC LP the cost tt is bounded below by 00, so this case does not happen there. With rational data and tol = 0 all operations are exact; _pivot turns an integer pivot into a Fraction so that no float enters.

Part 4: the receding horizon loop

Let the terminal set be robustly positively invariant under a local law u=Kxu = K x: Xf⊆XX_f \subseteq X, and for every x∈Xfx \in X_f, Kx∈UK x \in U and (A+BK)x+w∈Xf(A + B K) x + w \in X_f for all w∈Ww \in W.

Theorem 2. If the feedback LP is feasible from x0x_0, then for every realized disturbance sequence in WW the LP of line L8 is feasible at every sample, and the closed loop meets xk∈Xx_k \in X and uk∈Uu_k \in U for all kk.

Proof. Let the LP be feasible from xx, with the interpolated optimal policy π\pi of Lemma 3, and let w0∈Ww_0 \in W be the realized disturbance, so that the next state is x+=Ax+Bπ0+w0x^+ = A x + B \pi_0 + w_0. Define a policy π+\pi^+ from x+x^+ by πk+(w1,…,wk)=πk+1(w0,w1,…,wk)\pi^+_k(w_1, \dots, w_k) = \pi_{k+1}(w_0, w_1, \dots, w_k) for k<N−1k < N - 1 and πN−1+=KxN\pi^+_{N-1} = K x_N, where xNx_N is the state reached at depth NN of π\pi. This is causal. For every (w1,…,wN)∈WN(w_1, \dots, w_N) \in W^N, the first N−1N - 1 steps follow π\pi under (w0,w1,…,wN−1)(w_0, w_1, \dots, w_{N-1}), so they meet XX and UU and reach xN∈Xfx_N \in X_f; the last step uses KxN∈UK x_N \in U and reaches (A+BK)xN+wN∈Xf⊆X(A + B K) x_N + w_N \in X_f \subseteq X. So π+\pi^+ is admissible from x+x^+, and by Theorem 1 the LP from x+x^+ is feasible. By induction every LP in the loop is feasible. The applied input is u()∈Uu_{()} \in U, and each state of the loop is the root of a feasible LP, so it is in XX. □\square

The open-loop form has no such argument, because the shifted policy needs the feedback KxNK x_N, which is not a constant. In the example of the page, the open-loop problem with N=3N = 3 is infeasible from every state while the feedback problem is feasible from ∣x0∣≤853/432|x_0| \le 853/432.

Part 5: what the code computes

  • Line L1 lists the 1+V+⋯+VN1 + V + \dots + V^N nodes.
  • Line L2 makes one control per inner node (feedback) or per depth (open loop), and one state per node other than the root.
  • Line L3 writes the equalities of (1).
  • Line L4 writes the box rows of XX and UU and the rows of XfX_f at the leaves, and returns None when the given x0x_0 breaks a constraint on the root.
  • Line L5 writes the epigraph rows of Part 1.
  • Lines L6 and L7 solve the LP and return its value J∗(x0)J^*(x_0) (Theorem 1), the first control and the tree.
  • Line L8 is the loop of Theorem 2.

Complexity

The tree has (VN+1−1)/(V−1)(V^{N+1} - 1)/(V - 1) nodes for V≥2V \ge 2, so the LP has LL of order VN(n+m+q)V^N (n + m + q) variables and rows, where qq is the number of constraint rows per node. The dense simplex tableau has O(L2)O(L^2) entries, and each pivot costs O(L2)O(L^2), so the time is O(IL2)O(I L^2) for II pivots. The simplex method can need exponentially many pivots in the worst case; an interior point method solves the LP in time polynomial in LL. The size is exponential in the horizon in any case, which limits exact feedback min-max MPC to short horizons and few vertices. The open-loop form has only NmN m input variables, but its constraints still range over all VNV^N vertex sequences.

Properties

  • Exact for the polytope. The worst case over the vertex sequences equals the worst case over all sequences in the polytope, for both forms, because the plant is linear and the cost and constraints are convex.
  • Feedback is never worse. The feedback value is at most the open-loop value, and its feasible region contains the open-loop one, often strictly.
  • Recursive feasibility of the feedback form, when the terminal set is robustly positively invariant under a local law that meets the constraints. The open-loop form has no such guarantee.
  • Guaranteed constraints for every disturbance in the set, as long as the model and the set are right.
  • Conservative cost. The controller plans for the worst case. Under typical disturbances, the performance can be worse than that of a nominal or stochastic MPC.

Variants and improvements

  • Infinity-norm costs. Replace the sum by a maximum; the problem is still an LP. Quadratic costs give a convex quadratically constrained program (an SOCP) for the open-loop form, since the epigraph bound tt must lie above a quadratic cost for each vertex sequence, and a convex problem over the tree for the feedback form.
  • Explicit solution. With 1-norm or infinity-norm costs, the first input is a piecewise affine function of x0x_0, and it can be computed offline as in explicit MPC.
  • Affine disturbance feedback. Restrict the policy to inputs affine in the past disturbances. The problem is then convex with size polynomial in NN, at the price of some conservatism.
  • Tube MPC. Fix the feedback to u=v+K(x−z)u = v + K (x - z) with a nominal state zz, and plan only vv with tightened constraints. The size does not grow with the number of vertices.
  • Model uncertainty. If AA and BB lie in a polytope instead of an additive disturbance, the tree branches over the vertex models. Kothare, Balakrishnan and Morari (1996) gave an LMI form with a state feedback law for this case.

When to use it

Use min-max MPC when the disturbance is bounded but has no useful probability law, the constraints are hard, and the system is small with a short horizon. The feedback form is the reference solution for robust linear MPC: other methods are often judged by how close they come to its value and feasible region. For larger systems or longer horizons, use tube MPC or affine disturbance feedback. If the disturbance has a known distribution and small violations are acceptable, use stochastic MPC. If a small disturbance only needs to be rejected near a setpoint, offset-free MPC is simpler.

Pitfalls

  • Open loop in place of feedback. The open-loop form plans as if no new information will come. It is very conservative for unstable plants and can be infeasible for every state, as in the example.
  • Exponential size. The tree has VNV^N leaves. A box disturbance in Rd\mathbb{R}^d has 2d2^d vertices, so the tree grows like 2dN2^{d N}.
  • Wrong disturbance set. The guarantees hold only for disturbances in WW. A set that is too small gives false confidence, and one that is too large gives a small feasible region.
  • No terminal set. Without a robustly invariant terminal set the loop can become infeasible after a few steps, even if the first problem is feasible.
  • Sampled vertices. Planning against a few sampled disturbance sequences instead of all vertex sequences is not the min-max problem and gives no guarantee.

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.

min_max_mpc.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/min-max-mpc/. The authors are listed in prov/SE9461.jsonl.

"""Min-max MPC with 1-norm costs, by one linear program on a scenario tree.

The plant is x_(k+1) = A x_k + B u_k + w_k with w_k in the convex hull of the
given vertices. The cost of a horizon is

    sum_(k < N) (|Q x_k|_1 + |R u_k|_1) + |P x_N|_1,

with the constraints |x_k|_i <= x_max_i, |u_k|_j <= u_max_j and F x_N <= f.
The tree has one branch per vertex at each step. In the feedback form each
node has its own control (the control may depend on the past disturbances);
in the open-loop form all nodes at the same depth share one control.

Matrices are lists of rows and vectors flat lists. The LP solver is a dense
two-phase simplex method with Bland's rule.
"""

from fractions import Fraction

__all__ = ["lp_min", "min_max_mpc", "closed_loop", "path_cost"]


def _pivot(T, obj, r, c):
    """Pivot on T[r][c]; obj is the reduced cost row and is updated too."""
    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):
    """Bland's rule on columns below limit. Returns False if the objective is unbounded below."""
    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.

    The variables in nonneg are >= 0, the others are free. Returns (value, z),
    or None if the LP is infeasible. Raises ValueError if it is unbounded.
    """
    n = len(c)
    nonneg = set(nonneg)
    free = [j for j in range(n) if j not in nonneg]
    # Columns: z_j (or its positive part), the negative parts of the free variables, slacks, artificials.
    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:
        # Phase 1: minimize the sum of the artificial variables.
        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  # a redundant equation
                _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 min_max_mpc(A, B, x0, N, vertices, Q, R, P, x_max, u_max, F, f, feedback=True, tol=1e-9):
    """Solve the min-max problem from x0. Returns (value, u0, tree) or None if infeasible.

    tree maps each node (a tuple of vertex indices, the past disturbances) to
    its state, and each inner node to ("u", control).
    """
    n, m = len(A), len(B[0])
    var = []  # names of the LP variables, for reading the answer

    def new(name):
        var.append(name)
        return len(var) - 1

    # @line L1
    nodes = [()]
    for k in range(N):
        nodes += [p + (i,) for p in nodes if len(p) == k for i in range(len(vertices))]
    inner = [p for p in nodes if len(p) < N]
    # @line L2
    if feedback:
        u_idx = {p: [new(("u", p, j)) for j in range(m)] for p in inner}
    else:
        shared = {k: [new(("u", k, j)) for j in range(m)] for k in range(N)}
        u_idx = {p: shared[len(p)] for p in inner}
    x_idx = {p: [new(("x", p, i)) for i in range(n)] for p in nodes if p}
    t = new("t")
    nonneg = [t]
    G, g, E, e = [], [], [], []

    def row(coef):
        r = [0] * len(var)
        for j, v in coef.items():
            r[j] = r[j] + v
        return r

    # @line L3
    for p in nodes:
        if not p:
            continue
        q, w = p[:-1], vertices[p[-1]]
        for i in range(n):
            coef = {x_idx[p][i]: 1}
            const = w[i]
            for j in range(n):
                if q:
                    coef[x_idx[q][j]] = coef.get(x_idx[q][j], 0) - A[i][j]
                else:
                    const += A[i][j] * x0[j]
            for j in range(m):
                coef[u_idx[q][j]] = coef.get(u_idx[q][j], 0) - B[i][j]
            E.append(coef)
            e.append(const)
    # Epigraph variables for the stage and terminal costs.
    s_idx = {}
    for p in nodes:
        Wt = P if len(p) == N else Q
        s_idx[p] = []
        for r_ in range(len(Wt)):
            s = new(("s", p, r_))
            nonneg.append(s)
            s_idx[p].append(s)
    r_vars = {}
    for p in inner:
        key = p if feedback else len(p)
        if key not in r_vars:
            r_vars[key] = []
            for r_ in range(len(R)):
                s = new(("r", key, r_))
                nonneg.append(s)
                r_vars[key].append(s)
    # Now every variable exists; build the rows.
    E = [row(cf) for cf in E]
    # @line L4
    for p in nodes:
        if p:
            for i in range(n):
                G.append(row({x_idx[p][i]: 1}))
                g.append(x_max[i])
                G.append(row({x_idx[p][i]: -1}))
                g.append(x_max[i])
        elif any(abs(x0[i]) > x_max[i] for i in range(n)):
            return None
        if len(p) == N:
            for fr, fb in zip(F, f):
                if p:
                    G.append(row({x_idx[p][i]: fr[i] for i in range(n)}))
                    g.append(fb)
                elif sum(a * b for a, b in zip(fr, x0)) > fb:
                    return None
    for p in inner:
        for j in range(m):
            G.append(row({u_idx[p][j]: 1}))
            g.append(u_max[j])
            G.append(row({u_idx[p][j]: -1}))
            g.append(u_max[j])
    # @line L5
    for p in nodes:
        Wt = P if len(p) == N else Q
        for r_, wr in enumerate(Wt):
            for sg in (1, -1):
                coef = {s_idx[p][r_]: -1}
                const = 0
                for i in range(n):
                    if p:
                        coef[x_idx[p][i]] = coef.get(x_idx[p][i], 0) + sg * wr[i]
                    else:
                        const += sg * wr[i] * x0[i]
                G.append(row(coef))
                g.append(-const)
    for p in inner:
        key = p if feedback else len(p)
        for r_, rr in enumerate(R):
            for sg in (1, -1):
                coef = {r_vars[key][r_]: -1}
                for j in range(m):
                    coef[u_idx[p][j]] = coef.get(u_idx[p][j], 0) + sg * rr[j]
                G.append(row(coef))
                g.append(0)
    for leaf in [p for p in nodes if len(p) == N]:
        coef = {t: -1}
        for k in range(N + 1):
            p = leaf[:k]
            for s in s_idx[p]:
                coef[s] = coef.get(s, 0) + 1
            if k < N:
                for s in r_vars[p if feedback else k]:
                    coef[s] = coef.get(s, 0) + 1
        G.append(row(coef))
        g.append(0)
    c = [0] * len(var)
    c[t] = 1
    # @line L6
    sol = lp_min(c, G, g, E, e, nonneg, tol)
    if sol is None:
        return None
    val, z = sol
    tree = {(): list(x0)}
    for p in nodes:
        if p:
            tree[p] = [z[j] for j in x_idx[p]]
    for p in inner:
        tree[("u",) + p] = [z[j] for j in u_idx[p]]
    # @line L7
    return val, [z[j] for j in u_idx[()]], tree


def path_cost(A, B, x0, us, ws, Q, R, P):
    """Cost of the input sequence us under the disturbance sequence ws."""
    x = list(x0)
    J = 0
    for u, w in zip(us, ws):
        J += sum(abs(sum(q * xi for q, xi in zip(row, x))) for row in Q)
        J += sum(abs(sum(r * ui for r, ui in zip(row, u))) for row in R)
        x = [sum(a * xi for a, xi in zip(Ar, x)) + sum(b * ui for b, ui in zip(Br, u)) + wi
             for Ar, Br, wi in zip(A, B, w)]
    return J + sum(abs(sum(p * xi for p, xi in zip(row, x))) for row in P), x


def closed_loop(A, B, x0, N, vertices, Q, R, P, x_max, u_max, F, f, disturbances, feedback=True):
    """Receding horizon: apply the first control of each min-max problem. Returns (xs, us, values)."""
    x = list(x0)
    xs, us, vals = [list(x)], [], []
    for w in disturbances:  # @line L8
        sol = min_max_mpc(A, B, x, N, vertices, Q, R, P, x_max, u_max, F, f, feedback)
        if sol is None:
            raise RuntimeError("the min-max problem became infeasible")
        val, u, _ = sol
        x = [sum(a * xi for a, xi in zip(Ar, x)) + sum(b * ui for b, ui in zip(Br, u)) + wi
             for Ar, Br, wi in zip(A, B, w)]
        xs.append(x)
        us.append(u)
        vals.append(val)
    return xs, us, vals
test_min_max_mpc.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/min-max-mpc/. The authors are listed in prov/SE9461.jsonl.

import itertools
import random
from fractions import Fraction as Fr

import pytest

from min_max_mpc import closed_loop, lp_min, min_max_mpc, path_cost

# The example of the page: x+ = 1.2 x + u + w, |w| <= 0.2, |u| <= 1, |x_N| <= 0.5.
A = [[Fr(6, 5)]]
B = [[1]]
V = [[Fr(-1, 5)], [Fr(1, 5)]]
Q = [[1]]
R = [[Fr(1, 10)]]
P = [[3]]
REST = ([10], [1], [[1], [-1]], [Fr(1, 2), Fr(1, 2)])


def test_lp_small_cases():
    # min x + y with x + y >= 1, x - y = 1/3, both free: value 1 at x = 2/3.
    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_lp_against_vertex_enumeration():
    rng = random.Random(7)
    for _ in range(40):
        k = rng.randint(1, 5)
        G = [[rng.uniform(-1, 1), rng.uniform(-1, 1)] for _ in range(k)]
        g = [rng.uniform(-0.5, 1.0) for _ in range(k)]
        G += [[1, 0], [-1, 0], [0, 1], [0, -1]]
        g += [1, 1, 1, 1]
        c = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        best = None
        for i, j in itertools.combinations(range(len(G)), 2):
            det = G[i][0] * G[j][1] - G[i][1] * G[j][0]
            if abs(det) < 1e-9:
                continue
            z = [(g[i] * G[j][1] - G[i][1] * g[j]) / det, (G[i][0] * g[j] - g[i] * G[j][0]) / det]
            if all(r[0] * z[0] + r[1] * z[1] <= b + 1e-9 for r, b in zip(G, g)):
                v = c[0] * z[0] + c[1] * z[1]
                best = v if best is None else min(best, v)
        sol = lp_min(c, G, g)
        assert (sol is None) == (best is None)
        if sol is not None:
            assert abs(sol[0] - best) < 1e-8


def test_example_values_are_exact():
    got = {}
    for N, x0 in [(1, 0), (1, Fr(1, 2)), (2, 0), (2, Fr(1, 2))]:
        fb = min_max_mpc(A, B, [x0], N, V, Q, R, P, *REST, feedback=True, tol=0)
        ol = min_max_mpc(A, B, [x0], N, V, Q, R, P, *REST, feedback=False, tol=0)
        got[N, x0] = (fb[0], ol[0], fb[1][0])
    assert got[1, 0] == (Fr(3, 5), Fr(3, 5), 0)
    assert got[1, Fr(1, 2)] == (Fr(29, 25), Fr(29, 25), Fr(-3, 5))
    assert got[2, 0] == (Fr(103, 125), Fr(38, 25), 0)
    assert got[2, Fr(1, 2)] == (Fr(173, 125), Fr(52, 25), Fr(-3, 5))
    # With N = 3 the open-loop spread 0.2 (1.44 + 1.2 + 1) = 0.728 does not fit in |x_3| <= 0.5.
    Af, Vf, Rf = [[1.2]], [[-0.2], [0.2]], [[0.1]]
    rest = ([10.0], [1.0], [[1.0], [-1.0]], [0.5, 0.5])
    assert min_max_mpc(Af, B, [0.0], 3, Vf, Q, Rf, P, *rest, feedback=False) is None
    assert abs(min_max_mpc(Af, B, [0.0], 3, Vf, Q, Rf, P, *rest)[0] - 131 / 125) < 1e-9


def scalar_value(a, b, x, k, N, ws, q, r, p, xmax, umax, f, step):
    """Worst-case cost to go from x at depth k, by dynamic programming over u."""
    if abs(x) > xmax + 1e-12:
        return float("inf")
    if k == N:
        return p * abs(x) if abs(x) <= f + 1e-12 else float("inf")
    if k == N - 1:
        # The cost is convex and piecewise linear in u, so the minimum is at a breakpoint.
        bound = min(xmax, f)
        lo = max(-umax, max((-bound - a * x - w) / b if b > 0 else (bound - a * x - w) / b for w in ws))
        hi = min(umax, min((bound - a * x - w) / b if b > 0 else (-bound - a * x - w) / b for w in ws))
        if lo > hi + 1e-12:
            return float("inf")
        # Kinks of |u|, of each |a x + b u + w|, and where two branches of the max cross.
        cands = [lo, hi, 0.0] + [(-a * x - w) / b for w in ws]
        cands += [(-a * x - (w1 + w2) / 2) / b for w1 in ws for w2 in ws]
        cands = [min(hi, max(lo, u)) for u in cands]
        return q * abs(x) + min(r * abs(u) + max(p * abs(a * x + b * u + w) for w in ws) for u in cands)
    best = float("inf")
    for i in range(int(round(2 * umax / step)) + 1):
        u = -umax + i * step
        v = r * abs(u) + max(scalar_value(a, b, a * x + b * u + w, k + 1, N, ws, q, r, p, xmax, umax, f, step)
                             for w in ws)
        best = min(best, v)
    return q * abs(x) + best


def test_dynamic_programming_brute_force():
    rng = random.Random(11)
    for _ in range(6):
        a, b = rng.uniform(0.6, 1.5), rng.choice([-1, 1]) * rng.uniform(0.6, 1.4)
        wb = rng.uniform(0.05, 0.25)
        q, r, p = rng.uniform(0.2, 1), rng.uniform(0.05, 0.5), rng.uniform(1, 3)
        x0 = rng.uniform(-1.5, 1.5)
        N = rng.choice([1, 2])
        sol = min_max_mpc([[a]], [[b]], [x0], N, [[-wb], [wb]], [[q]], [[r]], [[p]],
                          [3.0], [1.0], [[1.0], [-1.0]], [0.5, 0.5])
        dp = scalar_value(a, b, x0, 0, N, [-wb, wb], q, r, p, 3.0, 1.0, 0.5, 0.002)
        if sol is None:
            assert dp == float("inf")
        else:
            assert sol[0] <= dp + 1e-9
            assert dp <= sol[0] + (1e-9 if N == 1 else 0.02)


def test_feedback_never_worse_than_open_loop():
    rng = random.Random(2)
    Af, Vf, Rf = [[1.2]], [[-0.2], [0.2]], [[0.1]]
    rest = ([10.0], [1.0], [[1.0], [-1.0]], [0.5, 0.5])
    for _ in range(10):
        x0 = rng.uniform(-1.5, 1.5)
        fb = min_max_mpc(Af, B, [x0], 2, Vf, Q, Rf, P, *rest)
        ol = min_max_mpc(Af, B, [x0], 2, Vf, Q, Rf, P, *rest, feedback=False)
        assert fb is not None and ol is not None
        assert fb[0] <= ol[0] + 1e-9
        # The open-loop value is the worst case of the open-loop inputs over the vertex sequences.
        us = [ol[2][("u",) + (0,) * k] for k in range(2)]
        worst = max(path_cost(Af, B, [x0], us, ws, Q, Rf, P)[0] for ws in itertools.product(Vf, repeat=2))
        assert abs(worst - ol[0]) < 1e-9


def test_vertex_policy_covers_the_whole_disturbance_set():
    # Interpolating the vertex controls gives a causal policy for every w in the hull,
    # and its cost never exceeds the min-max value (two states, four vertices).
    rng = random.Random(5)
    A2 = [[1.0, 0.5], [0.0, 1.0]]
    B2 = [[0.125], [0.5]]
    V2 = [[0.05 * s, 0.05 * t] for s in (-1, 1) for t in (-1, 1)]
    Q2 = [[1.0, 0.0], [0.0, 1.0]]
    R2 = [[0.2]]
    P2 = [[2.0, 1.0], [0.0, 2.0]]
    F2 = [[1.0, 0.0], [-1.0, 0.0], [0.0, 1.0], [0.0, -1.0]]
    f2 = [0.6, 0.6, 0.6, 0.6]
    x0 = [0.4, -0.3]
    val, u0, tree = min_max_mpc(A2, B2, x0, 2, V2, Q2, R2, P2, [2.0, 2.0], [1.0], F2, f2)
    for _ in range(30):
        lam = [[rng.random() for _ in V2] for _ in range(2)]
        lam = [[v / sum(row) for v in row] for row in lam]
        ws = [[sum(l * vv[i] for l, vv in zip(row, V2)) for i in range(2)] for row in lam]
        u1 = [sum(lam[0][i] * tree[("u", i)][0] for i in range(4))]
        J, xN = path_cost(A2, B2, x0, [u0, u1], ws, Q2, R2, P2)
        assert J <= val + 1e-9
        assert all(sum(a * x for a, x in zip(row, xN)) <= b + 1e-9 for row, b in zip(F2, f2))
        assert abs(u1[0]) <= 1 + 1e-12


def test_closed_loop_stays_feasible():
    Af, Vf, Rf = [[1.2]], [[-0.2], [0.2]], [[0.1]]
    rest = ([10.0], [1.0], [[1.0], [-1.0]], [0.5, 0.5])
    rng = random.Random(3)
    ws = [[rng.uniform(-0.2, 0.2)] for _ in range(12)]
    xs, us, vals = closed_loop(Af, B, [1.5], 2, Vf, Q, Rf, P, *rest, ws)
    assert all(abs(u[0]) <= 1 + 1e-9 for u in us)
    assert all(abs(x[0]) <= 0.5 + 1e-9 for x in xs[2:])
    xs, us, vals = closed_loop(Af, B, [1.0], 2, Vf, Q, Rf, P, *rest, [[0.0]] * 4)
    assert abs(xs[1][0] - 0.2) < 1e-9 and all(abs(x[0]) < 1e-9 for x in xs[2:])

History

Campo and Morari (1987) brought the worst case cost into MPC and showed that the 1-norm and infinity-norm problems are linear programs. Open-loop min-max MPC was soon found to be conservative, and Scokaert and Mayne (1998) proposed the feedback form, which optimizes one control for each vertex sequence and has feasibility and stability guarantees. The survey of Mayne, Rawlings, Rao and Scokaert (2000) placed min-max MPC in the general theory of MPC stability. Later work reduced the cost of robust MPC with explicit solutions, affine disturbance feedback, and tubes.

References

  1. Pedro J. Campo and Manfred Morari, Robust model predictive control, Proceedings of the American Control Conference, 1021-1026, 1987, the worst case formulation of MPC and its solution by linear programming for 1-norm and infinity-norm costs
  2. Pierre O. M. Scokaert and David Q. Mayne, Min-max feedback model predictive control for constrained linear systems, IEEE Transactions on Automatic Control 43(8), 1136-1142, 1998, the feedback min-max problem with one control per vertex sequence, and its feasibility and stability properties
  3. David Q. Mayne, James B. Rawlings, Christopher V. Rao and Pierre O. M. Scokaert, Constrained model predictive control, stability and optimality, Automatica 36(6), 789-814, 2000, the section on robust MPC, with open-loop and feedback min-max formulations
  4. 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

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