Algorithmadvanced
Explicit MPC
Also called explicit model predictive control.
Solves the linear MPC quadratic program offline for all states as a multiparametric QP, so the online controller only finds the polyhedral region of x and applies its affine law.
- Time
- O(2^c (N^3 m^3 + c N m n + L)) worstO(M (c + n) n) online
- Space
- O(M (c + n) (n + N m)) extra
- Where
- L = the cost of one linear program in n + 1 variables; M = the number of regions; N = the horizon; c = the number of constraint rows of the QP; m = the number of inputs; n = the number of states
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alberto Bemporad, Manfred Morari, Vivek Dua, Efstratios N. Pistikopoulos, 2002
Explicit MPC computes the linear MPC law for every state in advance. The MPC quadratic program depends on the state only through its linear term and its right-hand side, so it is a multiparametric quadratic program (mp-QP) with the parameter . Bemporad, Morari, Dua and Pistikopoulos (2002) showed that its solution is a continuous piecewise affine function of : the feasible states split into finitely many polyhedral critical regions, one per optimal active set, and on each region the optimal plan is . Explicit MPC computes the regions and the gains offline. Online, the controller finds the region that contains the measured state and applies one affine law, with no QP solver. The price is the number of regions: it is exponential in the number of constraints in the worst case, and the counts of real problems are measurements.
In plain words
Online MPC solves an optimization problem at every tick. For a linear model, a quadratic cost and linear limits, that problem changes in a simple way with the state. For each choice of which limits are tight, the best plan is a fixed linear formula of the state. The states where that choice is the right one form a region with flat sides. So you can solve the problem for all states before the system runs. You store a list of regions, each with its own formula. At run time the controller only checks which region holds the state and evaluates that formula. This needs little computing power and gives a fixed run time, which helps on small hardware and for fast systems.
The problem
Input: the mp-QP of a linear MPC problem,
with of size (the stacked inputs), constraint rows, and a box of states of interest. Output: a list of regions , each a polyhedron with an affine law , such that the regions cover and for . The online problem is: given , return , or report that .
The law of one active set. For a set of rows with linearly independent (the linear independence constraint qualification, LICQ), the KKT conditions with exactly the rows active are linear in and give
The critical region of is the set of where is feasible and . Both conditions are affine inequalities in , so it is a polyhedron.
The algorithm
EXPLICIT-MPC(H, F, G, w, E, box) ▷ offline- 1
regions ← ∅ - 2
for each set A of at most s rows of G ▷ candidate active sets - 3
M ← G_A H⁻¹ G_Aᵀ; skip A if M is singular ▷ LICQ - 4
λ_A(x) = L x + l: L ← -M⁻¹ (E_A + G_A H⁻¹ F), l ← -M⁻¹ w_A - 5
z_A(x) = K x + k: K ← -H⁻¹ (F + G_Aᵀ L), k ← -H⁻¹ G_Aᵀ l - 6
CR ← {x in box : G (K x + k) ≤ w + E x, L x + l ≥ 0} - 7
if the Chebyshev radius of CR is > ε then add (A, CR, K, k) to regions - 8
return regions EVALUATE(regions, x) ▷ online, at each sampling instant- 9
for each (A, CR, K, k) in regions - 10
if x ∈ CR then return K x + k - 11
return "x is not in the covered set"
Line L2 enumerates every set of at most rows. Larger sets cannot have linearly independent rows in , and line L3 drops the dependent ones. Lines L4 and L5 are the formulas above. Line L6 writes the region as inequalities in : primal feasibility of for all rows, and dual feasibility of the multipliers. Line L7 solves one linear program for the Chebyshev radius, the radius of the largest ball inside ; a positive radius means the region has an interior point, and regions without one are dropped. The online part is a sequential search. Only the first entries of are needed online, so a controller stores only the first rows of and .
This enumeration is the simplest correct method, close in spirit to the combinatorial method of Gupta, Bhartiya and Nataraj (2011), which prunes the candidate sets. Bemporad et al. (2002) explore the parameter space instead, and Tøndel, Johansen and Bemporad (2003) step from a region to its neighbors across facets. All of them return the same partition up to regions without interior points.
Example
Take the double integrator of the linear MPC page, , , , , the DARE solution as terminal weight , the horizon and only the input limits . The mp-QP has variables and rows, in the order , , , , , . The box is .
- Candidates. There are sets of at most 3 rows. A set that contains both limits of the same input has a singular and is skipped, which leaves sets.
- Regions. 19 of the 27 regions have an interior point inside the box (measurement with the implementation).
- The unconstrained region () contains the origin and has the law , the LQR law .
- One input limit active. For the law is . For it is . The regions with active have the same gains with the opposite offsets.
- Saturated regions. In 14 regions or . So the first input has only 7 different affine pieces on the 19 regions.
Online evaluation. For the search finds the region of , and the law gives . As in the linear MPC example with from the same state, only the row is active. For the region is and . The tests compare the law with a brute-force QP solution at 300 random states and find agreement to .
Region counts. For the same plant with inside (measurement with the implementation):
| rows | regions | |
|---|---|---|
| 2 | 4 | 9 |
| 3 | 6 | 19 |
| 4 | 8 | 33 |
| 5 | 10 | 43 |
With the state limits added and , the covered set shrinks: the state , for which no input meets the limits, lies in no region.
Correctness
The proofs are in proofs/correctness.md.
- One active set gives an affine law. If has independent rows, is positive definite, so the linear KKT system with the rows active has the unique solution of the formulas above, affine in .
- Inside its region the law is optimal. For , is feasible, , complementarity holds because the rows in are active, and stationarity holds by construction. For a convex QP the KKT conditions are sufficient, and makes the minimizer unique.
- Every feasible state is in some region. At the optimum , the vector is a nonnegative combination of the active rows. By Carathéodory's theorem for cones, a linearly independent subset of the active rows is enough. That subset is a set of line L2 with .
- The kept regions cover . Regions without interior points lie in proper affine subspaces, which have measure zero. If has an interior point, a finite union of such sets cannot contain the open set that a missed point would need, so the full-dimensional regions alone cover .
- The online search is correct. By point 4, a state in lies in a kept region, and by point 2 its law gives . Every region lies in , so a state outside is in none.
The law is continuous on , because the affine pieces agree on shared boundaries (both equal the unique minimizer). The value function is convex, because the MPC cost is jointly convex in , and it is quadratic on each region.
Proof: The critical regions of the independent active sets cover the feasible states, and on each region the MPC input is the stored affine lawfull
The MPC problem at the state is the multiparametric quadratic program
with , and rows in . For a fixed the problem is strictly convex, so if it is feasible it has exactly one minimizer , and is that minimizer if and only if there is with
Let be the box of states given to the algorithm and . The set is the projection of the polyhedron , so it is a convex polyhedron.
Lemma 1: the affine law of one active set
Let be a set whose rows are linearly independent. Then the system
has, for every , exactly one solution, given by
Proof. is positive definite: for , by independence, so . The first equation gives . Substituting it into the second gives , which has the single solution stated.
These are lines L3 to L5. Both maps are affine in , so line L6 defines a polyhedron
Lemma 2: inside a region the law is optimal
If , then , and equal to on and 0 elsewhere is a KKT multiplier.
Proof. Stationarity holds by Lemma 1. Feasibility and are the inequalities of . Complementarity holds because off and the rows in hold with equality. So (KKT) holds, and is the unique minimizer.
Lemma 3: every feasible state is in some region
If , there is a set with independent rows and .
Proof. Let and let be the set of active rows at . By (KKT), lies in the cone generated by . By Carathéodory's theorem for cones, it is a nonnegative combination of a subset whose vectors are linearly independent. Then and solve the system of Lemma 1 for this , because the rows in are active, and by uniqueness and . Since is feasible, .
Lemma 3 is why the enumeration of line L2 only needs sets of at most rows: an independent set in has at most elements.
Theorem 1: the kept regions cover the feasible box
Assume has an interior point. Let be the union of the regions that have an interior point (the ones kept by line L7 in exact arithmetic, where the test is radius ). Then .
Proof. Each by Lemma 2, so . By Lemma 3, is the union of all the regions, of which there are finitely many. Suppose . is a finite union of closed sets, so it is closed, and some open ball around misses . Because is convex with an interior point and , the set is open and not empty (the segment from to an interior point of enters at once). This open set lies in the union of the regions without interior points. Each of them lies in a proper affine subspace, which has Lebesgue measure 0, and a finite union of null sets cannot contain a nonempty open set. This is a contradiction.
The Chebyshev radius computed in line L7 is positive if and only if the polyhedron has an interior point, because a polyhedron with an interior point contains a ball and a ball is an interior neighborhood of its center. In floating point the code keeps a region only when the radius exceeds a small , so a region thinner than can be lost, and the search then finds no region for the states inside it. With in exact arithmetic nothing is lost.
Theorem 2: the online evaluation is correct
For , lines L9 to L11 return . For they report that no region contains .
Proof. If , Theorem 1 gives a kept region that contains , so the search finds a first region and returns , which is by Lemma 2. Different regions may share boundary points, but every region that contains gives the same value, since the minimizer is unique. If , no region contains , because every region lies in .
Consequences: continuity and convexity
The law is continuous on . On each kept region is affine, so continuous. The regions are finitely many closed sets that cover , and on any intersection the affine laws agree (both equal ). By the pasting lemma for finitely many closed sets, is continuous on .
The value function is convex and piecewise quadratic. For the MPC cost, the horizon cost is with the block matrix , because is a sum of nonnegative quadratic terms in . The set is convex. The minimum of a jointly convex function over the section of a convex set is a convex function of , so is convex on . On each region is quadratic in .
Limits of the enumeration
The algorithm needs neither strict complementarity nor a nondegenerate problem: Lemma 3 picks an independent subset of the active rows even when more than rows are active at the solution. The price is the enumeration of sets, each with an solve and a linear program. When has no interior point (for example when equality constraints are written as two inequalities), Theorem 1 does not apply and the radius test drops every region; such problems must first be reduced to a lower dimension.
Complexity
Costs are in the real-RAM model, with variables and rows.
- Offline. Line L2 visits sets. Each costs for the solves of lines L3 to L5, to write the region, and one LP for the Chebyshev radius. The total is . This is a theorem about this enumeration; exploration methods visit fewer sets in practice, but they share the bound below on the output.
- Number of regions. Each region belongs to a different active set with independent rows, so . The bound is exponential in the number of constraints, and the count can grow quickly with . The counts in the table are measurements.
- Online. The sequential search tests at most regions with inequalities each, so in the worst case. A binary search tree over the hyperplanes of the partition (Tøndel, Johansen and Bemporad 2003) gives a time logarithmic in for a balanced tree; building the tree is an offline cost. In two dimensions this is planar point location.
- Space. for the inequalities and the gains; if only the first input is stored.
Properties
- Exact. In exact arithmetic the stored law equals the QP solution on all of . It is not an approximation.
- Continuous piecewise affine law and convex piecewise quadratic value function (theorem, Bemporad et al. 2002), when .
- Same closed loop as online MPC. The explicit law is the same function as the online law, so the stability and feasibility properties of linear MPC carry over unchanged.
- Fixed online time. The worst case of the online search is known in advance, which matters for certification.
- Offline only for a fixed problem. Any change of the model, the weights or the limits needs a new offline computation.
Variants and improvements
- Geometric exploration (Bemporad et al. 2002): start from a region, and explore the rest of the parameter space region by region.
- Facet stepping (Tøndel, Johansen and Bemporad 2003): cross each facet of a region and guess the neighbor's active set by adding or removing the constraint of that facet.
- Combinatorial enumeration with pruning (Gupta, Bhartiya and Nataraj 2011): if a set of rows is infeasible as an active set, all its supersets are too, which cuts the search.
- Merging regions. Regions with the same first-input law can be merged into fewer, possibly nonconvex, pieces; the example has 19 regions but 7 different laws for .
- Approximate explicit MPC. Accept a law that is suboptimal by a bounded amount in exchange for far fewer regions.
- Explicit hybrid MPC. For piecewise affine models the regions may overlap and the law can be discontinuous. See hybrid MPC.
- Explicit LP-based MPC. With a 1-norm or infinity-norm cost the problem is a parametric linear program, and the law is again piecewise affine.
When to use it
Use it for small problems: a few states, one to three inputs, a short horizon, and few constraints, on hardware that cannot run a QP solver in the sampling period, or where a verified fixed run time is required. For larger problems the number of regions makes the offline time and the memory too large; use an online QP solver as in linear MPC. Rule of thumb: the region count, not the number of states alone, decides. Compute it for the real problem before you commit.
Pitfalls
- Region explosion. The count can grow fast with , and the number of constraints. Measure it for the real problem before you choose explicit MPC.
- Lost thin regions. In floating point, a region with a Chebyshev radius below the threshold is dropped. States in it are then not covered. Check the coverage of by sampling, as the tests do.
- The box of states. The partition covers only the chosen box. A state outside it is reported as not covered, even if the QP is feasible there.
- Degenerate problems. When more than rows are active at the solution, or LICQ fails, several active sets describe the same region, and exploration methods that rely on one active set per region can miss regions. The enumeration of this page handles it, at the cost of more candidates.
- Ties on boundaries. A state on a shared boundary is in several regions. All give the same value, but the floating-point tests can disagree; use a small tolerance in the membership test.
- Equality constraints written as two inequalities. Then has no interior point and every region is dropped by the radius test. Eliminate the equalities first.
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/explicit-mpc/. The authors are listed in prov/6TK6XY.jsonl.
"""Explicit linear MPC: the solution of the MPC quadratic program as a
piecewise affine function of the state, computed offline.
The MPC problem is the multiparametric QP (mp-QP)
minimize over z 1/2 z^T H z + x^T F^T z
subject to G z <= w + E x,
with H positive definite, the decision z (the stacked inputs) and the
parameter x (the current state). For a set A of constraint rows with linearly
independent rows G_A, the KKT conditions with exactly these rows active give
lambda_A(x) = -(G_A H^-1 G_A^T)^-1 (w_A + (E_A + G_A H^-1 F) x),
z(x) = -H^-1 (F x + G_A^T lambda_A(x)),
both affine in x. The critical region of A is the polyhedron of the x where
z(x) is feasible and lambda_A(x) >= 0. The offline part enumerates the
candidate sets, keeps the regions that have an interior point inside a box
of states, and stores (region, gain, offset). The online part finds the
region that contains x by sequential search and evaluates the affine law.
The enumeration visits every set of at most dim(z) rows, so the offline cost
is exponential in the number of constraints. This is the simplest correct
method; the geometric exploration of Bemporad, Morari, Dua and Pistikopoulos
(2002) and the combinatorial method of Gupta et al. (2011) visit fewer sets.
"""
from itertools import combinations
__all__ = ["mpc_to_mpqp", "explicit_mpc", "evaluate", "chebyshev_radius", "Region"]
def _mul(a, b):
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def _matvec(a, x):
return [sum(v * w for v, w in zip(row, x)) for row in a]
def _t(a):
return [list(c) for c in zip(*a)]
def _solve(a, b, tol=1e-12):
"""Solve a x = b (b a matrix) by Gaussian elimination; None if singular."""
n = len(a)
aa = [list(map(float, r)) + list(map(float, br)) for r, br in zip(a, b)]
k = len(b[0])
scale = max((abs(v) for r in a for v in r), default=1.0) or 1.0
for c in range(n):
p = max(range(c, n), key=lambda r: abs(aa[r][c]))
if abs(aa[p][c]) <= tol * scale:
return None
aa[c], aa[p] = aa[p], aa[c]
for r in range(n):
if r != c and aa[r][c] != 0.0:
f = aa[r][c] / aa[c][c]
aa[r] = [x - f * y for x, y in zip(aa[r], aa[c])]
return [[aa[i][n + j] / aa[i][i] for j in range(k)] for i in range(n)]
def mpc_to_mpqp(A, B, Q, R, P, N, umin, umax, xmin=None, xmax=None):
"""Return (H, F, G, w, E) of the condensed MPC problem.
Cost sum_(k<N) x_k^T Q x_k + u_k^T R u_k + x_N^T P x_N, halved, so the
objective is 1/2 z^T H z + x^T F^T z plus a constant. Constraints:
umin <= u_k <= umax for k < N and, if given, xmin <= x_k <= xmax for
k = 1..N.
"""
n, m = len(A), len(B[0])
powers = [[[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]]
for _ in range(N):
powers.append(_mul(A, powers[-1]))
phi = [row for k in range(1, N + 1) for row in powers[k]]
gamma = [[0.0] * (N * m) for _ in range(N * n)]
for k in range(1, N + 1):
for j in range(k):
blk = _mul(powers[k - 1 - j], B)
for i in range(n):
for c in range(m):
gamma[(k - 1) * n + i][j * m + c] = blk[i][c]
qbar = [[0.0] * (N * n) for _ in range(N * n)]
for k in range(N):
W = P if k == N - 1 else Q
for i in range(n):
for j in range(n):
qbar[k * n + i][k * n + j] = W[i][j]
gq = _mul(_t(gamma), qbar)
H = _mul(gq, gamma)
for k in range(N):
for i in range(m):
for j in range(m):
H[k * m + i][k * m + j] += R[i][j]
F = _mul(gq, phi)
G, w, E = [], [], []
for k in range(N):
for c in range(m):
e = [0.0] * (N * m)
e[k * m + c] = 1.0
G += [e, [-v for v in e]]
w += [umax[c], -umin[c]]
E += [[0.0] * n, [0.0] * n]
if xmax is not None:
for r in range(N * n):
G += [gamma[r], [-v for v in gamma[r]]]
w += [xmax[r % n], -xmin[r % n]]
E += [[-v for v in phi[r]], list(phi[r])]
return H, F, G, w, E
def _lp_max(c, rows, b, tol=1e-9):
"""Maximize c^T y subject to rows y <= b, y free (two phase simplex).
Returns the optimal value, None if infeasible, or inf if unbounded.
"""
n, mr = len(c), len(rows)
arts = [i for i in range(mr) if b[i] < 0]
ncols = 2 * n + mr + len(arts)
T, basis = [], []
for i, (row, bi) in enumerate(zip(rows, b)):
line = list(row) + [-v for v in row] + [1.0 if j == i else 0.0 for j in range(mr)]
line += [0.0] * len(arts) + [float(bi)]
if bi < 0:
line = [-v for v in line]
a = 2 * n + mr + arts.index(i)
line[a] = 1.0
basis.append(a)
else:
basis.append(2 * n + i)
T.append(line)
def run(cost, ncol):
while True:
enter = None
for j in range(ncol):
if j not in basis:
rc = cost[j] - sum(cost[basis[i]] * T[i][j] for i in range(mr))
if rc > tol:
enter = j
break
if enter is None:
return True
leave, best = None, None
for i in range(mr):
if T[i][enter] > tol:
ratio = T[i][-1] / T[i][enter]
if best is None or ratio < best - tol or (abs(ratio - best) <= tol and basis[i] < basis[leave]):
best, leave = ratio, i
if leave is None:
return False
piv = T[leave][enter]
T[leave] = [v / piv for v in T[leave]]
for i in range(mr):
if i != leave and T[i][enter] != 0.0:
f = T[i][enter]
T[i] = [x - f * y for x, y in zip(T[i], T[leave])]
basis[leave] = enter
if arts:
art_cols = set(range(2 * n + mr, ncols))
run([0.0] * (2 * n + mr) + [-1.0] * len(arts), ncols)
if sum(T[i][-1] for i in range(mr) if basis[i] in art_cols) > tol:
return None
for i in range(mr):
if basis[i] in art_cols:
for j in range(2 * n + mr):
if abs(T[i][j]) > tol and j not in basis:
piv = T[i][j]
T[i] = [v / piv for v in T[i]]
for r in range(mr):
if r != i and T[r][j] != 0.0:
f = T[r][j]
T[r] = [x - f * y for x, y in zip(T[r], T[i])]
basis[i] = j
break
for row in T:
for j in art_cols:
row[j] = 0.0
cost = list(c) + [-v for v in c] + [0.0] * (mr + len(arts))
if not run(cost, 2 * n + mr):
return float("inf")
y = [0.0] * ncols
for i, j in enumerate(basis):
y[j] = T[i][-1]
return sum(ci * (y[j] - y[n + j]) for j, ci in enumerate(c))
def chebyshev_radius(rows, b):
"""Radius of the largest ball inside {x : rows x <= b}; None if empty."""
n = len(rows[0])
ext = [list(r) + [sum(v * v for v in r) ** 0.5] for r in rows]
ext.append([0.0] * n + [-1.0]) # r >= 0
v = _lp_max([0.0] * n + [1.0], ext, list(b) + [0.0])
return v
class Region:
"""A critical region {x : Ax x <= bx} with the law z = K x + k."""
def __init__(self, active, Ax, bx, K, k, L, l):
self.active, self.Ax, self.bx = active, Ax, bx
self.K, self.k, self.L, self.l = K, k, L, l
def contains(self, x, tol=1e-9):
return all(sum(a * v for a, v in zip(r, x)) <= bi + tol for r, bi in zip(self.Ax, self.bx))
def law(self, x):
return [v + c for v, c in zip(_matvec(self.K, x), self.k)]
def multipliers(self, x):
return [v + c for v, c in zip(_matvec(self.L, x), self.l)]
def explicit_mpc(H, F, G, w, E, xbox, eps=1e-7):
"""Return the list of full-dimensional critical regions inside |x_i| <= xbox_i."""
nz, nx, q = len(H), len(F[0]), len(G)
Hinv = _solve(H, [[1.0 if i == j else 0.0 for j in range(nz)] for i in range(nz)])
HiF = _mul(Hinv, F)
box_rows = []
box_b = []
for i in range(nx):
e = [0.0] * nx
e[i] = 1.0
box_rows += [e, [-1.0 * v for v in e]]
box_b += [xbox[i], xbox[i]]
regions = [] # @line L1
for size in range(0, nz + 1):
for act in combinations(range(q), size): # @line L2
GA = [G[i] for i in act]
if act:
M = _mul(_mul(GA, Hinv), _t(GA)) # @line L3
Minv = _solve(M, [[1.0 if i == j else 0.0 for j in range(size)] for i in range(size)])
if Minv is None: # rows of G_A are dependent (LICQ fails)
continue
S = [[e + s for e, s in zip(E[i], srow)] for i, srow in zip(act, _mul(GA, HiF))]
L = [[-v for v in r] for r in _mul(Minv, S)] # @line L4
l = [-v for v in _matvec(Minv, [w[i] for i in act])]
GtL = _mul(_t(GA), L)
Gtl = _matvec(_t(GA), l)
else:
L, l = [], []
GtL, Gtl = [[0.0] * nx for _ in range(nz)], [0.0] * nz
K = [[-v for v in r] for r in _mul(Hinv, [[a + b for a, b in zip(r1, r2)] for r1, r2 in zip(F, GtL)])] # @line L5
k = [-v for v in _matvec(Hinv, Gtl)]
rows, b = list(box_rows), list(box_b) # @line L6
GK = _mul(G, K)
Gk = _matvec(G, k)
for i in range(q): # G (K x + k) <= w + E x
rows.append([gk - e for gk, e in zip(GK[i], E[i])])
b.append(w[i] - Gk[i])
for j in range(size): # lambda(x) = L x + l >= 0
rows.append([-v for v in L[j]])
b.append(l[j])
r = chebyshev_radius(rows, b) # @line L7
if r is not None and r > eps:
keep = [i for i in range(len(rows)) if any(abs(v) > 1e-12 for v in rows[i])]
regions.append(Region(act, [rows[i] for i in keep], [b[i] for i in keep], K, k, L, l))
return regions # @line L8
def evaluate(regions, x, m=None, tol=1e-9):
"""Return (z(x), region index) by sequential search; (None, None) if x is in no region."""
for idx, reg in enumerate(regions): # @line L9
if reg.contains(x, tol): # @line L10
z = reg.law(x)
return (z if m is None else z[:m]), idx
return None, None # @line L11
test_explicit_mpc.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/explicit-mpc/. The authors are listed in prov/6TK6XY.jsonl.
import itertools
import random
from explicit_mpc import chebyshev_radius, evaluate, explicit_mpc, mpc_to_mpqp
# Double integrator with h = 1, Q = I, R = 1, P from the DARE (P_12 = sqrt(5)/2).
A = [[1.0, 1.0], [0.0, 1.0]]
B = [[0.5], [1.0]]
Q = [[1.0, 0.0], [0.0, 1.0]]
R = [[1.0]]
def dare(iters=400):
p = [[1.0, 0.0], [0.0, 1.0]]
for _ in range(iters):
pb = [p[0][0] * 0.5 + p[0][1], p[1][0] * 0.5 + p[1][1]] # P B
s = 1.0 + 0.5 * pb[0] + pb[1] # R + B^T P B
bpa = [pb[0], pb[0] + pb[1]] # B^T P A
apa = [[p[0][0], p[0][0] + p[0][1]], [p[0][0] + p[1][0], p[0][0] + p[0][1] + p[1][0] + p[1][1]]]
p = [[Q[i][j] + apa[i][j] - bpa[i] * bpa[j] / s for j in range(2)] for i in range(2)]
return p, [bpa[0] / s, bpa[1] / s]
P, K = dare()
XBOX = [10.0, 10.0]
H, F, G, W, E = mpc_to_mpqp(A, B, Q, R, P, 3, [-1.0], [1.0])
REGIONS = explicit_mpc(H, F, G, W, E, XBOX)
def lin_solve(a, b):
n = len(a)
m = [list(r) + [v] for r, v in zip(a, b)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[p][c]) < 1e-12:
return None
m[c], m[p] = m[p], m[c]
for r in range(n):
if r != c:
f = m[r][c] / m[c][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
return [m[i][n] / m[i][i] for i in range(n)]
def brute_qp(x):
"""Solve the QP at x by trying every active set (H > 0, so the KKT point is unique)."""
nz = len(H)
f = [sum(F[i][j] * x[j] for j in range(len(x))) for i in range(nz)]
b = [W[i] + sum(E[i][j] * x[j] for j in range(len(x))) for i in range(len(G))]
for size in range(nz + 1):
for S in itertools.combinations(range(len(G)), size):
kkt = [H[i] + [G[j][i] for j in S] for i in range(nz)] + [G[j] + [0.0] * size for j in S]
sol = lin_solve(kkt, [-v for v in f] + [b[j] for j in S])
if sol is None:
continue
z, lam = sol[:nz], sol[nz:]
if all(v >= -1e-9 for v in lam) and all(
sum(g * zi for g, zi in zip(G[i], z)) <= b[i] + 1e-9 for i in range(len(G))):
return z
raise AssertionError("no KKT point")
def horizon_cost(x, U):
J, xk = 0.0, list(x)
for u in U:
J += xk[0] ** 2 + xk[1] ** 2 + u ** 2
xk = [xk[0] + xk[1] + 0.5 * u, xk[1] + u]
return J + sum(xk[i] * P[i][j] * xk[j] for i in range(2) for j in range(2))
def test_region_count_and_unconstrained_region():
assert len(REGIONS) == 19 # of the 27 candidate sets with independent rows
free = [r for r in REGIONS if r.active == ()]
assert len(free) == 1 and free[0].contains([0.0, 0.0])
assert abs(free[0].K[0][0] + K[0]) < 1e-9 and abs(free[0].K[0][1] + K[1]) < 1e-9
def test_law_matches_brute_force_qp():
rng = random.Random(21)
for _ in range(300):
x = [rng.uniform(-10, 10), rng.uniform(-10, 10)]
z, idx = evaluate(REGIONS, x)
assert idx is not None
zb = brute_qp(x)
assert max(abs(a - b) for a, b in zip(z, zb)) < 1e-7
def test_example_points():
z, idx = evaluate(REGIONS, [-5.0, 3.0])
assert REGIONS[idx].active == (3,) # u_1 >= -1 is active
assert max(abs(a - b) for a, b in zip(z, [-0.9516, -1.0, -0.6753])) < 5e-5
z, idx = evaluate(REGIONS, [3.0, 2.0])
assert z == [-1.0, -1.0, -1.0] or max(abs(v + 1.0) for v in z) < 1e-12
def test_multipliers_and_kkt_inside_regions():
rng = random.Random(22)
for reg in REGIONS:
for _ in range(20):
x = [rng.uniform(-10, 10), rng.uniform(-10, 10)]
if not reg.contains(x, 0.0):
continue
z, lam = reg.law(x), reg.multipliers(x)
assert all(v >= -1e-9 for v in lam)
grad = [sum(H[i][j] * z[j] for j in range(3)) + sum(F[i][j] * x[j] for j in range(2))
+ sum(lam[a] * G[reg.active[a]][i] for a in range(len(lam))) for i in range(3)]
assert max(abs(v) for v in grad) < 1e-9
def test_interiors_do_not_overlap():
rng = random.Random(23)
for _ in range(500):
x = [rng.uniform(-10, 10), rng.uniform(-10, 10)]
strict = [i for i, r in enumerate(REGIONS) if r.contains(x, -1e-9)]
assert len(strict) <= 1
def test_law_is_continuous():
rng = random.Random(24)
for _ in range(300):
x = [rng.uniform(-9.9, 9.9), rng.uniform(-9.9, 9.9)]
y = [x[0] + rng.uniform(-1e-6, 1e-6), x[1] + rng.uniform(-1e-6, 1e-6)]
zx, _ = evaluate(REGIONS, x)
zy, _ = evaluate(REGIONS, y)
assert max(abs(a - b) for a, b in zip(zx, zy)) < 1e-4
def test_value_function_is_convex():
rng = random.Random(25)
for _ in range(200):
x = [rng.uniform(-10, 10), rng.uniform(-10, 10)]
y = [rng.uniform(-10, 10), rng.uniform(-10, 10)]
mid = [(a + b) / 2 for a, b in zip(x, y)]
v = [horizon_cost(p, evaluate(REGIONS, p)[0]) for p in (x, y, mid)]
assert v[2] <= (v[0] + v[1]) / 2 + 1e-8
def test_outside_the_box_is_not_covered():
z, idx = evaluate(REGIONS, [10.5, 0.0])
assert z is None and idx is None
def test_chebyshev_radius():
box = [[1.0, 0.0], [-1.0, 0.0], [0.0, 1.0], [0.0, -1.0]]
assert abs(chebyshev_radius(box, [1.0, 1.0, 1.0, 1.0]) - 1.0) < 1e-12
assert abs(chebyshev_radius(box + [[1.0, 1.0]], [1.0, 1.0, 1.0, 1.0, 0.0]) - (2 - 2 ** 0.5)) < 1e-9
assert chebyshev_radius(box, [1.0, -2.0, 1.0, 1.0]) is None
def test_state_constraints_shrink_the_covered_set():
Hs, Fs, Gs, Ws, Es = mpc_to_mpqp(A, B, Q, R, P, 2, [-1.0], [1.0], [-5.0, -5.0], [5.0, 5.0])
regs = explicit_mpc(Hs, Fs, Gs, Ws, Es, [5.0, 5.0])
assert evaluate(regs, [4.0, 2.0])[1] is None # infeasible: x_1 >= 5.5 for every u
z, idx = evaluate(regs, [0.1, -0.1])
assert idx is not None and abs(z[0] + K[0] * 0.1 - K[1] * 0.1) < 1e-9
History
Bemporad, Morari, Dua and Pistikopoulos (2002) showed that the constrained linear quadratic regulator over a finite horizon is a continuous piecewise affine function of the state and gave an algorithm that computes it. Tøndel, Johansen and Bemporad (2003) gave a faster exploration across facets, and in a second paper a binary search tree for fast online evaluation. Gupta, Bhartiya and Nataraj (2011) replaced the exploration of the state space by an enumeration of active sets with pruning. The book of Borrelli, Bemporad and Morari presents the theory for linear and hybrid systems.
References
- Alberto Bemporad, Manfred Morari, Vivek Dua and Efstratios N. Pistikopoulos, The explicit linear quadratic regulator for constrained systems, Automatica 38(1), 3-20, 2002, the critical regions, the continuous piecewise affine law, the convex piecewise quadratic value function, and the geometric algorithm that explores the parameter space
- Petter Tøndel, Tor Arne Johansen and Alberto Bemporad, An algorithm for multi-parametric quadratic programming and explicit MPC solutions, Automatica 39(3), 489-497, 2003, the exploration of neighboring regions across facets by changing one active constraint at a time
- Petter Tøndel, Tor Arne Johansen and Alberto Bemporad, Evaluation of piecewise affine control via binary search tree, Automatica 39(5), 945-950, 2003, the binary search tree over the regions, with an online time logarithmic in the number of regions for a balanced tree
- Arun Gupta, Sharad Bhartiya and P. S. V. Nataraj, A novel approach to multiparametric quadratic programming, Automatica 47(9), 2112-2117, 2011, the enumeration of candidate active sets with pruning, instead of the exploration of the parameter space
- Francesco Borrelli, Alberto Bemporad and Manfred Morari, Predictive Control for Linear and Hybrid Systems, Cambridge University Press, 2017, the chapters on multiparametric programming and on the explicit solution of constrained linear quadratic control
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 6TK6XY Edit this page History Report an error Markdown