Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 xx only through its linear term and its right-hand side, so it is a multiparametric quadratic program (mp-QP) with the parameter xx. Bemporad, Morari, Dua and Pistikopoulos (2002) showed that its solution is a continuous piecewise affine function of xx: the feasible states split into finitely many polyhedral critical regions, one per optimal active set, and on each region the optimal plan is z∗(x)=Kix+kiz^*(x) = K_i x + k_i. 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,

min⁡z 12zTHz+xTFTzsubject toGz≤w+Ex,\min_z \ \tfrac12 z^T H z + x^T F^T z \quad \text{subject to} \quad G z \le w + E x,

with H>0H > 0 of size s=Nms = N m (the stacked inputs), cc constraint rows, and a box X={x:∣xi∣≤xˉi}\mathbb{X} = \{x : |x_i| \le \bar x_i\} of states of interest. Output: a list of regions CR1,…,CRMCR_1, \dots, CR_M, each a polyhedron with an affine law z=Kix+kiz = K_i x + k_i, such that the regions cover S={x∈X:the QP is feasible}S = \{x \in \mathbb{X} : \text{the QP is feasible}\} and z∗(x)=Kix+kiz^*(x) = K_i x + k_i for x∈CRix \in CR_i. The online problem is: given xx, return z∗(x)z^*(x), or report that x∉Sx \notin S.

The law of one active set. For a set AA of rows with linearly independent GAG_A (the linear independence constraint qualification, LICQ), the KKT conditions with exactly the rows AA active are linear in (z,λA)(z, \lambda_A) and give

λA(x)=−MA−1(wA+(EA+GAH−1F)x),zA(x)=−H−1(Fx+GATλA(x)),MA=GAH−1GAT.\lambda_A(x) = -M_A^{-1}\left(w_A + (E_A + G_A H^{-1} F) x\right), \qquad z_A(x) = -H^{-1}\left(F x + G_A^T \lambda_A(x)\right), \qquad M_A = G_A H^{-1} G_A^T.

The critical region of AA is the set of xx where zA(x)z_A(x) is feasible and λA(x)≥0\lambda_A(x) \ge 0. Both conditions are affine inequalities in xx, so it is a polyhedron.

The algorithm

  1. EXPLICIT-MPC(H, F, G, w, E, box) ▷ offline
  2. 1regions ← ∅
  3. 2for each set A of at most s rows of G ▷ candidate active sets
  4. 3M ← G_A H⁻¹ G_Aᵀ; skip A if M is singular ▷ LICQ
  5. 4λ_A(x) = L x + l: L ← -M⁻¹ (E_A + G_A H⁻¹ F), l ← -M⁻¹ w_A
  6. 5z_A(x) = K x + k: K ← -H⁻¹ (F + G_Aᵀ L), k ← -H⁻¹ G_Aᵀ l
  7. 6CR ← {x in box : G (K x + k) ≤ w + E x, L x + l ≥ 0}
  8. 7if the Chebyshev radius of CR is > ε then add (A, CR, K, k) to regions
  9. 8return regions
  10. EVALUATE(regions, x) ▷ online, at each sampling instant
  11. 9for each (A, CR, K, k) in regions
  12. 10if x ∈ CR then return K x + k
  13. 11return "x is not in the covered set"

Line L2 enumerates every set of at most ss rows. Larger sets cannot have linearly independent rows in Rs\mathbb{R}^s, and line L3 drops the dependent ones. Lines L4 and L5 are the formulas above. Line L6 writes the region as inequalities in xx: primal feasibility of zA(x)z_A(x) for all cc rows, and dual feasibility of the multipliers. Line L7 solves one linear program for the Chebyshev radius, the radius of the largest ball inside CRCR; 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 mm entries of zz are needed online, so a controller stores only the first mm rows of KK and kk.

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, A=[1101]A = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}, B=[0.51]B = \begin{bmatrix} 0.5 \\ 1 \end{bmatrix}, Q=IQ = I, R=1R = 1, the DARE solution as terminal weight PP, the horizon N=3N = 3 and only the input limits ∣uk∣≤1|u_k| \le 1. The mp-QP has s=3s = 3 variables and c=6c = 6 rows, in the order u0≤1u_0 \le 1, u0≥−1u_0 \ge -1, u1≤1u_1 \le 1, u1≥−1u_1 \ge -1, u2≤1u_2 \le 1, u2≥−1u_2 \ge -1. The box is ∣xi∣≤10|x_i| \le 10.

  • Candidates. There are (60)+(61)+(62)+(63)=42\binom60 + \binom61 + \binom62 + \binom63 = 42 sets of at most 3 rows. A set that contains both limits of the same input has a singular MM and is skipped, which leaves 33=273^3 = 27 sets.
  • Regions. 19 of the 27 regions have an interior point inside the box (measurement with the implementation).
  • The unconstrained region (A=∅A = \emptyset) contains the origin and has the law u0=−0.4345x1−1.0285x2u_0 = -0.4345 x_1 - 1.0285 x_2, the LQR law u=−Kxu = -K x.
  • One input limit active. For A={u1≥−1}A = \{u_1 \ge -1\} the law is u0=−0.3824x1−1.1172x2+0.4882u_0 = -0.3824 x_1 - 1.1172 x_2 + 0.4882. For A={u1≥−1,u2≥−1}A = \{u_1 \ge -1, u_2 \ge -1\} it is u0=−0.3174x1−1.1236x2+0.9338u_0 = -0.3174 x_1 - 1.1236 x_2 + 0.9338. The regions with u1≤1u_1 \le 1 active have the same gains with the opposite offsets.
  • Saturated regions. In 14 regions u0=1u_0 = 1 or u0=−1u_0 = -1. So the first input has only 7 different affine pieces on the 19 regions.

Online evaluation. For x=(−5,3)x = (-5, 3) the search finds the region of {u1≥−1}\{u_1 \ge -1\}, and the law gives z=(−0.9516,−1,−0.6753)z = (-0.9516, -1, -0.6753). As in the linear MPC example with N=5N = 5 from the same state, only the row u1≥−1u_1 \ge -1 is active. For x=(3,2)x = (3, 2) the region is {u0,u1,u2≥−1}\{u_0, u_1, u_2 \ge -1\} and z=(−1,−1,−1)z = (-1, -1, -1). The tests compare the law with a brute-force QP solution at 300 random states and find agreement to 10−710^{-7}.

Region counts. For the same plant with ∣u∣≤1|u| \le 1 inside ∣xi∣≤10|x_i| \le 10 (measurement with the implementation):

NN rows cc regions MM
2 4 9
3 6 19
4 8 33
5 10 43

With the state limits ∣xk,i∣≤5|x_{k,i}| \le 5 added and N=2N = 2, the covered set shrinks: the state (4,2)(4, 2), for which no input meets the limits, lies in no region.

Correctness

The proofs are in proofs/correctness.md.

  1. One active set gives an affine law. If GAG_A has independent rows, MAM_A is positive definite, so the linear KKT system with the rows AA active has the unique solution of the formulas above, affine in xx.
  2. Inside its region the law is optimal. For x∈CRAx \in CR_A, zA(x)z_A(x) is feasible, λA(x)≥0\lambda_A(x) \ge 0, complementarity holds because the rows in AA are active, and stationarity holds by construction. For a convex QP the KKT conditions are sufficient, and H>0H > 0 makes the minimizer unique.
  3. Every feasible state is in some region. At the optimum z∗(x)z^*(x), the vector −(Hz∗+Fx)-(H z^* + F x) 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 AA of line L2 with x∈CRAx \in CR_A.
  4. The kept regions cover SS. Regions without interior points lie in proper affine subspaces, which have measure zero. If SS 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 SS.
  5. The online search is correct. By point 4, a state in SS lies in a kept region, and by point 2 its law gives z∗(x)z^*(x). Every region lies in SS, so a state outside SS is in none.

The law is continuous on SS, 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 (z,x)(z, x), 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 x∈Rnx \in \mathbb{R}^{n} is the multiparametric quadratic program

min⁡z 12zTHz+xTFTzsubject toGz≤w+Ex,\min_z \ \tfrac12 z^T H z + x^T F^T z \quad \text{subject to} \quad G z \le w + E x,

with H=HT>0H = H^T > 0, z∈Rsz \in \mathbb{R}^{s} and qq rows giTg_i^T in GG. For a fixed xx the problem is strictly convex, so if it is feasible it has exactly one minimizer z∗(x)z^*(x), and zz is that minimizer if and only if there is λ∈Rq\lambda \in \mathbb{R}^q with

Hz+Fx+GTλ=0,Gz≤w+Ex,λ≥0,λi(wi+Eix−giTz)=0.(KKT)H z + F x + G^T \lambda = 0, \quad G z \le w + E x, \quad \lambda \ge 0, \quad \lambda_i (w_i + E_i x - g_i^T z) = 0. \tag{KKT}

Let XX be the box of states given to the algorithm and S={x∈X:the QP is feasible at x}S = \{x \in X : \text{the QP is feasible at } x\}. The set SS is the projection of the polyhedron {(z,x):Gz≤w+Ex,x∈X}\{(z, x) : G z \le w + E x, x \in X\}, so it is a convex polyhedron.

Lemma 1: the affine law of one active set

Let A⊆{1,…,q}A \subseteq \{1, \dots, q\} be a set whose rows GAG_A are linearly independent. Then the system

Hz+Fx+GATλA=0,GAz=wA+EAxH z + F x + G_A^T \lambda_A = 0, \qquad G_A z = w_A + E_A x

has, for every xx, exactly one solution, given by

λA(x)=−M−1(wA+(EA+GAH−1F)x),zA(x)=−H−1(Fx+GATλA(x)),M=GAH−1GAT.\lambda_A(x) = -M^{-1} \big(w_A + (E_A + G_A H^{-1} F) x\big), \qquad z_A(x) = -H^{-1} \big(F x + G_A^T \lambda_A(x)\big), \qquad M = G_A H^{-1} G_A^T.

Proof. MM is positive definite: for v≠0v \ne 0, GATv≠0G_A^T v \ne 0 by independence, so vTMv=(GATv)TH−1(GATv)>0v^T M v = (G_A^T v)^T H^{-1} (G_A^T v) > 0. The first equation gives z=−H−1(Fx+GATλA)z = -H^{-1}(F x + G_A^T \lambda_A). Substituting it into the second gives −GAH−1Fx−MλA=wA+EAx-G_A H^{-1} F x - M \lambda_A = w_A + E_A x, which has the single solution stated. □\square

These are lines L3 to L5. Both maps are affine in xx, so line L6 defines a polyhedron

CRA={x∈X:GzA(x)≤w+Ex, λA(x)≥0}.CR_A = \{x \in X : G z_A(x) \le w + E x, \ \lambda_A(x) \ge 0\}.

Lemma 2: inside a region the law is optimal

If x∈CRAx \in CR_A, then zA(x)=z∗(x)z_A(x) = z^*(x), and λ\lambda equal to λA(x)\lambda_A(x) on AA and 0 elsewhere is a KKT multiplier.

Proof. Stationarity holds by Lemma 1. Feasibility and λA≥0\lambda_A \ge 0 are the inequalities of CRACR_A. Complementarity holds because λi=0\lambda_i = 0 off AA and the rows in AA hold with equality. So (KKT) holds, and zA(x)z_A(x) is the unique minimizer. □\square

Lemma 3: every feasible state is in some region

If x∈Sx \in S, there is a set AA with independent rows and x∈CRAx \in CR_A.

Proof. Let z∗=z∗(x)z^* = z^*(x) and let II be the set of active rows at z∗z^*. By (KKT), −(Hz∗+Fx)-(H z^* + F x) lies in the cone generated by {gi:i∈I}\{g_i : i \in I\}. By Carathéodory's theorem for cones, it is a nonnegative combination ∑i∈Aμigi\sum_{i \in A} \mu_i g_i of a subset A⊆IA \subseteq I whose vectors are linearly independent. Then z∗z^* and μ\mu solve the system of Lemma 1 for this AA, because the rows in AA are active, and by uniqueness zA(x)=z∗z_A(x) = z^* and λA(x)=μ≥0\lambda_A(x) = \mu \ge 0. Since z∗z^* is feasible, x∈CRAx \in CR_A. □\square

Lemma 3 is why the enumeration of line L2 only needs sets of at most ss rows: an independent set in Rs\mathbb{R}^s has at most ss elements.

Theorem 1: the kept regions cover the feasible box

Assume SS has an interior point. Let DD be the union of the regions CRACR_A that have an interior point (the ones kept by line L7 in exact arithmetic, where the test is radius >0> 0). Then D=SD = S.

Proof. Each CRA⊆SCR_A \subseteq S by Lemma 2, so D⊆SD \subseteq S. By Lemma 3, SS is the union of all the regions, of which there are finitely many. Suppose x∈S∖Dx \in S \setminus D. DD is a finite union of closed sets, so it is closed, and some open ball UU around xx misses DD. Because SS is convex with an interior point and x∈Sx \in S, the set U∩int⁡SU \cap \operatorname{int} S is open and not empty (the segment from xx to an interior point of SS enters int⁡S\operatorname{int} S 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. □\square

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 ε\varepsilon, so a region thinner than ε\varepsilon can be lost, and the search then finds no region for the states inside it. With ε=0\varepsilon = 0 in exact arithmetic nothing is lost.

Theorem 2: the online evaluation is correct

For x∈Sx \in S, lines L9 to L11 return z∗(x)z^*(x). For x∈X∖Sx \in X \setminus S they report that no region contains xx.

Proof. If x∈Sx \in S, Theorem 1 gives a kept region that contains xx, so the search finds a first region CRA∋xCR_A \ni x and returns zA(x)z_A(x), which is z∗(x)z^*(x) by Lemma 2. Different regions may share boundary points, but every region that contains xx gives the same value, since the minimizer is unique. If x∉Sx \notin S, no region contains xx, because every region lies in SS. □\square

Consequences: continuity and convexity

The law is continuous on SS. On each kept region z∗z^* is affine, so continuous. The regions are finitely many closed sets that cover SS, and on any intersection the affine laws agree (both equal z∗z^*). By the pasting lemma for finitely many closed sets, z∗z^* is continuous on SS.

The value function is convex and piecewise quadratic. For the MPC cost, the horizon cost is J(x,z)=zTHz+2xTFTz+xTYxJ(x, z) = z^T H z + 2 x^T F^T z + x^T Y x with the block matrix [HFFTY]≥0\begin{bmatrix} H & F \\ F^T & Y \end{bmatrix} \ge 0, because JJ is a sum of nonnegative quadratic terms in (z,x)(z, x). The set {(z,x):Gz≤w+Ex}\{(z, x) : G z \le w + E x\} is convex. The minimum of a jointly convex function over the zz section of a convex set is a convex function of xx, so V(x)=min⁡zJ(x,z)V(x) = \min_z J(x, z) is convex on SS. On each region V(x)=J(x,zA(x))V(x) = J(x, z_A(x)) is quadratic in xx.

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 ss rows are active at the solution. The price is the enumeration of ∑k≤s(qk)\sum_{k \le s} \binom{q}{k} sets, each with an s×ss \times s solve and a linear program. When SS 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 s=Nms = N m variables and cc rows.

  • Offline. Line L2 visits ∑k≤s(ck)≤2c\sum_{k \le s} \binom{c}{k} \le 2^c sets. Each costs O(s3)O(s^3) for the solves of lines L3 to L5, O(csn)O(c s n) to write the region, and one LP for the Chebyshev radius. The total is O(2c(N3m3+cNmn+L))O(2^c (N^3 m^3 + c N m n + L)). 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 M≤∑k≤s(ck)M \le \sum_{k \le s} \binom{c}{k}. The bound is exponential in the number of constraints, and the count can grow quickly with NN. The counts in the table are measurements.
  • Online. The sequential search tests at most MM regions with O(c+n)O(c + n) inequalities each, so O(M(c+n)n)O(M (c + n) n) 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 MM for a balanced tree; building the tree is an offline cost. In two dimensions this is planar point location.
  • Space. O(M(c+n)(n+Nm))O(M (c + n) (n + N m)) for the inequalities and the gains; O(M(c+n)n+Mmn)O(M (c + n) n + M m n) if only the first input is stored.

Properties

  • Exact. In exact arithmetic the stored law equals the QP solution on all of SS. It is not an approximation.
  • Continuous piecewise affine law and convex piecewise quadratic value function (theorem, Bemporad et al. 2002), when H>0H > 0.
  • 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 u0u_0.
  • 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 NN, mm 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 ε\varepsilon is dropped. States in it are then not covered. Check the coverage of SS 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 ss 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 SS 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.

explicit_mpc.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.online
  • 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