Algorithm Search⌘K

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
Properties
deterministicnot exactoffline
Origin
Wolfgang Kühn, Antoine Girard, 2005

Zonotope reachability computes sets that contain every state that a linear system x′=Ax+ux' = Ax + u can reach, for all initial states in a set X0X_0 and all inputs with ∥u(t)∥∞≤μ\|u(t)\|_\infty \le \mu. It is one method for the reachable set computation problem. It cuts the time axis into steps of length rr, and it returns one zonotope QiQ_i for each interval [ir,(i+1)r][ir, (i+1)r]. A zonotope is the image of a cube under an affine map, ⟨c,g1,…,gp⟩={c+∑jajgj:∣aj∣≤1}\langle c, g_1, \ldots, g_p \rangle = \{c + \sum_j a_j g_j : |a_j| \le 1\}. 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 A∈Rn×nA \in \mathbb{R}^{n \times n}, an initial zonotope X0=⟨c,g1,…,gp⟩X_0 = \langle c, g_1, \ldots, g_p \rangle, an input bound μ≥0\mu \ge 0, a step r>0r > 0, a number of steps NN and a maximum number m≥nm \ge n of generators. The system is x′=Ax+ux' = Ax + u with ∥u(t)∥∞≤μ\|u(t)\|_\infty \le \mu. For x′=Ax+Bwx' = Ax + Bw with ∥w∥∞≤μ′\|w\|_\infty \le \mu', set u=Bwu = Bw and μ=∥B∥∞μ′\mu = \|B\|_\infty \mu'. The output is a list of zonotopes Q0,…,QN−1Q_0, \ldots, Q_{N-1} such that every solution satisfies x(t)∈Qix(t) \in Q_i for ir≤t≤(i+1)rir \le t \le (i+1)r. All norms are infinity norms: ∥x∥=max⁡i∣xi∣\|x\| = \max_i |x_i|, ∥A∥\|A\| is the largest absolute row sum, and the ball B(ρ)B(\rho) is the box ⟨0,ρe1,…,ρen⟩\langle 0, \rho e_1, \ldots, \rho e_n \rangle.

The algorithm

  1. ZONOTOPE-REACH(A, X0 = <c, g_1 .. g_p>, mu, r, N, m)
  2. 1Phi ← e^(rA)
  3. 2a ← ‖A‖; s ← max of ‖x‖ over X0; alpha ← (e^(ra) - 1 - ra) s; beta ← (e^(ra) - 1) mu / a
  4. 3P0 ← <(c + Phi c)/2, (g_j + Phi g_j)/2, (c - Phi c)/2, (g_j - Phi g_j)/2>
  5. 4Q_0 ← P0 ⊕ B(alpha + beta)
  6. 5for i ← 0 to N - 2 do
  7. 6Q_{i+1} ← Phi Q_i ⊕ B(beta)
  8. 7if Q_{i+1} has more than m generators then Q_{i+1} ← REDUCE(Q_{i+1}, m)
  9. 8append Q_{i+1} to the output
  10. 9return Q_0, ..., Q_{N-1}

Line L1 computes the matrix exponential once. At line L2, s=max⁡i(∣ci∣+∑j∣gj,i∣)s = \max_i (|c_i| + \sum_j |g_{j,i}|), and if a=0a = 0 then β=rμ\beta = r\mu. Line L3 builds a zonotope that contains the convex hull of X0X_0 and ΦX0\Phi X_0, the sets at times 00 and rr. Line L4 adds a box: α\alpha covers the gap between the true curve etAx0e^{tA}x_0 and the straight segment from x0x_0 to Φx0\Phi x_0, and β\beta 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 ∥g∥1−∥g∥∞\|g\|_1 - \|g\|_\infty, keeps the m−nm - n largest, and replaces the others by the smallest box around their sum, which is nn 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 A=(−1−44−1)A = \begin{pmatrix} -1 & -4 \\ 4 & -1 \end{pmatrix}, the box X0X_0 with center (1,0)(1, 0) and radius 0.10.1, μ=0.05\mu = 0.05 and r=0.05r = 0.05. Then Φ=e−0.05(cos⁡0.2−sin⁡0.2sin⁡0.2cos⁡0.2)=(0.93227−0.188980.188980.93227)\Phi = e^{-0.05} \begin{pmatrix} \cos 0.2 & -\sin 0.2 \\ \sin 0.2 & \cos 0.2 \end{pmatrix} = \begin{pmatrix} 0.93227 & -0.18898 \\ 0.18898 & 0.93227 \end{pmatrix}.

quantity value
a=∥A∥∞a = \|A\|_\infty 5
s=max⁡X0∥x∥∞s = \max_{X_0} \|x\|_\infty 1.1
α=(e0.25−1.25)⋅1.1\alpha = (e^{0.25} - 1.25) \cdot 1.1 0.037428
β=(e0.25−1)⋅0.05/5\beta = (e^{0.25} - 1) \cdot 0.05 / 5 0.0028403
center of P0P_0 (0.96613,0.09449)(0.96613, 0.09449)
generators of P0P_0, Q0Q_0, Q19Q_{19} 5, 7, 45
interval hull of Q0Q_0 [0.7731,1.1592]×[−0.1592,0.3481][0.7731, 1.1592] \times [-0.1592, 0.3481]
interval hull of Q19Q_{19} [−0.4310,−0.1154]×[−0.4035,−0.1115][-0.4310, -0.1154] \times [-0.4035, -0.1115]
interval hull of Q19Q_{19}, at most 6 generators [−0.5427,−0.0037]×[−0.5149,−0.0002][-0.5427, -0.0037] \times [-0.5149, -0.0002]

X0X_0 has 2 generators, so P0P_0 has 2⋅2+1=52 \cdot 2 + 1 = 5, Q0Q_0 adds the 2 of the box, and each step adds 2 more. Q19Q_{19} covers the times 0.950.95 to 11. With u=0u = 0, the center of X0X_0 moves to eA(1,0)=(−0.2405,−0.2784)e^{A}(1, 0) = (-0.2405, -0.2784) at t=1t = 1, inside the interval hull of Q19Q_{19}. The reduction to 6 generators makes the interval hull about 1.71.7 times wider in each coordinate. The tests of the implementation reproduce these numbers. They also run RK4 solutions with random inputs of size μ\mu and check, with an exact membership test for zonotopes in the plane, that each solution stays in QiQ_i 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 X0∪ΦX0X_0 \cup \Phi X_0: a point λz+(1−λ)Φz′\lambda z + (1 - \lambda)\Phi z' of the hull has coefficients 2λ−12\lambda - 1, λaj+(1−λ)bj\lambda a_j + (1 - \lambda) b_j and λaj−(1−λ)bj\lambda a_j - (1 - \lambda) b_j in this zonotope, and all of them are in [−1,1][-1, 1]. (3) For t∈[0,r]t \in [0, r], the power series gives ∥etAx0−x0−tr(Φ−I)x0∥≤(era−1−ra)∥x0∥≤α\|e^{tA}x_0 - x_0 - \frac{t}{r}(\Phi - I)x_0\| \le (e^{ra} - 1 - ra)\|x_0\| \le \alpha, because ∣tk−trk−1∣≤rk|t^k - t r^{k-1}| \le r^k, and the input adds at most ∫0reσaμ dσ=β\int_0^r e^{\sigma a} \mu \, d\sigma = \beta. So Q0Q_0 contains the states of [0,r][0, r]. (4) A state at time t+rt + r is Φx(t)\Phi x(t) plus an input term of norm at most β\beta, 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 x′(t)=Ax(t)+u(t)x'(t) = A x(t) + u(t) with x(t)∈Rnx(t) \in \mathbb{R}^n, x(0)∈X0x(0) \in X_0 and a measurable input with ∥u(t)∥∞≤μ\|u(t)\|_\infty \le \mu for all tt. Here ∥⋅∥\|\cdot\| is the infinity norm on Rn\mathbb{R}^n and the induced norm (the largest absolute row sum) on matrices. X0=⟨c,g1,…,gp⟩={c+∑jajgj:∣aj∣≤1}X_0 = \langle c, g_1, \ldots, g_p \rangle = \{c + \sum_j a_j g_j : |a_j| \le 1\} is a zonotope. B(ρ)={x:∥x∥≤ρ}B(\rho) = \{x : \|x\| \le \rho\} is the box ⟨0,ρe1,…,ρen⟩\langle 0, \rho e_1, \ldots, \rho e_n \rangle. For a time interval II, R(I)\mathcal{R}(I) is the set of all x(t)x(t) with t∈It \in I, over all initial states and inputs. Let Φ=erA\Phi = e^{rA}, a=∥A∥a = \|A\|, s=max⁡x∈X0∥x∥s = \max_{x \in X_0} \|x\|, α=(era−1−ra)s\alpha = (e^{ra} - 1 - ra) s and β=(era−1)μ/a\beta = (e^{ra} - 1)\mu / a (and β=rμ\beta = r\mu if a=0a = 0). These are lines L1 and L2.

Lemma 1 (operations). For zonotopes Z=⟨c,g1,…,gp⟩Z = \langle c, g_1, \ldots, g_p \rangle and Z′=⟨c′,h1,…,hq⟩Z' = \langle c', h_1, \ldots, h_q \rangle and a matrix MM: MZ=⟨Mc,Mg1,…,Mgp⟩MZ = \langle Mc, Mg_1, \ldots, Mg_p \rangle and Z⊕Z′=⟨c+c′,g1,…,gp,h1,…,hq⟩Z \oplus Z' = \langle c + c', g_1, \ldots, g_p, h_1, \ldots, h_q \rangle. Also max⁡x∈Z∥x∥=max⁡i(∣ci∣+∑j∣gj,i∣)\max_{x \in Z} \|x\| = \max_i (|c_i| + \sum_j |g_{j,i}|).

Proof. M(c+∑ajgj)=Mc+∑ajMgjM(c + \sum a_j g_j) = Mc + \sum a_j M g_j, and a sum of two points of ZZ and Z′Z' is c+c′+∑ajgj+∑bkhkc + c' + \sum a_j g_j + \sum b_k h_k with free coefficients in [−1,1][-1, 1]. For the norm, coordinate ii of a point of ZZ is at most ∣ci∣+∑j∣gj,i∣|c_i| + \sum_j |g_{j,i}| in absolute value, and the signs aj=sign⁡(ci)sign⁡(gj,i)a_j = \operatorname{sign}(c_i) \operatorname{sign}(g_{j,i}) reach this bound. ■\blacksquare

Lemma 2 (hull, line L3). The zonotope P0P_0 with center (c+Φc)/2(c + \Phi c)/2 and generators (gj+Φgj)/2(g_j + \Phi g_j)/2, (c−Φc)/2(c - \Phi c)/2 and (gj−Φgj)/2(g_j - \Phi g_j)/2 contains the convex hull of X0∪ΦX0X_0 \cup \Phi X_0.

Proof. Both sets are convex, so a point of the hull is y=λz+(1−λ)Φz′y = \lambda z + (1 - \lambda) \Phi z' with z=c+∑ajgjz = c + \sum a_j g_j, z′=c+∑bjgjz' = c + \sum b_j g_j in X0X_0 and λ∈[0,1]\lambda \in [0, 1]. Write

y=c+Φc2+(2λ−1)c−Φc2+∑j(ξjgj+Φgj2+ηjgj−Φgj2)y = \frac{c + \Phi c}{2} + (2\lambda - 1)\frac{c - \Phi c}{2} + \sum_j \left( \xi_j \frac{g_j + \Phi g_j}{2} + \eta_j \frac{g_j - \Phi g_j}{2} \right)

with ξj=λaj+(1−λ)bj\xi_j = \lambda a_j + (1 - \lambda) b_j and ηj=λaj−(1−λ)bj\eta_j = \lambda a_j - (1 - \lambda) b_j. Expanding the right side gives back λc+(1−λ)Φc+∑j(λajgj+(1−λ)bjΦgj)=y\lambda c + (1 - \lambda)\Phi c + \sum_j (\lambda a_j g_j + (1 - \lambda) b_j \Phi g_j) = y. Each coefficient is in [−1,1][-1, 1]: ∣2λ−1∣≤1|2\lambda - 1| \le 1, and ∣ξj∣,∣ηj∣≤λ∣aj∣+(1−λ)∣bj∣≤1|\xi_j|, |\eta_j| \le \lambda |a_j| + (1 - \lambda)|b_j| \le 1. ■\blacksquare

Lemma 3 (first interval, line L4). R([0,r])⊆Q0=P0⊕B(α+β)\mathcal{R}([0, r]) \subseteq Q_0 = P_0 \oplus B(\alpha + \beta).

Proof. Take x0∈X0x_0 \in X_0, an input uu and t∈[0,r]t \in [0, r]. By the variation of constants formula, x(t)=etAx0+∫0te(t−τ)Au(τ) dτx(t) = e^{tA} x_0 + \int_0^t e^{(t - \tau)A} u(\tau)\, d\tau. Compare the first term with the point y=x0+tr(Φx0−x0)y = x_0 + \frac{t}{r}(\Phi x_0 - x_0), which lies on the segment from x0x_0 to Φx0\Phi x_0, so in P0P_0 by Lemma 2. From the power series,

etAx0−y=∑k≥2tk−trk−1k!Akx0.e^{tA} x_0 - y = \sum_{k \ge 2} \frac{t^k - t r^{k-1}}{k!} A^k x_0.

For 0≤t≤r0 \le t \le r, 0≤trk−1−tk≤rk0 \le t r^{k-1} - t^k \le r^k, so ∥etAx0−y∥≤∑k≥2rkakk!∥x0∥=(era−1−ra)∥x0∥≤α\|e^{tA} x_0 - y\| \le \sum_{k \ge 2} \frac{r^k a^k}{k!} \|x_0\| = (e^{ra} - 1 - ra)\|x_0\| \le \alpha. For the second term, ∥eσA∥≤eσa\|e^{\sigma A}\| \le e^{\sigma a} gives ∥∫0te(t−τ)Au(τ) dτ∥≤μ∫0teσa dσ=μ(eta−1)/a≤β\left\|\int_0^t e^{(t - \tau)A} u(\tau)\, d\tau\right\| \le \mu \int_0^t e^{\sigma a}\, d\sigma = \mu (e^{ta} - 1)/a \le \beta (and ≤rμ\le r\mu if a=0a = 0). So x(t)=y+(etAx0−y)+∫…∈P0⊕B(α)⊕B(β)=P0⊕B(α+β)x(t) = y + (e^{tA}x_0 - y) + \int \ldots \in P_0 \oplus B(\alpha) \oplus B(\beta) = P_0 \oplus B(\alpha + \beta), as B(α)⊕B(β)=B(α+β)B(\alpha) \oplus B(\beta) = B(\alpha + \beta) for boxes. ■\blacksquare

Lemma 4 (one more step, line L6). If R([ir,(i+1)r])⊆Qi\mathcal{R}([ir, (i+1)r]) \subseteq Q_i, then R([(i+1)r,(i+2)r])⊆ΦQi⊕B(β)\mathcal{R}([(i+1)r, (i+2)r]) \subseteq \Phi Q_i \oplus B(\beta).

Proof. A state at time t+rt + r with t∈[ir,(i+1)r]t \in [ir, (i+1)r] is x(t+r)=Φx(t)+∫tt+re(t+r−τ)Au(τ) dτx(t + r) = \Phi x(t) + \int_t^{t + r} e^{(t + r - \tau)A} u(\tau)\, d\tau. Here x(t)∈Qix(t) \in Q_i, and the integral has norm at most β\beta, as in Lemma 3. ■\blacksquare

Lemma 5 (reduction, line L7). Split the generators of Z=⟨c,G⟩Z = \langle c, G \rangle into KK and LL, and let DD be the diagonal matrix with Dii=∑h∈L∣hi∣D_{ii} = \sum_{h \in L} |h_i|. Then Z⊆⟨c,K,De1,…,Den⟩Z \subseteq \langle c, K, D e_1, \ldots, D e_n \rangle.

Proof. ∑h∈Lbhh\sum_{h \in L} b_h h with ∣bh∣≤1|b_h| \le 1 has coordinate ii at most DiiD_{ii} in absolute value, so it is ∑idiDiiei\sum_i d_i D_{ii} e_i with ∣di∣≤1|d_i| \le 1. ■\blacksquare

Theorem. For i=0,…,N−1i = 0, \ldots, N - 1, the zonotope QiQ_i returned at line L9 contains R([ir,(i+1)r])\mathcal{R}([ir, (i+1)r]), with or without the reduction of line L7.

Proof. By induction on ii. Lemma 3 gives the case i=0i = 0, and Lemma 5 keeps it after a reduction. Lemma 4 gives the step from ii to i+1i + 1, 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. ■\blacksquare

What is not proved. The theorem gives containment only. The sets QiQ_i are larger than the reach sets by terms of order α\alpha and by the reduction, and the gap does not go to zero with ii unless Φ\Phi is a contraction. As r→0r \to 0, α=O(r2)\alpha = O(r^2) and β=rμ+O(r2)\beta = r\mu + O(r^2).

Termination and cost. The loop of line L5 runs N−1N - 1 times. If X0X_0 has pp generators, Q0Q_0 has 2p+1+n2p + 1 + n generators and each step adds nn. A step multiplies each generator by Φ\Phi in O(n2)O(n^2) operations. With the reduction to at most mm generators, a step costs O(n2m)O(n^2 m) for the product and O(mlog⁡m)O(m \log m) for the sort; Φ\Phi costs O(n3)O(n^3) once. ■\blacksquare

Complexity

The model is the real RAM, with the cost counted in arithmetic operations.

  • Line L1 costs O(n3)O(n^3) for a dense matrix exponential by scaling and squaring.
  • Without reduction, QiQ_i has 2p+1+n(i+1)2p + 1 + n(i + 1) generators, and line L6 costs O(n2)O(n^2) per generator. NN steps cost O(N2n3)O(N^2 n^3) in total when p≤np \le n.
  • With reduction to mm generators, a step costs O(n2m)O(n^2 m) for the product and O(mlog⁡m)O(m \log m) for the sort. NN steps cost O(n3+Nn2m+Nmlog⁡m)O(n^3 + N n^2 m + N m \log m), and storing all QiQ_i takes O(Nnm)O(N n m) numbers.

The cost is polynomial in nn. This is the main reason to use zonotopes: a grid method such as Hamilton-Jacobi reachability has a cost exponential in nn, and a polytope in vertex or facet form can need exponentially many vertices or facets to write the same set.

Properties

  • Sound. Every QiQ_i contains the true reach set of its time interval. This is a theorem, under the stated bound on the inputs.
  • Not exact. The terms α\alpha and β\beta and the reduction make QiQ_i larger than the reach set. α\alpha is O(r2)O(r^2), 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 dd is d⋅c+∑j∣d⋅gj∣d \cdot c + \sum_j |d \cdot g_j|, and the interval hull is c±∑j∣gj∣c \pm \sum_j |g_j|. Testing whether a point is in a zonotope in nn 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 Qi=ΦiQ0⊕SiQ_i = \Phi^i Q_0 \oplus S_i, with Si+1=Si⊕ΦiB(β)S_{i+1} = S_i \oplus \Phi^i B(\beta). The product ΦiQ0\Phi^i Q_0 is exact, and only SiS_i is reduced, so a reduction error is not multiplied by Φ\Phi 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 B(ρ)B(\rho) 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 α\alpha and β\beta come from ∥A∥∞\|A\|_\infty, the added ball must be the box. A disk of radius α+β\alpha + \beta does not contain all the error vectors whose infinity norm is at most α+β\alpha + \beta.
  • Only the sampled times (line L3). The set ΦiX0\Phi^i X_0 contains the states at the times irir only. Without the hull and α\alpha, a trajectory can leave the computed sets between two samples.
  • Input term once (line L4). β\beta must be added at every step. Adding it only in Q0Q_0 ignores the inputs after the first step.
  • Too much reduction (line L7). Each reduction adds a box, and Φ\Phi 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.

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()
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 αr\alpha_r and βr\beta_r 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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • 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