Algorithmresearch
Zonotope reachability
Also called Girard's zonotope reachability.
Over-approximates the reachable sets of linear systems by zonotopes, which stay zonotopes under linear maps and Minkowski sums.
- Time
- O(n^3 + N n^2 m + N m log m) worst
- Space
- O(N n m) extra
- Where
- N = the number of time steps; m = the number of generators kept after each step; n = the state dimension
- Model
- Real RAM
- Properties
- deterministicnot exactoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Wolfgang Kühn, Antoine Girard, 2005
Zonotope reachability computes sets that contain every state that a linear system can reach, for all initial states in a set and all inputs with . It is one method for the reachable set computation problem. It cuts the time axis into steps of length , and it returns one zonotope for each interval . A zonotope is the image of a cube under an affine map, . A linear map and a Minkowski sum of zonotopes are again zonotopes, and the program computes them exactly with a matrix product and a list concatenation. The method is due to Girard (2005), and it uses the zonotopes that Kühn (1998) introduced against the wrapping effect of interval arithmetic. The result is sound: it never misses a reachable state. It is not exact.
In plain words
You want to know everywhere a system can go, when you know only roughly where it starts and how strongly it can be pushed. You cannot run every possible case, so you carry a whole set of states through time instead of one state.
The set is a special shape: a box that you can stretch, tilt and add other boxes to. Such shapes stay the same kind of shape when the system moves them, and when you add the push, so each step is cheap and exact. The only losses come from two places. To cover the times between two steps, you blow the first shape up a little. To keep the shapes small enough to store, you sometimes replace some thin parts by a box around them. Both losses make the answer larger, never smaller, so a state outside the answer is truly unreachable.
The problem
The input is a matrix , an initial zonotope , an input bound , a step , a number of steps and a maximum number of generators. The system is with . For with , set and . The output is a list of zonotopes such that every solution satisfies for . All norms are infinity norms: , is the largest absolute row sum, and the ball is the box .
The algorithm
ZONOTOPE-REACH(A, X0 = <c, g_1 .. g_p>, mu, r, N, m)- 1
Phi ← e^(rA) - 2
a ← ‖A‖; s ← max of ‖x‖ over X0; alpha ← (e^(ra) - 1 - ra) s; beta ← (e^(ra) - 1) mu / a - 3
P0 ← <(c + Phi c)/2, (g_j + Phi g_j)/2, (c - Phi c)/2, (g_j - Phi g_j)/2> - 4
Q_0 ← P0 ⊕ B(alpha + beta) - 5
for i ← 0 to N - 2 do - 6
Q_{i+1} ← Phi Q_i ⊕ B(beta) - 7
if Q_{i+1} has more than m generators then Q_{i+1} ← REDUCE(Q_{i+1}, m) - 8
append Q_{i+1} to the output - 9
return Q_0, ..., Q_{N-1}
Line L1 computes the matrix exponential once. At line L2, , and if then . Line L3 builds a zonotope that contains the convex hull of and , the sets at times and . Line L4 adds a box: covers the gap between the true curve and the straight segment from to , and covers the effect of the input over one step. Line L6 moves the set one step forward and adds the input effect of the new step. REDUCE at line L7 sorts the generators by , keeps the largest, and replaces the others by the smallest box around their sum, which is axis-parallel generators. This sort key is the one of Girard (2005); it boxes first the generators that are close to an axis, where the box loses little.
Example
Take , the box with center and radius , and . Then .
| quantity | value |
|---|---|
| 5 | |
| 1.1 | |
| 0.037428 | |
| 0.0028403 | |
| center of | |
| generators of , , | 5, 7, 45 |
| interval hull of | |
| interval hull of | |
| interval hull of , at most 6 generators |
has 2 generators, so has , adds the 2 of the box, and each step adds 2 more. covers the times to . With , the center of moves to at , inside the interval hull of . The reduction to 6 generators makes the interval hull about times wider in each coordinate. The tests of the implementation reproduce these numbers. They also run RK4 solutions with random inputs of size and check, with an exact membership test for zonotopes in the plane, that each solution stays in on every interval.
Correctness
The proof has four parts. (1) A linear map and a Minkowski sum of zonotopes are exact, by the definition. (2) The zonotope of line L3 contains the convex hull of : a point of the hull has coefficients , and in this zonotope, and all of them are in . (3) For , the power series gives , because , and the input adds at most . So contains the states of . (4) A state at time is plus an input term of norm at most , so line L6 keeps the invariant, and REDUCE only adds points. The full proof is in the correctness proof.
Proof: Each zonotope Q_i contains every state reachable in the time interval [i r, (i+1) r]full
Setting. The system is with , and a measurable input with for all . Here is the infinity norm on and the induced norm (the largest absolute row sum) on matrices. is a zonotope. is the box . For a time interval , is the set of all with , over all initial states and inputs. Let , , , and (and if ). These are lines L1 and L2.
Lemma 1 (operations). For zonotopes and and a matrix : and . Also .
Proof. , and a sum of two points of and is with free coefficients in . For the norm, coordinate of a point of is at most in absolute value, and the signs reach this bound.
Lemma 2 (hull, line L3). The zonotope with center and generators , and contains the convex hull of .
Proof. Both sets are convex, so a point of the hull is with , in and . Write
with and . Expanding the right side gives back . Each coefficient is in : , and .
Lemma 3 (first interval, line L4). .
Proof. Take , an input and . By the variation of constants formula, . Compare the first term with the point , which lies on the segment from to , so in by Lemma 2. From the power series,
For , , so . For the second term, gives (and if ). So , as for boxes.
Lemma 4 (one more step, line L6). If , then .
Proof. A state at time with is . Here , and the integral has norm at most , as in Lemma 3.
Lemma 5 (reduction, line L7). Split the generators of into and , and let be the diagonal matrix with . Then .
Proof. with has coordinate at most in absolute value, so it is with .
Theorem. For , the zonotope returned at line L9 contains , with or without the reduction of line L7.
Proof. By induction on . Lemma 3 gives the case , and Lemma 5 keeps it after a reduction. Lemma 4 gives the step from to , and Lemma 5 again keeps it after a reduction, because a superset of a superset is a superset. Lemma 1 shows that the zonotopes built by lines L3, L4 and L6 are exactly the sets in Lemmas 2 to 4.
What is not proved. The theorem gives containment only. The sets are larger than the reach sets by terms of order and by the reduction, and the gap does not go to zero with unless is a contraction. As , and .
Termination and cost. The loop of line L5 runs times. If has generators, has generators and each step adds . A step multiplies each generator by in operations. With the reduction to at most generators, a step costs for the product and for the sort; costs once.
Complexity
The model is the real RAM, with the cost counted in arithmetic operations.
- Line L1 costs for a dense matrix exponential by scaling and squaring.
- Without reduction, has generators, and line L6 costs per generator. steps cost in total when .
- With reduction to generators, a step costs for the product and for the sort. steps cost , and storing all takes numbers.
The cost is polynomial in . This is the main reason to use zonotopes: a grid method such as Hamilton-Jacobi reachability has a cost exponential in , and a polytope in vertex or facet form can need exponentially many vertices or facets to write the same set.
Properties
- Sound. Every contains the true reach set of its time interval. This is a theorem, under the stated bound on the inputs.
- Not exact. The terms and and the reduction make larger than the reach set. is , so a smaller step helps, but more steps mean more reductions.
- Closed operations. Linear maps and Minkowski sums are exact on zonotopes. Intersection with a half-space and the union are not; they need an enclosure.
- Cheap queries. The support function in a direction is , and the interval hull is . Testing whether a point is in a zonotope in dimensions is a linear program; in the plane it is a list of half-plane tests.
- Symmetric. A zonotope is centrally symmetric, so it encloses sets that are not symmetric with some waste.
Variants and improvements
- Wrapping-free form. Girard, Le Guernic and Maler (2006) write , with . The product is exact, and only is reduced, so a reduction error is not multiplied by at later steps.
- Support functions. Le Guernic and Girard (2010) run the same recurrence on support functions in a fixed set of directions. Each direction costs a few matrix products and no set is ever stored in full.
- Other norms. Any norm works if is a ball of the same norm, or a set that contains it. The infinity norm is used here because its ball is a zonotope.
- Hybrid systems. For hybrid automata with linear dynamics, tools intersect the zonotopes with the guards and continue in the next mode. The intersection is not a zonotope, and it is enclosed again; see the survey of Althoff, Frehse and Girard (2021).
- Nonlinear systems. Linearize around the current set and add the Lagrange remainder as an extra input set. The error terms then depend on the size of the set.
When to use it
Use it to verify a linear system with bounded disturbances over a finite horizon in many dimensions, for example that a closed loop never leaves a safe box. It also gives the disturbance tubes of tube MPC. Use Hamilton-Jacobi reachability when the dynamics are strongly nonlinear, the state has very few dimensions and a control and a disturbance play against each other. Use a positively invariant set when you need an infinite horizon.
Pitfalls
- Mixed norms (lines L2 and L4). If and come from , the added ball must be the box. A disk of radius does not contain all the error vectors whose infinity norm is at most .
- Only the sampled times (line L3). The set contains the states at the times only. Without the hull and , a trajectory can leave the computed sets between two samples.
- Input term once (line L4). must be added at every step. Adding it only in ignores the inputs after the first step.
- Too much reduction (line L7). Each reduction adds a box, and turns the box at the next step. The sets can grow even when the system is stable. This is the wrapping effect that zonotopes were introduced to avoid, now back through the reduction. Keep more generators, or use the wrapping-free form.
- Tests by sampling. Random trajectories that stay inside the sets can find a bug, but they do not prove containment. The proof does.
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()
zonotope_reachability.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zonotope-reachability/. The authors are listed in prov/XHB5KP.jsonl.
"""Zonotope reachability for x' = A x + u with ||u(t)||_inf <= mu (Girard 2005).
A zonotope is a pair (c, gens): the center c is a flat list of n floats and
gens is a list of p generators, each a flat list of n floats. It is the set
{c + sum_j a_j g_j : -1 <= a_j <= 1}.
reach(A, z0, mu, r, steps) returns zonotopes Q_0, ..., Q_(steps-1) with the
following guarantee: every solution x(t) that starts in z0 and uses an input
with ||u(t)||_inf <= mu for all t satisfies x(t) in Q_i for i r <= t <= (i+1) r.
The norm is the infinity norm everywhere: ||x|| = max_i |x_i| and ||A|| is
the largest absolute row sum. The ball of radius rho in this norm is the box
(0, rho I).
For a system x' = A x + B w with ||w||_inf <= mu', put u = B w. Then
||u||_inf <= ||B||_inf mu', and the guarantee holds with mu = ||B||_inf mu'.
Cost: Phi = e^(rA) once, O(n^3). Each step multiplies Phi by the p
generators, O(n^2 p), and adds n generators. Without reduction the order
grows by one per step; reduce_order keeps at most m generators, so with
reduction a step costs O(n^2 m + m log m).
"""
import math
from ctlmat import expm, matvec
__all__ = [
"zonotope", "box", "linear_map", "minkowski_sum", "support",
"interval_hull", "sup_norm", "norm_inf", "hull_with_map",
"reduce_order", "reach", "contains_2d", "vertices_2d",
]
def zonotope(center, gens):
"""Return a zonotope with float entries; drop generators that are exactly zero."""
c = [float(v) for v in center]
g = [[float(v) for v in gj] for gj in gens if any(v != 0 for v in gj)]
return (c, g)
def box(n, rho, center=None):
"""The infinity-norm ball of radius rho, as a zonotope with n axis generators."""
c = [0.0] * n if center is None else [float(v) for v in center]
if rho == 0:
return (c, [])
return (c, [[float(rho) if i == j else 0.0 for i in range(n)] for j in range(n)])
def linear_map(m, z):
"""Return M Z = (M c, [M g_j]). This is exact."""
c, gens = z
return (matvec(m, c), [matvec(m, g) for g in gens])
def minkowski_sum(z1, z2):
"""Return Z1 + Z2 = (c1 + c2, gens1 + gens2). This is exact."""
c1, g1 = z1
c2, g2 = z2
return ([a + b for a, b in zip(c1, c2)], g1 + g2)
def support(z, d):
"""Return max over x in Z of d . x, which is d . c + sum_j |d . g_j|."""
c, gens = z
s = sum(di * ci for di, ci in zip(d, c))
for g in gens:
s += abs(sum(di * gi for di, gi in zip(d, g)))
return s
def interval_hull(z):
"""Return (lo, hi), the smallest box that contains Z."""
c, gens = z
rad = [sum(abs(g[i]) for g in gens) for i in range(len(c))]
return [ci - ri for ci, ri in zip(c, rad)], [ci + ri for ci, ri in zip(c, rad)]
def sup_norm(z):
"""Return max over x in Z of ||x||_inf, which is max_i (|c_i| + sum_j |g_j[i]|)."""
c, gens = z
return max(abs(c[i]) + sum(abs(g[i]) for g in gens) for i in range(len(c)))
def norm_inf(a):
"""Return the induced infinity norm of a matrix, the largest absolute row sum."""
return max(sum(abs(v) for v in row) for row in a)
def hull_with_map(z, phi):
"""Return a zonotope that contains the convex hull of Z and Phi Z.
The center is (c + Phi c) / 2, and the generators are (g_j + Phi g_j) / 2,
(c - Phi c) / 2 and (g_j - Phi g_j) / 2 (Girard 2005). It has 2 p + 1
generators for p generators of Z.
"""
c, gens = z
pc = matvec(phi, c)
center = [(a + b) / 2 for a, b in zip(c, pc)]
out = []
pg = [matvec(phi, g) for g in gens]
for g, q in zip(gens, pg):
out.append([(a + b) / 2 for a, b in zip(g, q)])
out.append([(a - b) / 2 for a, b in zip(c, pc)])
for g, q in zip(gens, pg):
out.append([(a - b) / 2 for a, b in zip(g, q)])
return zonotope(center, out)
def reduce_order(z, m):
"""Return a zonotope with at most m generators (m >= n) that contains Z.
The generators are sorted by ||g||_1 - ||g||_inf. The m - n largest are
kept. The others are replaced by their interval hull, which is n axis
generators (Girard 2005 uses this sort key).
"""
c, gens = z
n = len(c)
if m < n:
raise ValueError("reduce_order: m must be at least n")
if len(gens) <= m:
return z
key = sorted(gens, key=lambda g: sum(abs(v) for v in g) - max(abs(v) for v in g))
small = key[: len(gens) - (m - n)]
keep = key[len(gens) - (m - n):]
rad = [sum(abs(g[i]) for g in small) for i in range(n)]
boxed = [[rad[j] if i == j else 0.0 for i in range(n)] for j in range(n)]
return zonotope(c, keep + boxed)
def reach(a, z0, mu, r, steps, max_gens=None):
"""Return [Q_0, ..., Q_(steps-1)] with Reach([i r, (i+1) r]) inside Q_i.
a: the n by n matrix A. z0: the initial zonotope. mu: the bound on
||u||_inf. r: the time step. max_gens: if given, Q_i is reduced to at most
max_gens generators after each step.
"""
n = len(a)
phi = expm([[r * v for v in row] for row in a]) # @line L1
na = norm_inf(a)
s = sup_norm(z0)
if na == 0: # @line L2
alpha, beta = 0.0, r * mu
else:
alpha = (math.exp(r * na) - 1 - r * na) * s
beta = (math.exp(r * na) - 1) * mu / na
p0 = hull_with_map(z0, phi) # @line L3
q = minkowski_sum(p0, box(n, alpha + beta)) # @line L4
if max_gens is not None:
q = reduce_order(q, max_gens)
out = [q]
for _ in range(steps - 1): # @line L5
q = minkowski_sum(linear_map(phi, q), box(n, beta)) # @line L6
if max_gens is not None: # @line L7
q = reduce_order(q, max_gens)
out.append(q) # @line L8
return out # @line L9
def contains_2d(z, x, tol=1e-9):
"""Exact membership test for a zonotope in the plane.
In two dimensions every edge of Z is parallel to a generator, so Z is the
set of points x with |d . (x - c)| <= sum_j |d . g_j| for each normal
d = (-g_2, g_1) of a generator g. Points within tol (relative) count as
inside.
"""
c, gens = z
if len(c) != 2:
raise ValueError("contains_2d: the zonotope must be in the plane")
if not gens:
return abs(x[0] - c[0]) <= tol and abs(x[1] - c[1]) <= tol
dx = [x[0] - c[0], x[1] - c[1]]
normals = [[-g[1], g[0]] for g in gens]
rank_one = all(abs(nm[0] * gens[0][0] + nm[1] * gens[0][1]) <= 1e-15 * (1 + abs(nm[0]) + abs(nm[1])) for nm in normals)
if rank_one:
# All generators are parallel: Z is a segment, so also test the extent along it.
normals.append(list(gens[0]))
for d in normals:
width = sum(abs(d[0] * g[0] + d[1] * g[1]) for g in gens)
if abs(d[0] * dx[0] + d[1] * dx[1]) > width + tol * (1 + width):
return False
return True
def vertices_2d(z):
"""Return the vertices of a zonotope in the plane, in counterclockwise order."""
c, gens = z
if not gens:
return [list(c)]
gs = []
for g in gens:
if g[1] < 0 or (g[1] == 0 and g[0] < 0):
g = [-g[0], -g[1]]
gs.append(g)
gs.sort(key=lambda g: math.atan2(g[1], g[0]))
start = [c[0] - sum(g[0] for g in gs), c[1] - sum(g[1] for g in gs)]
pts = [start]
p = start
for g in gs + [[-v for v in g] for g in gs]:
p = [p[0] + 2 * g[0], p[1] + 2 * g[1]]
pts.append(p)
return pts[:-1]
test_zonotope_reachability.py 222 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zonotope-reachability/. The authors are listed in prov/XHB5KP.jsonl.
import itertools
import math
import random
from ctlmat import expm, matvec
from zonotope_reachability import (
box,
contains_2d,
hull_with_map,
interval_hull,
linear_map,
minkowski_sum,
norm_inf,
reach,
reduce_order,
support,
sup_norm,
vertices_2d,
zonotope,
)
# The example of the page.
A = [[-1.0, -4.0], [4.0, -1.0]]
Z0 = box(2, 0.1, [1.0, 0.0])
MU = 0.05
R = 0.05
def corner_points(z):
"""All points c + sum s_j g_j with s_j = +1 or -1. Z is their convex hull."""
c, gens = z
pts = []
for signs in itertools.product((-1.0, 1.0), repeat=len(gens)):
pts.append([c[i] + sum(s * g[i] for s, g in zip(signs, gens)) for i in range(len(c))])
return pts
def random_zonotope(rng, n, p):
return zonotope([rng.uniform(-1, 1) for _ in range(n)], [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)])
def unit_directions(k):
return [[math.cos(2 * math.pi * i / k), math.sin(2 * math.pi * i / k)] for i in range(k)]
def test_example_numbers():
phi = expm([[R * v for v in row] for row in A])
assert abs(phi[0][0] - math.exp(-R) * math.cos(4 * R)) < 1e-14
assert abs(phi[1][0] - math.exp(-R) * math.sin(4 * R)) < 1e-14
assert norm_inf(A) == 5.0
assert abs(sup_norm(Z0) - 1.1) < 1e-15
qs = reach(A, Z0, MU, R, 20)
assert [len(q[1]) for q in qs] == [7 + 2 * i for i in range(20)]
lo, hi = interval_hull(qs[0])
assert abs(lo[0] - 0.773102) < 1e-6 and abs(hi[0] - 1.159166) < 1e-6
assert abs(lo[1] + 0.159166) < 1e-6 and abs(hi[1] - 0.348146) < 1e-6
lo, hi = interval_hull(qs[19])
assert abs(lo[0] + 0.430991) < 1e-6 and abs(hi[0] + 0.115371) < 1e-6
def test_support_function_matches_corners():
rng = random.Random(1)
for _ in range(50):
n = rng.randint(1, 3)
z = random_zonotope(rng, n, rng.randint(0, 5))
pts = corner_points(z)
for _ in range(5):
d = [rng.uniform(-1, 1) for _ in range(n)]
best = max(sum(a * b for a, b in zip(d, p)) for p in pts)
assert abs(support(z, d) - best) < 1e-12
def test_linear_map_and_sum_are_exact():
rng = random.Random(2)
for _ in range(50):
z1 = random_zonotope(rng, 2, 3)
z2 = random_zonotope(rng, 2, 2)
m = [[rng.uniform(-2, 2) for _ in range(2)] for _ in range(2)]
mz = linear_map(m, z1)
s = minkowski_sum(z1, z2)
for d in unit_directions(24):
mtd = [m[0][0] * d[0] + m[1][0] * d[1], m[0][1] * d[0] + m[1][1] * d[1]]
assert abs(support(mz, d) - support(z1, mtd)) < 1e-12
assert abs(support(s, d) - support(z1, d) - support(z2, d)) < 1e-12
def test_contains_2d_is_exact_on_vertices():
rng = random.Random(3)
for _ in range(40):
z = random_zonotope(rng, 2, rng.randint(1, 5))
for v in vertices_2d(z):
assert contains_2d(z, v)
c = z[0]
for v in vertices_2d(z):
out = [c[0] + 1.001 * (v[0] - c[0]), c[1] + 1.001 * (v[1] - c[1])]
assert not contains_2d(z, out, tol=1e-12)
def test_hull_contains_convex_hull():
rng = random.Random(4)
for _ in range(30):
z = random_zonotope(rng, 2, rng.randint(1, 3))
phi = [[rng.uniform(-1.5, 1.5) for _ in range(2)] for _ in range(2)]
h = hull_with_map(z, phi)
pz = linear_map(phi, z)
for p in corner_points(z) + corner_points(pz):
assert contains_2d(h, p)
for _ in range(20):
lam = rng.random()
p = rng.choice(corner_points(z))
q = rng.choice(corner_points(pz))
assert contains_2d(h, [lam * a + (1 - lam) * b for a, b in zip(p, q)])
def test_reduction_contains_original():
rng = random.Random(5)
for _ in range(30):
z = random_zonotope(rng, 2, rng.randint(3, 8))
red = reduce_order(z, 3)
assert len(red[1]) <= 3
# Z is the convex hull of its corner points, and the reduced zonotope is
# convex, so this proves containment.
for p in corner_points(z):
assert contains_2d(red, p)
def test_reduction_contains_original_in_3d_by_support():
rng = random.Random(6)
for _ in range(20):
z = random_zonotope(rng, 3, 9)
red = reduce_order(z, 4)
assert len(red[1]) <= 4
for _ in range(50):
d = [rng.gauss(0, 1) for _ in range(3)]
assert support(red, d) >= support(z, d) - 1e-12
def simulate_inside(a, z0, mu, r, steps, qs, rng, sub=10, trials=40, check=contains_2d):
"""RK4 runs with random piecewise constant inputs; x(t) must lie in Q_i for t in [i r, (i+1) r]."""
n = len(a)
h = r / sub
def f(x, u):
return [sum(a[i][j] * x[j] for j in range(n)) + u[i] for i in range(n)]
c, gens = z0
for _ in range(trials):
coef = [rng.choice((-1.0, 1.0)) if rng.random() < 0.5 else rng.uniform(-1, 1) for _ in gens]
x = [c[i] + sum(s * g[i] for s, g in zip(coef, gens)) for i in range(n)]
for i in range(steps):
for k in range(sub):
assert check(qs[i], x), (i, k, x)
u = [mu * rng.choice((-1.0, 1.0)) for _ in range(n)]
k1 = f(x, u)
k2 = f([xi + h / 2 * v for xi, v in zip(x, k1)], u)
k3 = f([xi + h / 2 * v for xi, v in zip(x, k2)], u)
k4 = f([xi + h * v for xi, v in zip(x, k3)], u)
x = [xi + h / 6 * (p + 2 * q + 2 * s + t) for xi, p, q, s, t in zip(x, k1, k2, k3, k4)]
assert check(qs[i], x)
def test_trajectories_stay_inside_example():
rng = random.Random(7)
qs = reach(A, Z0, MU, R, 20)
simulate_inside(A, Z0, MU, R, 20, qs, rng)
def test_trajectories_stay_inside_with_reduction():
rng = random.Random(8)
qs = reach(A, Z0, MU, R, 20, max_gens=6)
assert all(len(q[1]) <= 6 for q in qs)
simulate_inside(A, Z0, MU, R, 20, qs, rng)
def test_trajectories_unstable_and_zero_matrix():
rng = random.Random(9)
a = [[0.5, 1.0], [0.0, 0.3]]
z0 = zonotope([0.0, 1.0], [[0.2, 0.1], [0.0, 0.05]])
qs = reach(a, z0, 0.1, 0.1, 15, max_gens=8)
simulate_inside(a, z0, 0.1, 0.1, 15, qs, rng, trials=20)
zero = [[0.0, 0.0], [0.0, 0.0]]
qs = reach(zero, z0, 0.2, 0.1, 5)
simulate_inside(zero, z0, 0.2, 0.1, 5, qs, rng, trials=10)
def test_trajectories_3d_by_support():
"""In 3D the test only checks support directions: a necessary condition."""
rng = random.Random(10)
a = [[-0.5, 2.0, 0.0], [-2.0, -0.5, 0.0], [0.0, 0.0, -1.0]]
z0 = box(3, 0.05, [1.0, 0.0, 1.0])
qs = reach(a, z0, 0.02, 0.05, 10, max_gens=9)
dirs = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(30)]
def check(q, x):
return all(sum(di * xi for di, xi in zip(d, x)) <= support(q, d) + 1e-9 for d in dirs)
simulate_inside(a, z0, 0.02, 0.05, 10, qs, rng, trials=10, check=check)
def test_no_input_contains_exact_flow():
"""With mu = 0, the exact image e^(tA) Z0 at sample times lies in the reach set."""
qs = reach(A, Z0, 0.0, R, 20)
for i in range(20):
for frac in (0.0, 0.3, 0.7, 1.0):
e = expm([[(i + frac) * R * v for v in row] for row in A])
for p in corner_points(Z0):
assert contains_2d(qs[i], matvec(e, p))
def test_smaller_step_is_tighter():
"""Halving r shrinks the first set; the extra width of Q_0 is about alpha, which is O(r^2)."""
widths = []
for r in (0.04, 0.02, 0.01):
q0 = reach(A, Z0, 0.0, r, 1)[0]
lo, hi = interval_hull(q0)
hull = hull_with_map(Z0, expm([[r * v for v in row] for row in A]))
hlo, hhi = interval_hull(hull)
widths.append((hi[0] - lo[0]) - (hhi[0] - hlo[0]))
assert widths[1] < 0.3 * widths[0] and widths[2] < 0.3 * widths[1]
History
Interval methods for ordinary differential equations lose accuracy because each step wraps a rotated box in a larger box. Kühn (1998) used zonotopes to keep the enclosures tight in validated computations of orbits. Girard (2005) applied them to the reach sets of linear systems with uncertain inputs and gave the bounds and and the order reduction used here. Girard, Le Guernic and Maler (2006) removed the wrapping effect of the reduction, and Le Guernic and Girard (2010) moved the recurrence to support functions. Althoff, Frehse and Girard (2021) survey these and other set representations for reachability.
References
- A. Girard, Reachability of uncertain linear systems using zonotopes, Hybrid Systems: Computation and Control (HSCC 2005), LNCS 3414, Springer, 2005, pages 291 to 305, the algorithm for the reach sets over time intervals, the bounds alpha_r and beta_r, and the reduction of the order
- W. Kühn, Rigorously computed orbits of dynamical systems without the wrapping effect, Computing 61(1), 1998, pages 47 to 67, zonotopes as enclosures that do not suffer from the wrapping effect of boxes
- A. Girard, C. Le Guernic and O. Maler, Efficient computation of reachable sets of linear time-invariant systems with inputs, HSCC 2006, LNCS 3927, Springer, 2006, pages 257 to 271, the wrapping-free form of the recurrence
- C. Le Guernic and A. Girard, Reachability analysis of linear systems using support functions, Nonlinear Analysis: Hybrid Systems 4(2), 2010, pages 250 to 262, the same recurrence with support functions instead of zonotopes
- M. Althoff, G. Frehse and A. Girard, Set propagation techniques for reachability analysis, Annual Review of Control, Robotics, and Autonomous Systems 4, 2021, pages 369 to 395, the survey of set representations, zonotopes among them
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 XHB5KP Edit this page History Report an error Markdown