Algorithmadvanced
Maximal positively invariant set computation
Also called Gilbert-Tan algorithm, MPI set algorithm.
Computes the largest positively invariant set of x_(k+1) = A x_k inside polyhedral output limits by adding the limits of step t + 1 until a linear program shows they are redundant.
- Time
- O(t (n^3 + c n^2 + c L)) worst
- Space
- O(c t n) extra
- Where
- L = the cost of one linear program in n variables with at most c (t + 1) rows; c = the number of rows of the output limits F y <= g; n = the number of states; t = the index at which the algorithm stops, the determinedness index
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Elmer G. Gilbert, K. T. Tan, 1991
The maximal positively invariant set of the linear system under the output limits is the set of all initial states whose whole trajectory meets the limits:
It is the largest positively invariant set inside . Gilbert and Tan (1991) called it the maximal output admissible set. For a polyhedron , the algorithm of this page adds the limits of steps one block at a time and checks with one linear program per row whether the new limits cut anything off. It stops at the first at which nothing is cut, and then is a polyhedron with a finite description. Gilbert and Tan proved that such a exists when is Schur, is observable, and is bounded with 0 in its interior. In MPC the set is the usual terminal set of linear MPC: is the closed loop of the LQR gain, and stacks the state limits and the input .
In plain words
A system moves by itself under a fixed rule, and its outputs must stay inside some limits. Some starting points are safe forever. Others are inside the limits now but leave them later. This method finds all the safe starting points. It first keeps the points that meet the limits now. Then it adds the condition for one step later, then two steps later, and so on. After each new step it asks whether the new condition removes any point that is still in the set. When a new step removes nothing, every later step also removes nothing, so the set is final. Each check is a small optimization problem with a linear goal and linear limits.
The problem
Input: , , and the output limits with and . Output: an index and a finite list of inequalities whose solution set is , with
The sets shrink: . The set is finitely determined if for some finite ; the smallest such is the determinedness index . The algorithm can only return a finite description, so it needs finite determination. For an MPC terminal set with the gain , take in place of , the stacked output and the limits on states and inputs as .
The algorithm
MPI(A, C, F, g)- 1
(rows, bounds) ← (F C, g) ▷ O_0 = {x : F C x ≤ g} - 2
for t = 0, 1, 2, ... - 3
R ← F C A^(t+1) ▷ the limits of step t + 1 - 4
for each row r_i of R, with bound g_i - 5
v_i ← max r_i x subject to rows · x ≤ bounds ▷ one LP; v_i = ∞ if unbounded - 6
if v_i > g_i then mark row i as new - 7
if no row is new then return (rows, bounds, t) ▷ O_t = O_(t+1) = O_∞ - 8
append the new rows to rows and bounds ▷ the stored set is O_(t+1)
Line L5 asks how far the set reaches in the direction of the new row. If the answer is at most , the row holds on all of and it is redundant. Only the rows that cut are stored, so the stored description is shorter than the full list of rows, and it still describes , because the dropped rows hold on it. The implementation solves each LP with a two-phase simplex method with Bland's rule, in exact rational arithmetic for rational data. It stops with an error after a set number of passes, because without the hypotheses of finite determination the loop need not end. A last pass that removes redundant rows among the stored ones gives the facets of .
Example
A damped rotation. Let , a rotation by scaled by , with and the box , ( rows). For :
- Line L1 stores the 4 rows of the box.
- Pass : the rows of are , and their negatives. Each LP over the box gives , so all 4 rows are new.
- Pass : the rows of are , and their negatives. Each LP over the 8 rows gives . Nothing is new, so .
is the octagon with the vertices
The vertex lies on and on the new row : . The tests check exactly, in fractions, that maps each vertex into the octagon.
Slower decay needs more passes (measurement with the implementation):
| facets of | ||
|---|---|---|
| 9/10 | 1 | 8 |
| 19/20 | 2 | 12 |
| 99/100 | 4 | 20 |
For the loop never stops. The rotation keeps the length of , and is not a rational multiple of (by Niven's theorem, the only rational values of at rational multiples of are , and ). So every orbit on a circle of radius is dense on that circle, and is the closed unit disc. A disc is not a polyhedron, so no finite works.
An unbounded first set. Let , and . is the strip , so the LP of pass 0 is unbounded and the row of step 1 is new. Because is observable, is bounded. The algorithm returns , and is the hexagon with the vertices , , , , and .
The terminal set of the linear MPC example. For the double integrator , with the LQR gain of , , take , the limits and (). The algorithm stops at with 8 stored rows, and the redundancy pass leaves 6 facets:
The last pair is the input limit one step ahead, . This is the terminal set used on the linear MPC page.
Correctness
The proofs are in proofs/correctness.md.
- is the maximal positively invariant set in . If , every limit of is a limit of one step later, so . If is positively invariant, every trajectory from stays in , so .
- The stopping test is correct. The sets satisfy . If , then , and by induction all later sets are equal, so . The LP of line L5 decides row by row: the rows of step hold on all of exactly when each maximum is at most its bound. An unbounded LP means the row cuts .
- The loop ends under the hypotheses (theorem, Gilbert and Tan 1991). Suppose is Schur, is observable, is bounded and contains a ball of radius around 0. Observability and boundedness make bounded, say . Since , there is with for , so all limits of later steps hold automatically on . Hence .
- The LP answers are exact. The simplex method with Bland's rule does not cycle and stops with an optimum, an unbounded ray, or an infeasibility proof. With rational data the arithmetic is exact, so the comparison of line L6 has no rounding error.
The hypotheses of point 3 are sufficient, not necessary. The unbounded-strip example above has in the interior of but an unbounded , and observability still bounds .
Proof: The stopping test O_t = O_(t+1) gives the maximal positively invariant set, and the test is reached under stability, observability and a bounded constraint setfull
The system is with output , , . The constraint set is . For let
So is the set of initial states whose output stays in for all time. The sets are nested: .
Part 1: is the maximal positively invariant set in
Lemma 1. is positively invariant (), it lies in , and every positively invariant set lies in .
Proof. If then for all , so . by definition. If is positively invariant and , then for every , that is, for all , so .
Part 2: the stopping test
Lemma 2. .
Proof. means for , that is, the conditions on . Together with these are the conditions of .
Lemma 3. If , then .
Proof. Let . Then , so by Lemma 2. So is positively invariant, and . By Lemma 1, . The other inclusion holds because the sets are nested.
So once the test succeeds, every later set is the same, and the algorithm may stop.
Lemma 4 (the LP test, lines L4 to L6). Let be any description of . Then if and only if, for each row of ,
where an unbounded maximum counts as a failure.
Proof. . This equals if and only if every satisfies each new row, which is the condition on the maximum.
Lemma 5 (the stored description). At the start of iteration of line L2, the stored rows describe .
Proof. Line L1 stores , the rows of . In iteration , line L8 adds the rows of whose maximum over the stored set is larger than the bound. A row whose maximum is at most its bound holds at every point of , so adding it would not change the set. So the stored rows after the iteration describe .
Theorem 1 (correctness). If the algorithm returns at line L7 with index , the returned rows describe , the maximal positively invariant subset of , and is the smallest with .
Proof. Line L7 returns when no row of step is new, that is, when by Lemmas 4 and 5. Lemma 3 and Lemma 1 give the rest. The loop tries in order, so the first success is the smallest such .
Part 3: finite determination
The loop is guaranteed to reach the test only under extra hypotheses. Without them it can run forever: for a rotation by an angle that is not a rational multiple of and a box , the sets keep gaining facets.
Theorem 2. Suppose is Schur (all eigenvalues in the open unit disc), is observable, is bounded, and contains a ball with . Then for some , so the algorithm stops.
Proof. Step 1: is bounded. Since is bounded there is with for . The observability matrix has full column rank, so is invertible and . For each block lies in , so . Hence on for some .
Step 2: late constraints are automatic. Since is Schur, , so there is with for all . For and , , so .
Step 3: let . For the condition of step holds by Step 2. So .
The bound from the proof depends on how fast decays, so the bound grows without limit as the spectral radius of tends to 1. The index itself need not grow: for with and a box symmetric about 0, . This is why the iteration count is part of the output and not a constant.
Part 4: the linear programs
Each LP of line L5 has the form maximize subject to with free. The routine writes with and adds a slack per row. Rows with get an artificial variable, and phase one maximizes minus the sum of the artificials; a positive optimal sum means no feasible point. Phase two runs the simplex method on the original cost. Both phases use Bland's rule (the first improving column enters, ties in the ratio test are broken by the smallest basic index), which prevents cycling, so each phase stops after finitely many pivots. A column with an improving reduced cost and no positive entry is a ray along which the objective grows without bound, which is the unbounded report. These are the standard correctness facts of the simplex method; see the simplex method page. With integer and rational data the code uses exact rational arithmetic, so the tests of line L6 have no rounding error.
Complexity
Costs are in the real-RAM model.
- One pass. Line L3 costs if is kept and multiplied by once per pass (the implementation recomputes the power, which adds ). Lines L4 to L6 solve linear programs in variables with at most rows.
- All passes. passes give , with the cost of one LP. With the simplex method, has no polynomial bound in the worst case. An interior point method is polynomial in the bit model, in the size of the LP and the bit length of the data; in the real-RAM model no strongly polynomial LP algorithm is known.
- The index . It is not bounded by a function of and alone. The bound grows as the spectral radius of tends to 1, and the table above shows the growth (measurement).
- Space. The stored rows number at most , each of length .
Properties
- Exact output. In exact arithmetic the returned inequalities describe exactly. It is a polyhedron, and a polytope when it is bounded.
- Convex and symmetric. is convex because it is an intersection of half-spaces. If is symmetric about 0, so is .
- Contains a neighborhood of 0. If is Schur and 0 is in the interior of , then contains a ball around 0, because and the supremum is finite.
- Monotone in the limits. Larger limits give a larger set.
- Redundant rows. The stored list can contain rows that are redundant at the end. One LP per row removes them.
Variants and improvements
- Systems with inputs and a fixed gain. The terminal set of MPC: apply the algorithm to with the stacked output above.
- Constant references. For a reference governor, the state is augmented with a constant reference. The matrix then has an eigenvalue 1, the set is in general not finitely determined, and the limits are tightened by a small margin on the steady-state part to restore finite determination. See reference governor.
- Maximal control invariant set. With a free input, iterate . Each step needs a projection, for example by Fourier-Motzkin elimination, which is much more expensive. See control-invariant set.
- Disturbances. For with in a polytope, tighten each limit of step by the support function of summed over . The result is the maximal robust positively invariant set. Robust methods such as tube MPC use sets of this kind.
- Ellipsoidal sets. A level set of a Lyapunov function, with chosen so that it fits inside the limits, is positively invariant and simpler, but in general smaller than .
When to use it
Use it to compute the terminal set of linear MPC, to check that a fixed linear controller keeps a constraint for all time from a given state, or to build the admissible sets of a reference governor. It suits small and moderate , where the number of LPs is small. For a large , or a spectral radius close to 1, the number of rows can grow large; then use an ellipsoidal set or a simpler terminal constraint.
Pitfalls
- No finite determination. If is not Schur, or is not observable, the loop may not end. Set a pass limit and report failure, as the implementation does. The rotation with shows the case.
- Rounding. In floating point a row whose maximum is very close to its bound can be judged wrongly. Use a tolerance, and check the result by testing for each vertex in two or three dimensions. Rational arithmetic avoids the problem for rational data.
- Unbounded LPs. When does not bound all states, is unbounded, and the LP of line L5 can be unbounded. Treat that answer as "the row is new", not as an error.
- Not the terminal set by itself. For MPC stability the terminal set must also go with a terminal cost that is a Lyapunov function for . The set alone does not give a decreasing cost. See MPC stability theorem.
- The input limit. For an MPC terminal set, include in the output. Without it, the set does not ensure that meets the input limits.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# 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()
maximal_positively_invariant_set.py 180 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-positively-invariant-set/. The authors are listed in prov/MVMQPG.jsonl.
"""Maximal positively invariant (maximal output admissible) set of x+ = A x.
The system is x_(k+1) = A x_k with the output y_k = C x_k, which must stay in
the polytope Y = {y : F y <= g} for all k >= 0. The maximal output admissible
set is
O_inf = {x : F C A^k x <= g for all k >= 0},
the largest positively invariant set inside {x : F C x <= g}. Write O_t for
the set with the constraints k = 0, ..., t only. The algorithm of Gilbert and
Tan (1991) adds the constraints of step t + 1 one block at a time and stops
at the first t with O_t = O_(t+1); then O_t = O_inf. The test O_t = O_(t+1)
is one linear program per row of F: the row of step t + 1 is redundant if
its maximum over O_t is at most its bound.
If A is Schur, (C, A) is observable, and Y is bounded with 0 in its
interior, such a t exists (O_inf is finitely determined).
The linear programs use a dense two phase simplex method with Bland's rule.
With int and Fraction data the arithmetic is exact (tol = 0). With float
data a tolerance is used.
"""
from fractions import Fraction
from ctlmat import mat_power, mul
__all__ = ["lp_max", "mpi_set", "remove_redundant", "Unbounded", "Infeasible"]
class Unbounded(Exception):
"""The linear program is unbounded."""
class Infeasible(Exception):
"""The linear program has no feasible point."""
def _pivot(T, basis, r, c):
piv = T[r][c]
T[r] = [v / piv for v in T[r]]
for i in range(len(T)):
if i != r and T[i][c] != 0:
f = T[i][c]
Ti, Tr = T[i], T[r]
T[i] = [a - f * b for a, b in zip(Ti, Tr)]
basis[r] = c
def _simplex(T, basis, cost, ncols, tol):
"""Maximize cost^T y over the tableau T (last column is the right side)."""
while True:
enter = None
for j in range(ncols): # Bland's rule: the first improving column
if j in basis:
continue
rc = cost[j] - sum(cost[basis[i]] * T[i][j] for i in range(len(T)))
if rc > tol:
enter = j
break
if enter is None:
return
best, leave = None, None
for i in range(len(T)):
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:
raise Unbounded("the linear program is unbounded")
_pivot(T, basis, leave, enter)
def lp_max(c, rows, b, tol=None):
"""Return (max c^T x, x) subject to rows x <= b, with x free.
Two phase simplex on x = x_plus - x_minus with slack variables.
"""
exact = all(isinstance(v, (int, Fraction)) for v in list(c) + list(b) + [a for r in rows for a in r])
if tol is None:
tol = 0 if exact else 1e-9
conv = Fraction if exact else float
n, mr = len(c), len(rows)
nart = sum(1 for v in b if v < 0)
ncols = 2 * n + mr + nart
T, basis, art = [], [], []
a_idx = 2 * n + mr
for i, (row, bi) in enumerate(zip(rows, b)):
line = [conv(v) for v in row] + [conv(-v) for v in row] + [conv(1 if j == i else 0) for j in range(mr)]
line += [conv(0)] * nart + [conv(bi)]
if bi < 0:
line = [-v for v in line]
line[a_idx] = conv(1)
basis.append(a_idx)
art.append(a_idx)
a_idx += 1
else:
basis.append(2 * n + i)
T.append(line)
if art:
cost1 = [conv(0)] * ncols
for j in art:
cost1[j] = conv(-1)
_simplex(T, basis, cost1, ncols, tol)
if sum(T[i][-1] for i in range(mr) if basis[i] in art) > tol:
raise Infeasible("the linear program is infeasible")
for i in range(mr): # drive the artificial variables out of the basis
if basis[i] in art:
for j in range(2 * n + mr):
if abs(T[i][j]) > tol and j not in basis:
_pivot(T, basis, i, j)
break
for row in T:
for j in art:
row[j] = conv(0)
cost = [conv(v) for v in c] + [conv(-v) for v in c] + [conv(0)] * (mr + nart)
_simplex(T, basis, cost, 2 * n + mr, tol)
y = [conv(0)] * ncols
for i, j in enumerate(basis):
y[j] = T[i][-1]
x = [y[j] - y[n + j] for j in range(n)]
return sum(ci * xi for ci, xi in zip(cost[:n], x)), x
def mpi_set(A, C, F, g, kmax=200, tol=None):
"""Return (rows, bounds, t_star) with O_inf = {x : rows x <= bounds}.
t_star is the first t with O_t = O_(t+1). Only the rows that were not
redundant when they were added are kept, so the description may still
contain rows that later rows made redundant; see remove_redundant.
Raises RuntimeError if no t < kmax works, and Infeasible if O_0 is
empty (possible only if some g_i < 0).
"""
FC = mul(F, C)
rows = [list(r) for r in FC] # @line L1
bounds = list(g)
for t in range(kmax): # @line L2
FCAk = mul(FC, mat_power(A, t + 1)) # @line L3
new = []
for row, gi in zip(FCAk, g): # @line L4
try:
v, _ = lp_max(row, rows, bounds, tol) # @line L5
except Unbounded: # O_t is unbounded in this direction
v = None
slack = 0 if tol is None and isinstance(v, Fraction) else (1e-9 if tol is None else tol)
if v is None or v > gi + slack: # @line L6
new.append((row, gi))
if not new: # @line L7
return rows, bounds, t
for row, gi in new: # @line L8
rows.append(row)
bounds.append(gi)
raise RuntimeError("mpi_set: not finitely determined within kmax steps")
def remove_redundant(rows, bounds, tol=None):
"""Return a description of the same polytope with no redundant row.
A row is redundant if its maximum over the other rows, with its own
bound relaxed by 1, is at most its bound.
"""
rows, bounds = [list(r) for r in rows], list(bounds)
i = 0
while i < len(rows):
others = rows[:i] + rows[i + 1:]
ob = bounds[:i] + bounds[i + 1:]
try:
v, _ = lp_max(rows[i], others + [rows[i]], ob + [bounds[i] + 1], tol)
except Unbounded:
v = None
slack = 0 if v is None or isinstance(v, Fraction) else (1e-9 if tol is None else tol)
if v is not None and v <= bounds[i] + slack:
del rows[i]
del bounds[i]
else:
i += 1
return rows, bounds
test_maximal_positively_invariant_set.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-positively-invariant-set/. The authors are listed in prov/MVMQPG.jsonl.
import itertools
import random
from fractions import Fraction as Fr
import pytest
from ctlmat import mat_power, matvec, mul
from maximal_positively_invariant_set import Infeasible, Unbounded, lp_max, mpi_set, remove_redundant
BOX_F = [[1, 0], [-1, 0], [0, 1], [0, -1]]
BOX_G = [1, 1, 1, 1]
EYE = [[1, 0], [0, 1]]
def rotation(s):
"""s times the rotation with cos = 3/5 and sin = 4/5."""
return [[s * Fr(3, 5), -s * Fr(4, 5)], [s * Fr(4, 5), s * Fr(3, 5)]]
def inside(rows, b, x, tol=0):
return all(sum(a * v for a, v in zip(r, x)) <= bi + tol for r, bi in zip(rows, b))
def vertices(rows, b, tol=0):
out = []
for i, j in itertools.combinations(range(len(rows)), 2):
a1, a2 = rows[i], rows[j]
d = a1[0] * a2[1] - a1[1] * a2[0]
if d == 0 or abs(d) < 1e-12:
continue
x = [(b[i] * a2[1] - b[j] * a1[1]) / d, (a1[0] * b[j] - a2[0] * b[i]) / d]
if inside(rows, b, x, tol) and x not in out:
out.append(x)
return out
def test_lp_against_vertex_enumeration():
rng = random.Random(7)
for _ in range(80):
rows = [[1.0, 0.0], [-1.0, 0.0], [0.0, 1.0], [0.0, -1.0]]
b = [rng.uniform(0.5, 3.0) for _ in range(4)]
for _ in range(rng.randint(0, 5)):
rows.append([rng.uniform(-1, 1), rng.uniform(-1, 1)])
b.append(rng.uniform(-0.3, 1.5))
c = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
verts = vertices(rows, b, 1e-9)
if not verts:
with pytest.raises(Infeasible):
lp_max(c, rows, b)
continue
want = max(c[0] * v[0] + c[1] * v[1] for v in verts)
got, x = lp_max(c, rows, b)
assert abs(got - want) < 1e-7
assert inside(rows, b, x, 1e-7)
def test_lp_exact_and_unbounded():
v, x = lp_max([1, 1], [[1, 2], [3, 1], [-1, 0], [0, -1]], [4, 6, 0, 0])
assert v == Fr(14, 5) and x == [Fr(8, 5), Fr(6, 5)]
with pytest.raises(Unbounded):
lp_max([1, 0], [[0, 1]], [1])
with pytest.raises(Infeasible):
lp_max([1, 0], [[1, 0], [-1, 0]], [-1, -1])
def test_exact_octagon_for_s_nine_tenths():
A = rotation(Fr(9, 10))
rows, b, t = mpi_set(A, EYE, BOX_F, BOX_G)
assert t == 1
r2, b2 = remove_redundant(rows, b)
assert len(r2) == 8
verts = vertices(r2, b2)
want = [(-1, Fr(-14, 27)), (Fr(-23, 36), -1), (Fr(14, 27), -1), (1, Fr(-23, 36)),
(1, Fr(14, 27)), (Fr(23, 36), 1), (Fr(-14, 27), 1), (-1, Fr(23, 36))]
assert sorted(tuple(v) for v in verts) == sorted(want)
for v in verts: # invariance: A v stays in the set, exactly
assert inside(r2, b2, matvec(A, v))
@pytest.mark.parametrize("s, t_star, facets", [(Fr(19, 20), 2, 12), (Fr(99, 100), 4, 20)])
def test_determinedness_index(s, t_star, facets):
rows, b, t = mpi_set(rotation(s), EYE, BOX_F, BOX_G)
assert t == t_star
r2, _ = remove_redundant(rows, b)
assert len(r2) == facets
def test_sampling_invariance_and_maximality():
rng = random.Random(11)
A = rotation(Fr(19, 20))
rows, b, t = mpi_set(A, EYE, BOX_F, BOX_G)
Af = [[float(v) for v in r] for r in A]
rf = [[float(v) for v in r] for r in rows]
bf = [float(v) for v in b]
inner = outer = 0
for _ in range(400):
x = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
if inside(rf, bf, x):
inner += 1
y = x
for _ in range(60): # stays in the box for all k
y = matvec(Af, y)
assert max(abs(v) for v in y) <= 1 + 1e-12
assert inside(rf, bf, y, 1e-12)
else:
outer += 1
y, left = x, False
for _ in range(t + 1): # leaves the box within t* + 1 steps
y = matvec(Af, y)
left = left or max(abs(v) for v in y) > 1
assert left
assert inner > 50 and outer > 50
def test_lqr_terminal_set_double_integrator():
K = [0.4344832432759559, 1.0284659329503845]
AK = [[1.0 - 0.5 * K[0], 1.0 - 0.5 * K[1]], [-K[0], 1.0 - K[1]]]
C = [[1.0, 0.0], [0.0, 1.0], [-K[0], -K[1]]]
F = [[1.0, 0, 0], [-1.0, 0, 0], [0, 1.0, 0], [0, -1.0, 0], [0, 0, 1.0], [0, 0, -1.0]]
rows, b, t = mpi_set(AK, C, F, [5.0] * 4 + [1.0] * 2)
assert t == 1 and len(rows) == 8
r2, b2 = remove_redundant(rows, b)
assert len(r2) == 6
FCA = mul(mul(F, C), mat_power(AK, 1))
assert any(max(abs(u - v) for u, v in zip(r, FCA[4])) < 1e-12 for r in r2)
for v in vertices(r2, b2, 1e-9):
w = matvec(AK, v)
assert inside(r2, b2, w, 1e-9)
def test_single_output_with_unbounded_first_set():
# O_0 = {|x_1| <= 1} is an unbounded strip; observability makes O_1 bounded.
A = [[Fr(1, 2), 1], [0, Fr(1, 2)]]
rows, b, t = mpi_set(A, [[1, 0]], [[1], [-1]], [1, 1])
assert t == 2
r2, b2 = remove_redundant(rows, b)
assert len(r2) == 6
verts = vertices(r2, b2)
want = [(-1, Fr(-1, 2)), (0, -1), (1, Fr(-5, 4)), (1, Fr(1, 2)), (0, 1), (-1, Fr(5, 4))]
assert sorted(tuple(v) for v in verts) == sorted(want)
for v in verts:
assert inside(r2, b2, matvec(A, v))
def test_not_finitely_determined_without_schur():
with pytest.raises(RuntimeError):
mpi_set(rotation(1.0), EYE, [[float(a) for a in r] for r in BOX_F], [1.0] * 4, kmax=15)
History
Gilbert and Tan (1991) defined the maximal output admissible set for linear systems with state and control limits, gave conditions for finite determination, and computed the set with linear programs. Blanchini (1999) surveyed set invariance in control, and the book of Blanchini and Miani covers polyhedral invariant sets and their computation. The book of Borrelli, Bemporad and Morari presents the same iteration as the standard way to compute the terminal set of linear MPC with polyhedral limits.
References
- Elmer G. Gilbert and K. T. Tan, Linear systems with state and control constraints, the theory and application of maximal output admissible sets, IEEE Transactions on Automatic Control 36(9), 1008-1020, 1991, the definition of the maximal output admissible set, the conditions for finite determination, and the algorithm that tests redundancy by linear programming
- Franco Blanchini, Set invariance in control, Automatica 35(11), 1747-1767, 1999, the survey sections on polyhedral invariant sets for linear systems and their computation
- Franco Blanchini and Stefano Miani, Set-Theoretic Methods in Control, 2nd edition, Birkhäuser, 2015, the chapters on invariant sets and on the computation of polyhedral invariant sets
- Francesco Borrelli, Alberto Bemporad and Manfred Morari, Predictive Control for Linear and Hybrid Systems, Cambridge University Press, 2017, the chapter on invariant sets, with the algorithm for the maximal positive invariant set of an autonomous linear system
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MVMQPG Edit this page History Report an error Markdown