Algorithm Search⌘K

Algorithmresearch

Hybrid MPC

Also called hybrid model predictive control, mixed-integer MPC.

MPC for piecewise affine or mixed logical dynamical models, where each step is a mixed-integer quadratic or linear program.

Time
O(s^N (N^3 n m^2 + c)) worst
Space
O(N^2 m (n + m)) extra
Where
N = the horizon; c = the cost of one convex QP in N m variables; m = the input dimension; n = the state dimension; s = the number of modes
Properties
deterministicexactonline
Origin
Alberto Bemporad, Manfred Morari, 1999

Hybrid MPC is model predictive control for a plant whose model has both real states and discrete modes: a piecewise affine system or a mixed logical dynamical system. At each sampling instant it measures the state, finds the input sequence and the mode sequence over a horizon of NN steps that minimize a cost under constraints, and applies the first input. With a quadratic cost the problem at each instant is a mixed-integer quadratic program (MIQP), and with a 1-norm or infinity-norm cost it is a mixed-integer linear program. Bemporad and Morari (1999) gave this formulation. For a fixed mode sequence the problem is a convex QP, as in linear MPC. The mode choice makes it nonconvex, and the worst case grows exponentially with NN. The code on this page solves the problem exactly by enumeration of the sNs^N mode sequences, which is the simplest correct method for small ss and NN.

In plain words

Some machines change their behavior when the state crosses a line: a valve opens, a contact closes, a gear shifts. Plan the next few moves of such a machine as a normal predictive controller does, but also plan which behavior it will have at each move. For one fixed list of behaviors, the best moves are easy to find, because the problem is smooth and bowl-shaped. So try every list of behaviors. Drop the lists that the machine cannot follow from where it is. Solve the easy problem for each list that is left, and keep the cheapest. Apply only the first move, measure again, and repeat. The number of lists grows very fast with the length of the plan, so real solvers prune the lists with branch and bound.

The problem

The plant is a PWA system with modes i=1,…,si = 1, \ldots, s: x+=Aix+Biu+fix^+ = A_i x + B_i u + f_i when xx is in the closed polyhedral cell Ci={x:Hix≤hi}\mathcal{C}_i = \{x : H_i x \le h_i\}. The cells cover the state set and meet only on their boundaries. At each sampling instant, with the measured state x0x_0, solve

min⁡U,σ  ∑k=0N−1(xkTQxk+ukTRuk)+xNTPxN\min_{U, \sigma} \; \sum_{k=0}^{N-1} \left(x_k^T Q x_k + u_k^T R u_k\right) + x_N^T P x_N

over the inputs U=(u0,…,uN−1)U = (u_0, \ldots, u_{N-1}) and the mode sequence σ=(σ0,…,σN−1)\sigma = (\sigma_0, \ldots, \sigma_{N-1}), subject to xk+1=Aσkxk+Bσkuk+fσkx_{k+1} = A_{\sigma_k} x_k + B_{\sigma_k} u_k + f_{\sigma_k}, xk∈Cσkx_k \in \mathcal{C}_{\sigma_k}, umin⁡≤uk≤umax⁡u_{\min} \le u_k \le u_{\max} and xmin⁡≤xk+1≤xmax⁡x_{\min} \le x_{k+1} \le x_{\max} for k=0,…,N−1k = 0, \ldots, N - 1, with Q,P⪰0Q, P \succeq 0 and R≻0R \succ 0. Apply u0u_0. The MLD form writes the same problem with binary variables δ\delta for the modes and big-M inequalities; Heemels, De Schutter and Bemporad (2001) showed that the two model classes are equivalent under mild conditions, see mixed logical dynamical system.

The algorithm

  1. HYBRID-MPC-STEP(modes, x0, N, Q, R, P, bounds)
  2. 1best ← None
  3. 2for each mode sequence sigma in {1, ..., s}^N do
  4. 3if x0 is not in cell(sigma_0) then continue
  5. 4write x_k = d_k + Gamma_k U for k = 0, ..., N under sigma
  6. 5solve the QP in U: cost (1/2) U^T H U + phi^T U, input bounds, state bounds, x_k in cell(sigma_k) for k = 1, ..., N - 1
  7. 6if the QP is feasible and its cost < cost(best) then best ← (U, sigma, cost)
  8. 7return best
  9. CLOSED-LOOP(modes, x, steps)
  10. repeat steps times
  11. (U, sigma, J) ← HYBRID-MPC-STEP(modes, x, ...)
  12. 8u ← the first m entries of U
  13. 9x ← the true PWA step from x with input u

Line L4 is the condensing of linear MPC with a different (A,B,f)(A, B, f) at each step: dk+1=Aσkdk+fσkd_{k+1} = A_{\sigma_k} d_k + f_{\sigma_k} and Γk+1=AσkΓk+BσkEk\Gamma_{k+1} = A_{\sigma_k} \Gamma_k + B_{\sigma_k} E_k, where EkE_k picks uku_k out of UU. Substituting gives H=2(∑kΓkTWkΓk+IN⊗R)\mathcal{H} = 2(\sum_k \Gamma_k^T W_k \Gamma_k + I_N \otimes R), which is positive definite. Line L5 uses the dual active set method of Goldfarb and Idnani: it starts at the unconstrained minimum, adds the most violated constraint, and drops an active constraint when its multiplier would become negative. It also reports an empty feasible set. A production solver replaces lines L2 to L6 by branch and bound on the binary variables of the MLD form (see mixed-integer programming). Each node of the tree solves a QP in which some δ\delta are fixed and the others are relaxed to [0,1][0, 1], and its value bounds every leaf below it. The code also contains this big-M MLD form of a PWA system, and the tests check that it accepts exactly the mode of each state.

Example

Take two modes that rotate the state by ±π/3\pm \pi/3 and stretch it by ρ=1.2\rho = 1.2: x+=ρR(π/3)x+bux^+ = \rho R(\pi/3) x + b u if x1≥0x_1 \ge 0 (mode 1) and x+=ρR(−π/3)x+bux^+ = \rho R(-\pi/3) x + b u if x1≤0x_1 \le 0 (mode 2), with R(θ)R(\theta) the rotation matrix and with b=(0,1)Tb = (0, 1)^T. The open loop is unstable: from (1,1)(1, 1) with u=0u = 0, ∥x∥2>10\|x\|_2 > 10 after 15 steps. Use N=3N = 3, Q=P=IQ = P = I, R=0.1R = 0.1, ∣u∣≤1|u| \le 1 and ∣xi∣≤10|x_i| \le 10, and start at x0=(1,0)x_0 = (1, 0).

Line L2 visits 23=82^3 = 8 sequences. The 4 sequences that start in mode 2 fail at line L3, because x1=1>0x_1 = 1 > 0. For mode 1 first, x1=(0.6,1.0392+u0)x_1 = (0.6, 1.0392 + u_0) has the first entry 0.6>00.6 > 0 for every input, so it is not in the cell of mode 2, and the sequences (1,2,1)(1, 2, 1) and (1,2,2)(1, 2, 2) give infeasible QPs at line L5. Two QPs are left, each with 3 variables, 6 input bounds, 12 state bounds and 2 cell rows.

sequence UU cost note
(1, 1, 1) (-0.8270, -0.6812, -0.1698) 1.5474 states (1, 0), (0.6, 0.2122), (0.1395, 0.0697), (0.0113, 0.0170)
(1, 1, 2) (-0.6928, -0.7938, -0.0205) 1.5940 x2=(0.0,0.0376)x_2 = (0.0, 0.0376) lies on the boundary of the two cells

Line L7 returns (1,1,1)(1, 1, 1) and the controller applies u0=−0.8270u_0 = -0.8270. In closed loop from (1,1)(1, 1), the first input saturates at −1-1, and the state norm is below 10−410^{-4} after 15 steps, with all inputs and states inside their bounds. This is a measurement on this example, not a theorem: the problem has no terminal constraint.

Correctness

For a fixed sequence σ\sigma, the states are affine in UU, so the admissible inputs form a polyhedron and the cost is a strictly convex quadratic; line L5 gives its minimum. Every admissible pair (U,σ)(U, \sigma) has its σ\sigma in the loop of line L2, so the least of the QP minima is the minimum of the MIQP, and line L6 keeps it. The QP solver is the one step that the proof quotes rather than proves: Goldfarb and Idnani proved that their method stops at the optimum or detects infeasibility. The tests check the KKT conditions of its answers on random problems and compare with an enumeration of active sets. The full argument is in the correctness proof. Closed-loop properties are separate theorems: Bemporad and Morari (1999) prove convergence to the equilibrium xex_e with the terminal constraint xN=xex_N = x_e when the first problem is feasible, and Lazar et al. (2006) give conditions with a terminal cost and a terminal set for asymptotic stability in the sense of Lyapunov, as in the MPC stability theorem.

Proof: Enumeration of the mode sequences returns the optimum of the hybrid MPC problempartial

Setting. A piecewise affine system has modes i=1,…,si = 1, \ldots, s with x+=Aix+Biu+fix^+ = A_i x + B_i u + f_i on the closed cell Ci={x:Hix≤hi}\mathcal{C}_i = \{x : H_i x \le h_i\}, x∈Rnx \in \mathbb{R}^n, u∈Rmu \in \mathbb{R}^m. A mode sequence σ=(σ0,…,σN−1)\sigma = (\sigma_0, \ldots, \sigma_{N-1}) and an input sequence U=(u0,…,uN−1)U = (u_0, \ldots, u_{N-1}) are admissible from x0x_0 if the states xk+1=Aσkxk+Bσkuk+fσkx_{k+1} = A_{\sigma_k} x_k + B_{\sigma_k} u_k + f_{\sigma_k} satisfy xk∈Cσkx_k \in \mathcal{C}_{\sigma_k} for k=0,…,N−1k = 0, \ldots, N-1, umin⁡≤uk≤umax⁡u_{\min} \le u_k \le u_{\max}, and xmin⁡≤xk≤xmax⁡x_{\min} \le x_k \le x_{\max} for k=1,…,Nk = 1, \ldots, N. On a point shared by two cells either mode is admissible. The problem is

J∗(x0)=min⁡σ,U admissibleJ(U,σ),J=∑k=0N−1(xkTQxk+ukTRuk)+xNTPxN,J^*(x_0) = \min_{\sigma, U \text{ admissible}} J(U, \sigma), \qquad J = \sum_{k=0}^{N-1} \left(x_k^T Q x_k + u_k^T R u_k\right) + x_N^T P x_N,

with Q⪰0Q \succeq 0, P⪰0P \succeq 0 and R≻0R \succ 0. Lines L1 to L7 loop over all sNs^N sequences, solve one QP per sequence and keep the least cost.

Lemma 1 (condensing, line L4). For a fixed σ\sigma, xk=dk+ΓkUx_k = d_k + \Gamma_k U for k=0,…,Nk = 0, \ldots, N, where d0=x0d_0 = x_0, Γ0=0\Gamma_0 = 0, dk+1=Aσkdk+fσkd_{k+1} = A_{\sigma_k} d_k + f_{\sigma_k}, and Γk+1=AσkΓk+BσkEk\Gamma_{k+1} = A_{\sigma_k} \Gamma_k + B_{\sigma_k} E_k, with EkE_k the m×Nmm \times Nm matrix that picks uku_k out of UU.

Proof. Induction on kk. The case k=0k = 0 holds. If xk=dk+ΓkUx_k = d_k + \Gamma_k U, then xk+1=Aσk(dk+ΓkU)+BσkEkU+fσk=dk+1+Γk+1Ux_{k+1} = A_{\sigma_k}(d_k + \Gamma_k U) + B_{\sigma_k} E_k U + f_{\sigma_k} = d_{k+1} + \Gamma_{k+1} U. ■\blacksquare

Lemma 2 (the QP of one sequence). For a fixed σ\sigma, J(U,σ)=12UTHU+ϕTU+cJ(U, \sigma) = \frac12 U^T \mathcal{H} U + \phi^T U + c with

H=2(∑k=0NΓkTWkΓk+IN⊗R),ϕ=2∑k=0NΓkTWkdk,c=∑k=0NdkTWkdk,\mathcal{H} = 2\Big(\sum_{k=0}^{N} \Gamma_k^T W_k \Gamma_k + I_N \otimes R\Big), \qquad \phi = 2 \sum_{k=0}^{N} \Gamma_k^T W_k d_k, \qquad c = \sum_{k=0}^{N} d_k^T W_k d_k,

where Wk=QW_k = Q for k<Nk < N and WN=PW_N = P. H\mathcal{H} is positive definite. The admissible set of UU for this σ\sigma is the polyhedron of the rows that the code builds: the input bounds, Hσk(dk+ΓkU)≤hσkH_{\sigma_k}(d_k + \Gamma_k U) \le h_{\sigma_k} for k=1,…,N−1k = 1, \ldots, N-1, and the state bounds on dk+ΓkUd_k + \Gamma_k U for k=1,…,Nk = 1, \ldots, N, provided x0∈Cσ0x_0 \in \mathcal{C}_{\sigma_0}.

Proof. Substitute Lemma 1 into JJ and expand each quadratic form; the input terms give UT(IN⊗R)UU^T (I_N \otimes R) U. The matrix H\mathcal{H} is a sum of a positive semidefinite part and 2(IN⊗R)≻02(I_N \otimes R) \succ 0. The cell condition at k=0k = 0 does not depend on UU; line L3 tests it and skips σ\sigma if it fails. The other conditions are the admissibility conditions with xkx_k replaced by Lemma 1. ■\blacksquare

Quoted result (the QP solver, line L5). Goldfarb and Idnani (1983) proved that their dual active set method, applied to a strictly convex QP, either stops at the optimum in a finite number of steps or detects that the constraints have no common point. The code follows this method. Separately, any (U,λ)(U, \lambda) with HU+ϕ+CTλ=0\mathcal{H} U + \phi + C^T \lambda = 0, CU≤bCU \le b, λ≥0\lambda \ge 0 and λi(b−CU)i=0\lambda_i (b - CU)_i = 0 is the unique optimum, since the QP is convex with H≻0\mathcal{H} \succ 0 (the KKT conditions are sufficient). The tests check these conditions on random problems and compare with an enumeration of active sets. The proof below assumes that line L5 returns the optimum of a feasible QP and None for an infeasible one; this is the step that is quoted, not proved here.

Theorem. If some admissible pair exists, line L7 returns (U∗,σ∗,J∗)(U^*, \sigma^*, J^*) with J(U∗,σ∗)=J∗(x0)J(U^*, \sigma^*) = J^*(x_0) and (U∗,σ∗)(U^*, \sigma^*) admissible. If none exists, it returns None.

Proof. Let FσF_\sigma be the admissible set of UU for σ\sigma; by Lemma 2 it is empty if line L3 skips σ\sigma, and otherwise it is the feasible set of the QP of line L5. Every admissible pair has its σ\sigma in the loop of line L2, so the admissible pairs are exactly the pairs (U,σ)(U, \sigma) with U∈FσU \in F_\sigma, and

J∗(x0)=min⁡σmin⁡U∈FσJ(U,σ).J^*(x_0) = \min_{\sigma} \min_{U \in F_\sigma} J(U, \sigma).

For each σ\sigma with FσF_\sigma nonempty, line L5 returns the inner minimizer and the code adds back the constant cc of Lemma 2, so it has the inner minimum. Line L6 keeps the least value seen so far. After the loop, bestbest holds the outer minimum and a pair that attains it. If all FσF_\sigma are empty, bestbest stays None (line L1). ■\blacksquare

Termination. The loop of line L2 has sNs^N passes. Each pass builds H\mathcal{H}, ϕ\phi and the rows in polynomial time in nn, mm and NN, and the QP method stops in finitely many steps (quoted above; the code also stops with an error after a fixed number of iterations). The closed loop of lines L8 and L9 calls this a given number of times.

What is not proved. The theorem is about one sampling instant. Feasibility at the next instant and convergence of the closed loop need more: Bemporad and Morari (1999) use a terminal equality constraint at the equilibrium, and Lazar, Heemels, Weiland and Bemporad (2006) use a terminal cost and a terminal set. The example on the page has neither; its closed loop reaches the origin in the tests, which is a measurement, not a theorem. On a point shared by two cells, the optimizer may pick a mode that differs from the one the true system uses; then the predicted and true next states differ.

Complexity

The model is the real RAM. Per sampling instant:

  • Enumeration (this code). sNs^N QPs. Each has NmNm variables, 2Nm2Nm input bounds, 2Nn2Nn state bounds and the cell rows of x1,…,xN−1x_1, \ldots, x_{N-1}. Building Γk\Gamma_k and H\mathcal{H} costs O(N3nm2)O(N^3 n m^2), and cc is the cost of the QP. The total is O(sN(N3nm2+c))O(s^N (N^3 n m^2 + c)) time and O(N2m(n+m))O(N^2 m (n + m)) extra space.
  • Branch and bound on the MLD form. One MIQP with N(m+ns)N(m + n s) real variables, NsN s binary variables and the big-M rows. In the worst case it also explores 2Ns2^{Ns} leaves, since MIQP is NP-hard. In practice the relaxations prune most of the tree; how much depends on the model and the tightness of the big-M constants (rule of thumb, not a theorem).
  • Explicit hybrid MPC. The optimal input is a piecewise affine function of x0x_0 on a partition that is not convex in general, computed offline by multiparametric quadratic programming for each mode sequence, or by dynamic programming (Borrelli, Bemporad and Morari 2017, Chapter 17). Online cost is a point location, but the number of regions can grow exponentially with NN.

Properties

  • Exact per instant. Enumeration and complete branch and bound both return the global optimum of the MIQP, not a local one.
  • Online. It solves one optimization per sampling instant, so the time to solve must fit in the sampling period.
  • Discontinuous control law. The optimal input can jump when the optimal mode sequence changes, even for a continuous PWA system.
  • Same tuning as linear MPC. QQ, RR, PP, the horizon and the constraints have the same roles as in linear MPC.

Variants and improvements

  • Linear costs. With 1-norm or infinity-norm stage costs, each instant is a mixed-integer linear program, which mature MILP solvers handle well (Bemporad and Morari 1999).
  • Explicit hybrid MPC. Precompute the control law offline, as in explicit MPC, and store the regions; Borrelli, Bemporad and Morari (2017, Chapter 17) give the method.
  • Fewer sequences. Restrict the mode sequences to those that the reachable sets of the PWA system allow, or fix the mode after a few steps (move blocking of the modes). This trades optimality for speed.
  • Stabilizing terminal ingredients. Add a terminal equality constraint (Bemporad and Morari 1999) or a terminal cost and set (Lazar et al. 2006).
  • Modeling tools. HYSDEL (Torrisi and Bemporad 2004) compiles a description with logic and real variables into MLD form.

When to use it

Use it when the plant has real switching that a linear model cannot capture and the horizon is short enough for the solver: automotive traction and gear control, power converters, water and gas networks with valves, contact in robot locomotion (a related convex scheme is convex MPC for legged locomotion, which fixes the contact sequence in advance). If the mode sequence is known, fix it and use linear MPC on a time-varying model. If the plant switches without control, and only robustness to the switching is needed, a switched system analysis may be enough.

Pitfalls

  • Boundaries of the cells (line L3). With closed cells, a state on a shared boundary is admissible in both modes, and the optimizer may plan with a mode that the real system does not use there. Make the dynamics agree on the boundary, or make one cell open on it.
  • Exponential growth (line L2). sNs^N grows fast: 2 modes and N=20N = 20 give about 10610^6 QPs. Enumeration is for small examples and tests only.
  • Loose big-M constants. Big constants in the MLD form weaken the relaxations and slow branch and bound. Compute them from bounds on the states and inputs, as pwa_to_mld does.
  • No guarantee without terminal ingredients. Without a terminal constraint or a terminal cost and set, the closed loop may lose feasibility or fail to converge, even if each instant is solved exactly.
  • Time limit. A solver stopped early returns a feasible but suboptimal input; the stability arguments that assume the optimum then need a separate proof for suboptimal solutions.

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.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
hybrid_mpc.py 314 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-mpc/. The authors are listed in prov/1PY7EN.jsonl.

"""Hybrid MPC for a small piecewise affine (PWA) system, by enumeration of
the mode sequences and one convex QP per sequence.

A PWA system is a list of modes. A mode is a dict with the keys
"A" (n by n), "B" (n by m), "f" (n), "H" (q by n) and "h" (q). In mode i the
dynamics are x+ = A x + B u + f, and the mode is active on the closed cell
{x : H x <= h}. The cells must cover the state set and may only share
boundary points.

At each sampling instant the controller solves

    min  sum_{k=0}^{N-1} (x_k' Q x_k + u_k' R u_k) + x_N' P x_N
    s.t. x_0 = the measured state, x_{k+1} = the PWA dynamics,
         umin <= u_k <= umax, xmin <= x_k <= xmax for k = 1, ..., N,

and applies u_0. This is a mixed-integer QP. For a fixed mode sequence
(sigma_0, ..., sigma_{N-1}) the states are affine in U = (u_0, ..., u_{N-1}),
and the problem is a convex QP in N m variables with 2 N m input bounds,
2 N n state bounds and the cell rows of x_1, ..., x_{N-1}. The code solves
all s^N of them (s modes) with the dual active-set method of Goldfarb and
Idnani (1983) and keeps the best. This is exact but exponential in N; real
solvers use branch and bound on the mixed logical dynamical (MLD) form.

pwa_to_mld writes the same PWA system as big-M inequalities in the binary
variables delta_i (mode i is on) and the real variables z_i (the next state
if mode i is on), as in Bemporad and Morari (1999).
"""

import itertools
import math

from ctlmat import inv, matvec, mul, solve, transpose

__all__ = [
    "qp_solve", "qp_cost", "predict", "condense", "mpc_step", "pwa_step",
    "mode_of", "closed_loop", "pwa_to_mld", "mld_rows_hold", "rotation_example",
]


# ---------------------------------------------------------------- the QP solver

def qp_cost(h, f, x):
    """Return 1/2 x' H x + f' x."""
    hx = matvec(h, x)
    return 0.5 * sum(a * b for a, b in zip(x, hx)) + sum(a * b for a, b in zip(f, x))


def qp_solve(h, f, c, b, tol=1e-9, max_iter=500):
    """Solve min 1/2 x' H x + f' x subject to C x <= b, for H positive definite.

    Goldfarb-Idnani dual active-set method. It starts at the unconstrained
    minimum and adds the most violated constraint; a partial step drops an
    active constraint whose multiplier would become negative. Returns
    (x, lam) with H x + f + C' lam = 0, lam >= 0 and lam_i = 0 off the
    active set, or None if the constraints have no common point.
    """
    n = len(f)
    hinv = inv([[float(v) for v in row] for row in h])
    x = [-v for v in matvec(hinv, f)]
    normals = [[-v for v in row] for row in c]  # n_i . x + b_i >= 0 is row i
    scale = [math.sqrt(sum(v * v for v in row)) or 1.0 for row in c]
    active, u = [], []
    for _ in range(max_iter):
        slack = [sum(a * xi for a, xi in zip(nr, x)) + bi for nr, bi in zip(normals, b)]
        viol = [(s / sc, i) for i, (s, sc) in enumerate(zip(slack, scale)) if s < -tol * sc and i not in active]
        if not viol:
            lam = [0.0] * len(c)
            for i, ui in zip(active, u):
                lam[i] = ui
            return x, lam
        _, p = min(viol)
        u_plus = u + [0.0]
        npv = normals[p]
        while True:
            hn = matvec(hinv, npv)
            if active:
                nmat = [normals[i] for i in active]
                gram = [[sum(a * bb for a, bb in zip(ni, matvec(hinv, nj))) for nj in nmat] for ni in nmat]
                r = solve(gram, [sum(a * bb for a, bb in zip(ni, hn)) for ni in nmat])
                z = matvec(hinv, [npv[k] - sum(r[j] * nmat[j][k] for j in range(len(active))) for k in range(n)])
            else:
                r, z = [], hn
            t1, drop = math.inf, None
            for j, rj in enumerate(r):
                if rj > tol and u_plus[j] / rj < t1:
                    t1, drop = u_plus[j] / rj, j
            zn = sum(a * bb for a, bb in zip(z, npv))
            sp = sum(a * xi for a, xi in zip(npv, x)) + b[p]
            ref = sum(a * bb for a, bb in zip(npv, hn))
            t2 = -sp / zn if zn > 1e-12 * ref else math.inf
            t = min(t1, t2)
            if t == math.inf:
                return None
            for j in range(len(r)):
                u_plus[j] -= t * r[j]
            u_plus[-1] += t
            if t2 < math.inf:
                x = [xi + t * zi for xi, zi in zip(x, z)]
            if t2 <= t1:
                active.append(p)
                u = u_plus
                break
            del active[drop]
            del u_plus[drop]
    raise RuntimeError("qp_solve: no convergence")


# ---------------------------------------------------------------- PWA model

def mode_of(modes, x, tol=0.0):
    """Return the first mode whose cell holds x."""
    for i, md in enumerate(modes):
        if all(sum(a * v for a, v in zip(row, x)) <= hi + tol for row, hi in zip(md["H"], md["h"])):
            return i
    raise ValueError("mode_of: x is in no cell")


def pwa_step(modes, x, u, mode=None):
    """Return x+ = A x + B u + f of the mode of x (or of the given mode)."""
    md = modes[mode_of(modes, x) if mode is None else mode]
    return [ax + bu + fi for ax, bu, fi in zip(matvec(md["A"], x), matvec(md["B"], u), md["f"])]


def predict(modes, x0, us, seq):
    """States x_0, ..., x_N under the mode sequence seq (cells not checked)."""
    xs = [list(x0)]
    for u, s in zip(us, seq):
        xs.append(pwa_step(modes, xs[-1], u, mode=s))
    return xs


def condense(modes, seq, x0):
    """Return lists phi_d, gam: x_k = d_k + Gam_k U for k = 0, ..., N.

    d_k is the free response under the modes of seq (with the affine terms),
    and Gam_k is n by N m.
    """
    n = len(x0)
    m = len(modes[0]["B"][0])
    big = len(seq) * m
    d = [list(map(float, x0))]
    gam = [[[0.0] * big for _ in range(n)]]
    for k, s in enumerate(seq):
        md = modes[s]
        a = md["A"]
        d.append([v + fi for v, fi in zip(matvec(a, d[-1]), md["f"])])
        g = mul(a, gam[-1])
        for i in range(n):
            for j in range(m):
                g[i][k * m + j] += md["B"][i][j]
        gam.append(g)
    return d, gam


def _quad(q, x):
    return sum(x[i] * q[i][j] * x[j] for i in range(len(x)) for j in range(len(x)))


def mpc_step(modes, x0, horizon, q, r, p, umin, umax, xmin=None, xmax=None, sequences=None):
    """Return (U, seq, J): the optimal input sequence, its mode sequence and its cost.

    Returns None if no mode sequence is feasible. sequences, if given,
    restricts the search to these mode sequences.
    """
    n = len(x0)
    m = len(modes[0]["B"][0])
    big = horizon * m
    if sequences is None:
        sequences = itertools.product(range(len(modes)), repeat=horizon)
    best = None  # @line L1
    for seq in sequences:  # @line L2
        md0 = modes[seq[0]]
        if any(sum(a * v for a, v in zip(row, x0)) > hi for row, hi in zip(md0["H"], md0["h"])):
            continue  # @line L3
        d, gam = condense(modes, seq, x0)  # @line L4
        hmat = [[0.0] * big for _ in range(big)]
        fvec = [0.0] * big
        const = 0.0
        for k in range(horizon + 1):
            w = p if k == horizon else q
            gt = transpose(gam[k])
            hmat = [[a + 2 * bb for a, bb in zip(ra, rb)] for ra, rb in zip(hmat, mul(mul(gt, w), gam[k]))]
            fvec = [a + 2 * bb for a, bb in zip(fvec, matvec(gt, matvec(w, d[k])))]
            const += _quad(w, d[k])
        for k in range(horizon):
            for i in range(m):
                for j in range(m):
                    hmat[k * m + i][k * m + j] += 2 * r[i][j]
        rows, rhs = [], []
        for k in range(horizon):
            for j in range(m):
                e = [0.0] * big
                e[k * m + j] = 1.0
                rows.append(e)
                rhs.append(umax[j])
                rows.append([-v for v in e])
                rhs.append(-umin[j])
        for k in range(1, horizon + 1):
            if k < horizon:
                md = modes[seq[k]]
                for row, hi in zip(md["H"], md["h"]):
                    rows.append([sum(row[i] * gam[k][i][j] for i in range(n)) for j in range(big)])
                    rhs.append(hi - sum(a * v for a, v in zip(row, d[k])))
            if xmax is not None:
                for i in range(n):
                    rows.append(list(gam[k][i]))
                    rhs.append(xmax[i] - d[k][i])
                    rows.append([-v for v in gam[k][i]])
                    rhs.append(d[k][i] - xmin[i])
        sol = qp_solve(hmat, fvec, rows, rhs)  # @line L5
        if sol is None:
            continue
        cost = qp_cost(hmat, fvec, sol[0]) + const
        if best is None or cost < best[2]:  # @line L6
            best = (sol[0], seq, cost)
    return best  # @line L7


def closed_loop(modes, x0, steps, horizon, q, r, p, umin, umax, xmin=None, xmax=None):
    """Apply u_0 of mpc_step to the true PWA system for the given number of steps.

    Returns (xs, us). Stops early if a step is infeasible.
    """
    m = len(modes[0]["B"][0])
    xs, us = [list(x0)], []
    for _ in range(steps):
        res = mpc_step(modes, xs[-1], horizon, q, r, p, umin, umax, xmin, xmax)
        if res is None:
            break
        u0 = res[0][:m]  # @line L8
        us.append(u0)
        xs.append(pwa_step(modes, xs[-1], u0))  # @line L9
    return xs, us


# ---------------------------------------------------------------- MLD form

def _range(row, lo, hi):
    """Min and max of row . v over the box lo <= v <= hi."""
    a = sum(c * (l if c >= 0 else h) for c, l, h in zip(row, lo, hi))
    b = sum(c * (h if c >= 0 else l) for c, l, h in zip(row, lo, hi))
    return a, b


def pwa_to_mld(modes, xlo, xhi, ulo, uhi):
    """Big-M MLD form of a PWA system on the box xlo <= x <= xhi, ulo <= u <= uhi.

    Variables w = (x, u, delta_1..delta_s, z_1..z_s), with z_i in R^n. Returns
    (rows, eq): rows is a list of (a, b) meaning a . w <= b, and eq is the
    row of sum delta_i = 1. The next state is x+ = z_1 + ... + z_s.
    For each mode i:
      H_i x - h_i <= M (1 - delta_i)            (delta_i = 1 forces the cell)
      mlo delta_i <= z_i <= mhi delta_i         (delta_i = 0 forces z_i = 0)
      g_i - mhi (1 - delta_i) <= z_i <= g_i - mlo (1 - delta_i),
    where g_i = A_i x + B_i u + f_i and [mlo, mhi] bounds g_i on the box.
    """
    n, m, s = len(xlo), len(ulo), len(modes)
    width = n + m + s + s * n
    lo, hi = list(xlo) + list(ulo), list(xhi) + list(uhi)
    rows = []

    def row():
        return [0.0] * width

    for i, md in enumerate(modes):
        di = n + m + i
        for hrow, hval in zip(md["H"], md["h"]):
            big_m = max(0.0, _range(list(hrow) + [0.0] * m, lo, hi)[1] - hval)
            a = row()
            a[:n] = [float(v) for v in hrow]
            a[di] = big_m
            rows.append((a, hval + big_m))
        for k in range(n):
            g = [float(v) for v in md["A"][k]] + [float(v) for v in md["B"][k]]
            mlo, mhi = _range(g, lo, hi)
            mlo, mhi = mlo + md["f"][k], mhi + md["f"][k]
            zk = n + m + s + i * n + k
            a = row()
            a[zk], a[di] = 1.0, -mhi
            rows.append((a, 0.0))
            a = row()
            a[zk], a[di] = -1.0, mlo
            rows.append((a, 0.0))
            a = row()
            a[:n + m] = [-v for v in g]
            a[zk], a[di] = 1.0, -mlo
            rows.append((a, md["f"][k] - mlo))
            a = row()
            a[:n + m] = g
            a[zk], a[di] = -1.0, mhi
            rows.append((a, mhi - md["f"][k]))
    eq = [0.0] * (n + m) + [1.0] * s + [0.0] * (s * n)
    return rows, eq


def mld_rows_hold(rows, w, tol=1e-9):
    """Return True if every row a . w <= b holds within tol."""
    return all(sum(ai * wi for ai, wi in zip(a, w)) <= b + tol for a, b in rows)


# ---------------------------------------------------------------- the example

def rotation_example(rho=0.8, angle=math.pi / 3):
    """Two modes: x+ = rho R(+angle) x + [0, 1]' u if x_1 >= 0, rho R(-angle) x + [0, 1]' u if x_1 <= 0."""
    def rot(t):
        return [[rho * math.cos(t), -rho * math.sin(t)], [rho * math.sin(t), rho * math.cos(t)]]
    b = [[0.0], [1.0]]
    return [
        {"A": rot(angle), "B": b, "f": [0.0, 0.0], "H": [[-1.0, 0.0]], "h": [0.0]},
        {"A": rot(-angle), "B": b, "f": [0.0, 0.0], "H": [[1.0, 0.0]], "h": [0.0]},
    ]
test_hybrid_mpc.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-mpc/. The authors are listed in prov/1PY7EN.jsonl.

import itertools
import math
import random

from ctlmat import solve
from hybrid_mpc import (
    closed_loop,
    condense,
    mld_rows_hold,
    mode_of,
    mpc_step,
    predict,
    pwa_step,
    pwa_to_mld,
    qp_cost,
    qp_solve,
    rotation_example,
)

I2 = [[1.0, 0.0], [0.0, 1.0]]
R = [[0.1]]
UMIN, UMAX = [-1.0], [1.0]
XMIN, XMAX = [-10.0, -10.0], [10.0, 10.0]
MODES = rotation_example(1.2)


def random_pd(rng, n):
    m = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    return [[sum(m[k][i] * m[k][j] for k in range(n)) + (0.5 if i == j else 0.0) for j in range(n)] for i in range(n)]


def random_qp(rng, n, k):
    h = random_pd(rng, n)
    f = [rng.uniform(-2, 2) for _ in range(n)]
    c = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(k)]
    x0 = [rng.uniform(-1, 1) for _ in range(n)]
    # Make x0 strictly feasible, so the QP is feasible.
    b = [sum(a * v for a, v in zip(row, x0)) + rng.uniform(0.05, 1.0) for row in c]
    return h, f, c, b


def check_kkt(h, f, c, b, x, lam, tol=1e-7):
    grad = [sum(h[i][j] * x[j] for j in range(len(x))) + f[i] + sum(c[k][i] * lam[k] for k in range(len(c))) for i in range(len(x))]
    assert max(abs(g) for g in grad) < tol
    for row, bi, li in zip(c, b, lam):
        s = bi - sum(a * v for a, v in zip(row, x))
        assert s > -tol and li > -tol and abs(s * li) < tol


def brute_force_qp(h, f, c, b):
    """Try every active set of size at most n; keep the best KKT point."""
    n = len(f)
    best = None
    for size in range(n + 1):
        for act in itertools.combinations(range(len(c)), size):
            kkt = [[0.0] * (n + size) for _ in range(n + size)]
            rhs = [-v for v in f] + [b[i] for i in act]
            for i in range(n):
                for j in range(n):
                    kkt[i][j] = h[i][j]
                for t, a in enumerate(act):
                    kkt[i][n + t] = c[a][i]
                    kkt[n + t][i] = c[a][i]
            try:
                sol = solve(kkt, rhs)
            except ValueError:
                continue
            x, mult = sol[:n], sol[n:]
            if min(mult, default=0.0) < -1e-9:
                continue
            if any(sum(a * v for a, v in zip(row, x)) > bi + 1e-9 for row, bi in zip(c, b)):
                continue
            val = qp_cost(h, f, x)
            if best is None or val < best:
                best = val
    return best


def test_qp_kkt_on_random_problems():
    rng = random.Random(1)
    for _ in range(200):
        n, k = rng.randint(1, 4), rng.randint(0, 8)
        h, f, c, b = random_qp(rng, n, k)
        x, lam = qp_solve(h, f, c, b)
        check_kkt(h, f, c, b, x, lam)


def test_qp_matches_active_set_enumeration():
    rng = random.Random(2)
    for _ in range(100):
        n, k = rng.randint(1, 3), rng.randint(1, 7)
        h, f, c, b = random_qp(rng, n, k)
        x, _ = qp_solve(h, f, c, b)
        assert abs(qp_cost(h, f, x) - brute_force_qp(h, f, c, b)) < 1e-8


def test_qp_detects_infeasibility():
    h, f = [[1.0]], [0.0]
    assert qp_solve(h, f, [[1.0], [-1.0]], [-1.0, -1.0]) is None  # x <= -1 and x >= 1
    h2 = [[2.0, 0.0], [0.0, 1.0]]
    c = [[1.0, 1.0], [-1.0, 0.0], [0.0, -1.0]]
    assert qp_solve(h2, [0.0, 0.0], c, [-1.0, 0.0, 0.0]) is None  # x + y <= -1 with x, y >= 0


def test_condensed_prediction_matches_simulation():
    rng = random.Random(3)
    for _ in range(20):
        seq = tuple(rng.randint(0, 1) for _ in range(4))
        x0 = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        us = [[rng.uniform(-1, 1)] for _ in range(4)]
        d, gam = condense(MODES, seq, x0)
        xs = predict(MODES, x0, us, seq)
        flat = [u[0] for u in us]
        for k in range(5):
            pred = [d[k][i] + sum(gam[k][i][j] * flat[j] for j in range(4)) for i in range(2)]
            assert max(abs(a - b) for a, b in zip(pred, xs[k])) < 1e-12


def test_example_of_the_page():
    x0 = [1.0, 0.0]
    best = mpc_step(MODES, x0, 3, I2, R, I2, UMIN, UMAX, XMIN, XMAX)
    u, seq, cost = best
    assert seq == (0, 0, 0)
    assert abs(cost - 1.5474) < 1e-4
    assert all(abs(a - b) < 1e-4 for a, b in zip(u, [-0.8270, -0.6812, -0.1698]))
    other = mpc_step(MODES, x0, 3, I2, R, I2, UMIN, UMAX, XMIN, XMAX, sequences=[(0, 0, 1)])
    assert abs(other[2] - 1.5940) < 1e-4
    for seq in itertools.product((0, 1), repeat=3):
        if seq not in ((0, 0, 0), (0, 0, 1)):
            assert mpc_step(MODES, x0, 3, I2, R, I2, UMIN, UMAX, XMIN, XMAX, sequences=[seq]) is None


def true_cost(x0, us, horizon):
    xs = [x0]
    for u in us:
        xs.append(pwa_step(MODES, xs[-1], [u]))
    if any(abs(v) > 10 for x in xs for v in x):
        return math.inf
    return sum(x[0] ** 2 + x[1] ** 2 for x in xs) + 0.1 * sum(u * u for u in us)


def test_optimum_against_input_grid():
    """No input sequence on a grid beats the solver, and the best grid point is close to it."""
    for x0 in ([1.0, 0.0], [0.5, -1.0], [-1.0, 1.0], [0.2, 0.3]):
        _, _, cost = mpc_step(MODES, x0, 2, I2, R, I2, UMIN, UMAX, XMIN, XMAX)
        grid = [-1.0 + 0.02 * i for i in range(101)]
        best = min(true_cost(x0, [a, b], 2) for a in grid for b in grid)
        assert cost <= best + 1e-9
        assert best - cost < 2e-3


def test_closed_loop_reaches_origin():
    """The open loop diverges (rho = 1.2); the MPC loop meets |u| <= 1 and goes to 0."""
    x = [1.0, 1.0]
    for _ in range(15):
        x = pwa_step(MODES, x, [0.0])
    assert math.hypot(*x) > 10
    for x0 in ([1.0, 1.0], [1.0, 0.0], [-1.0, -0.5]):
        xs, us = closed_loop(MODES, x0, 15, 3, I2, R, I2, UMIN, UMAX, XMIN, XMAX)
        assert len(us) == 15
        assert all(-1 - 1e-9 <= u[0] <= 1 + 1e-9 for u in us)
        assert all(abs(v) <= 10 for x in xs for v in x)
        assert math.hypot(*xs[-1]) < 1e-4


def test_mld_big_m_agrees_with_pwa():
    rng = random.Random(4)
    xlo, xhi, ulo, uhi = [-5.0, -5.0], [5.0, 5.0], [-1.0], [1.0]
    rows, eq = pwa_to_mld(MODES, xlo, xhi, ulo, uhi)
    for _ in range(300):
        x = [rng.uniform(-5, 5), rng.uniform(-5, 5)]
        if rng.random() < 0.1:
            x[0] = 0.0
        u = [rng.uniform(-1, 1)]
        feasible = []
        for i in range(2):
            delta = [1.0 if j == i else 0.0 for j in range(2)]
            assert sum(a * v for a, v in zip(eq[3:5], delta)) == 1.0
            g = pwa_step(MODES, x, u, mode=i)
            z = [v * delta[j] for j in range(2) for v in g]
            w = x + u + delta + z
            if mld_rows_hold(rows, w):
                feasible.append(i)
                xnext = [z[k] + z[2 + k] for k in range(2)]
                assert xnext == g
                # z is fixed by the rows: moving one entry breaks a row.
                for k in range(4):
                    for step in (1e-6, -1e-6):
                        w2 = list(w)
                        w2[5 + k] += step
                        assert not mld_rows_hold(rows, w2, tol=1e-12)
        if x[0] > 0:
            assert feasible == [0]
        elif x[0] < 0:
            assert feasible == [1]
        else:
            assert feasible == [0, 1]
        assert mode_of(MODES, x) == feasible[0]

History

Sontag (1981) studied piecewise linear systems in discrete time. Bemporad and Morari (1999) introduced MLD models, which put logic, dynamics and constraints into mixed-integer linear inequalities, and formulated predictive control of these models as MIQP or MILP. Heemels, De Schutter and Bemporad (2001) showed that MLD, PWA and other hybrid model classes are equivalent under mild conditions, so results for one transfer to the others. Torrisi and Bemporad (2004) gave the HYSDEL language. Lazar, Heemels, Weiland and Bemporad (2006) gave stabilizing terminal conditions for PWA systems. Borrelli, Bemporad and Morari (2017) collected the theory, including explicit solutions, in a textbook.

References

  1. A. Bemporad and M. Morari, Control of systems integrating logic, dynamics, and constraints, Automatica 35(3), 1999, pages 407 to 427, the MLD form, the predictive control law as a mixed-integer quadratic program, and its stability with a terminal equality constraint
  2. F. Borrelli, A. Bemporad and M. Morari, Predictive Control for Linear and Hybrid Systems, Cambridge University Press, 2017, Chapter 16, Models of Hybrid Systems, and Chapter 17, Optimal Control of Hybrid Systems
  3. M. Lazar, W. P. M. H. Heemels, S. Weiland and A. Bemporad, Stabilizing model predictive control of hybrid systems, IEEE Transactions on Automatic Control 51(11), 2006, pages 1813 to 1818, terminal cost and terminal set conditions for the stability of hybrid MPC of PWA systems
  4. F. D. Torrisi and A. Bemporad, HYSDEL: a tool for generating computational hybrid models for analysis and synthesis problems, IEEE Transactions on Control Systems Technology 12(2), 2004, pages 235 to 249, the modeling language that compiles a hybrid description into MLD form
  5. W. P. M. H. Heemels, B. De Schutter and A. Bemporad, Equivalence of hybrid dynamical models, Automatica 37(7), 2001, pages 1085 to 1091, the equivalence of MLD, PWA and other hybrid model classes

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 correctness
  • 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