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
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , , the vertices of the disturbance set , a horizon , weights , , , bounds , , a terminal set , and the current state .
The plant is with . The cost of one trajectory is
Output: an input that is the first input of an optimal policy for
where the policy chooses as a function of (feedback form) or as a constant (open-loop form). If no policy meets the constraints, report that the problem is infeasible.
The algorithm
MIN-MAX-MPC(A, B, x₀, N, w¹..wⱽ, Q, R, P, x̄, ū, F, f)- 1
nodes ← all sequences s of vertex indices with |s| ≤ N ▷ the scenario tree - 2
variables: x_s for each node, u_s for each inner node (feedback) or one u per depth (open loop) - 3
for each node s and vertex i: x_{s i} = A x_s + B u_s + wⁱ - 4
|x_s| ≤ x̄ at each node, |u_s| ≤ ū at each inner node, F x_ℓ ≤ f at each leaf ℓ - 5
t ≥ (cost along the path to ℓ) for each leaf ℓ, with each |·| as an epigraph variable - 6
solve the LP: minimize t subject to L3 to L5 - 7
return t and u_() at the root - 8
at each sample: measure x, set x₀ ← x, run L1 to L7, apply u_()
Line L5 writes each absolute value as a variable with and , and bounds from below by the sum of these variables along each path. At the optimum each equals its absolute value, and 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 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 with , so the vertices are . The weights are , , , the input bound is , and the terminal set is . The plant alone is unstable.
From with . In the feedback form, , so . On the branch the second input is , which cancels and leaves ; the other branch is the mirror image. The worst path cost is . In the open-loop form, must be the same on both branches, the best choice is , and the worst final state is , so the value is . Feedback cuts the worst case cost by almost half.
| , | feedback value | open-loop value | first input |
|---|---|---|---|
| , | |||
| , | |||
| , | |||
| , | |||
| , | infeasible |
Where open loop fails. With a fixed input sequence, the spread of caused by the disturbances is , which does not fit in . So the open-loop problem with is infeasible from every state. The feedback problem is feasible exactly for , and for : 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 from and , the inputs are and , and the state goes and stays at 0. With random disturbances in every problem stays feasible, as Theorem 2 of the proof says, because the terminal set is robustly invariant under : then , and .
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 with . The horizon is . The constraints are for , for , and . The cost of one trajectory is
is a convex function of , and the constraint set is convex.
A causal policy is a list of maps , so that . It is admissible from if the trajectory meets for every . The feedback min-max value is
The open-loop value is the same with each a constant.
The tree. A node is a sequence of vertex indices with ; its depth is . The root is the empty sequence. A node of depth is a leaf. The LP of min_max_mpc (feedback form) has a state at each node with , a control at each inner node, the constraints
and the objective with for each leaf , where is the trajectory along the path from the root to : with the prefix of length . In the open-loop form, all inner nodes of the same depth share one control.
Part 1: the epigraph rows
The code writes with nonnegative variables: for each node and row , for each inner node, and (line L5).
Lemma 1. For fixed that meet (1), the least that is feasible with some choice of the epigraph variables is .
Proof. Each and each , so every feasible is at least for each . Setting every epigraph variable equal to its absolute value is feasible and gives .
So the optimal value of the LP is
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 is admissible from , then and the resulting states meet (1), and .
Proof. The path to a leaf is the trajectory of under the vertex sequence . It meets because is admissible, and its cost is one of the values in the supremum. Two nodes with the same prefix get the same control because is causal.
Lemma 3 (interpolation). Let meet (1). For each and each fix weights with and . For a disturbance sequence , let and define
Then is causal, and for every its trajectory is , a convex combination of the leaf trajectories. Hence is admissible and .
Proof. uses only . The weights over the nodes of one depth are nonnegative and sum to 1, and summing over the children of gives . We show by induction. It holds at . If it holds at , then
using , and (1). Since , both and equal the sums over the leaves of times the entries of , so . Every is in the convex set , so is too. is convex, so .
Theorem 1. The LP is feasible if and only if an admissible causal policy exists, and then . The infimum in is attained by the interpolated policy of Lemma 3 built from an optimal LP solution, and its first control is the that the code returns. The same holds for the open-loop form with , and .
Proof. Lemma 2 gives for every admissible , so . Lemma 3 applied to an optimal LP solution gives an admissible policy with , so and the infimum is attained. At the sum in Lemma 3 has the one term . 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 .
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 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 is bounded below by , 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 : , and for every , and for all .
Theorem 2. If the feedback LP is feasible from , then for every realized disturbance sequence in the LP of line L8 is feasible at every sample, and the closed loop meets and for all .
Proof. Let the LP be feasible from , with the interpolated optimal policy of Lemma 3, and let be the realized disturbance, so that the next state is . Define a policy from by for and , where is the state reached at depth of . This is causal. For every , the first steps follow under , so they meet and and reach ; the last step uses and reaches . So is admissible from , and by Theorem 1 the LP from is feasible. By induction every LP in the loop is feasible. The applied input is , and each state of the loop is the root of a feasible LP, so it is in .
The open-loop form has no such argument, because the shifted policy needs the feedback , which is not a constant. In the example of the page, the open-loop problem with is infeasible from every state while the feedback problem is feasible from .
Part 5: what the code computes
- Line L1 lists the 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 and and the rows of at the leaves, and returns
Nonewhen the given 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 (Theorem 1), the first control and the tree.
- Line L8 is the loop of Theorem 2.
Complexity
The tree has nodes for , so the LP has of order variables and rows, where is the number of constraint rows per node. The dense simplex tableau has entries, and each pivot costs , so the time is for pivots. The simplex method can need exponentially many pivots in the worst case; an interior point method solves the LP in time polynomial in . 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 input variables, but its constraints still range over all 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 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 , 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 , at the price of some conservatism.
- Tube MPC. Fix the feedback to with a nominal state , and plan only with tightened constraints. The size does not grow with the number of vertices.
- Model uncertainty. If and 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 leaves. A box disturbance in has vertices, so the tree grows like .
- Wrong disturbance set. The guarantees hold only for disturbances in . 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SE9461 Edit this page History Report an error Markdown