Algorithm Search⌘K

Algorithmadvanced

Maximal positively invariant set computation

Also called Gilbert-Tan algorithm, MPI set algorithm.

Computes the largest positively invariant set of x_(k+1) = A x_k inside polyhedral output limits by adding the limits of step t + 1 until a linear program shows they are redundant.

Time
O(t (n^3 + c n^2 + c L)) worst
Space
O(c t n) extra
Where
L = the cost of one linear program in n variables with at most c (t + 1) rows; c = the number of rows of the output limits F y <= g; n = the number of states; t = the index at which the algorithm stops, the determinedness index
Properties
deterministicexactofflineiterative
Origin
Elmer G. Gilbert, K. T. Tan, 1991

The maximal positively invariant set of the linear system xk+1=Axkx_{k+1} = A x_k under the output limits yk=Cxk∈Yy_k = C x_k \in \mathbb{Y} is the set of all initial states whose whole trajectory meets the limits:

O∞={x:CAkx∈Y for all k≥0}.O_\infty = \{x : C A^k x \in \mathbb{Y} \text{ for all } k \ge 0\}.

It is the largest positively invariant set inside {x:Cx∈Y}\{x : C x \in \mathbb{Y}\}. Gilbert and Tan (1991) called it the maximal output admissible set. For a polyhedron Y={y:Fy≤g}\mathbb{Y} = \{y : F y \le g\}, the algorithm of this page adds the limits of steps 1,2,…1, 2, \dots one block at a time and checks with one linear program per row whether the new limits cut anything off. It stops at the first tt at which nothing is cut, and then O∞=OtO_\infty = O_t is a polyhedron with a finite description. Gilbert and Tan proved that such a tt exists when AA is Schur, (C,A)(C, A) is observable, and Y\mathbb{Y} is bounded with 0 in its interior. In MPC the set is the usual terminal set of linear MPC: AA is the closed loop A−BKA - B K of the LQR gain, and CC stacks the state limits and the input −Kx-K x.

In plain words

A system moves by itself under a fixed rule, and its outputs must stay inside some limits. Some starting points are safe forever. Others are inside the limits now but leave them later. This method finds all the safe starting points. It first keeps the points that meet the limits now. Then it adds the condition for one step later, then two steps later, and so on. After each new step it asks whether the new condition removes any point that is still in the set. When a new step removes nothing, every later step also removes nothing, so the set is final. Each check is a small optimization problem with a linear goal and linear limits.

The problem

Input: A∈Rn×nA \in \mathbb{R}^{n \times n}, C∈Rp×nC \in \mathbb{R}^{p \times n}, and the output limits Fy≤gF y \le g with F∈Rc×pF \in \mathbb{R}^{c \times p} and g∈Rcg \in \mathbb{R}^c. Output: an index t∗t^* and a finite list of inequalities Hx≤hH x \le h whose solution set is O∞O_\infty, with

Ot={x:FCAkx≤g for k=0,…,t},O∞=⋂t≥0Ot.O_t = \{x : F C A^k x \le g \text{ for } k = 0, \dots, t\}, \qquad O_\infty = \bigcap_{t \ge 0} O_t.

The sets shrink: O0⊇O1⊇…O_0 \supseteq O_1 \supseteq \dots. The set O∞O_\infty is finitely determined if O∞=OtO_\infty = O_t for some finite tt; the smallest such tt is the determinedness index t∗t^*. The algorithm can only return a finite description, so it needs finite determination. For an MPC terminal set with the gain KK, take AK=A−BKA_K = A - B K in place of AA, the stacked output C=[I−K]C = \begin{bmatrix} I \\ -K \end{bmatrix} and the limits on states and inputs as Fy≤gF y \le g.

The algorithm

  1. MPI(A, C, F, g)
  2. 1(rows, bounds) ← (F C, g) ▷ O_0 = {x : F C x ≤ g}
  3. 2for t = 0, 1, 2, ...
  4. 3R ← F C A^(t+1) ▷ the limits of step t + 1
  5. 4for each row r_i of R, with bound g_i
  6. 5v_i ← max r_i x subject to rows · x ≤ bounds ▷ one LP; v_i = ∞ if unbounded
  7. 6if v_i > g_i then mark row i as new
  8. 7if no row is new then return (rows, bounds, t) ▷ O_t = O_(t+1) = O_∞
  9. 8append the new rows to rows and bounds ▷ the stored set is O_(t+1)

Line L5 asks how far the set OtO_t reaches in the direction of the new row. If the answer is at most gig_i, the row holds on all of OtO_t and it is redundant. Only the rows that cut OtO_t are stored, so the stored description is shorter than the full list of c(t+1)c (t + 1) rows, and it still describes Ot+1O_{t+1}, because the dropped rows hold on it. The implementation solves each LP with a two-phase simplex method with Bland's rule, in exact rational arithmetic for rational data. It stops with an error after a set number of passes, because without the hypotheses of finite determination the loop need not end. A last pass that removes redundant rows among the stored ones gives the facets of O∞O_\infty.

Example

A damped rotation. Let A=s[3/5−4/54/53/5]A = s \begin{bmatrix} 3/5 & -4/5 \\ 4/5 & 3/5 \end{bmatrix}, a rotation by θ=arccos⁡(3/5)≈53.13°\theta = \arccos(3/5) \approx 53.13° scaled by ss, with C=IC = I and the box ∣x1∣≤1|x_1| \le 1, ∣x2∣≤1|x_2| \le 1 (c=4c = 4 rows). For s=9/10s = 9/10:

  • Line L1 stores the 4 rows of the box.
  • Pass t=0t = 0: the rows of AA are (27/50,−18/25)(27/50, -18/25), (18/25,27/50)(18/25, 27/50) and their negatives. Each LP over the box gives v=63/50>1v = 63/50 > 1, so all 4 rows are new.
  • Pass t=1t = 1: the rows of A2A^2 are (−567/2500,−486/625)(-567/2500, -486/625), (486/625,−567/2500)(486/625, -567/2500) and their negatives. Each LP over the 8 rows gives v=369/400<1v = 369/400 < 1. Nothing is new, so t∗=1t^* = 1.

O∞O_\infty is the octagon with the vertices

(1,1427), (2336,1), (−1427,1), (−1,2336), (−1,−1427), (−2336,−1), (1427,−1), (1,−2336).(1, \tfrac{14}{27}),\ (\tfrac{23}{36}, 1),\ (-\tfrac{14}{27}, 1),\ (-1, \tfrac{23}{36}),\ (-1, -\tfrac{14}{27}),\ (-\tfrac{23}{36}, -1),\ (\tfrac{14}{27}, -1),\ (1, -\tfrac{23}{36}).

The vertex (1,14/27)(1, 14/27) lies on x1=1x_1 = 1 and on the new row 1825x1+2750x2=1\tfrac{18}{25} x_1 + \tfrac{27}{50} x_2 = 1: 0.72+0.28=10.72 + 0.28 = 1. The tests check exactly, in fractions, that AA maps each vertex into the octagon.

Slower decay needs more passes (measurement with the implementation):

ss t∗t^* facets of O∞O_\infty
9/10 1 8
19/20 2 12
99/100 4 20

For s=1s = 1 the loop never stops. The rotation keeps the length of xx, and θ\theta is not a rational multiple of π\pi (by Niven's theorem, the only rational values of cos⁡\cos at rational multiples of π\pi are 00, ±1/2\pm 1/2 and ±1\pm 1). So every orbit on a circle of radius rr is dense on that circle, and O∞O_\infty is the closed unit disc. A disc is not a polyhedron, so no finite tt works.

An unbounded first set. Let A=[1/2101/2]A = \begin{bmatrix} 1/2 & 1 \\ 0 & 1/2 \end{bmatrix}, C=[10]C = \begin{bmatrix} 1 & 0 \end{bmatrix} and ∣y∣≤1|y| \le 1. O0O_0 is the strip ∣x1∣≤1|x_1| \le 1, so the LP of pass 0 is unbounded and the row of step 1 is new. Because (C,A)(C, A) is observable, O1O_1 is bounded. The algorithm returns t∗=2t^* = 2, and O∞O_\infty is the hexagon with the vertices (1,1/2)(1, 1/2), (0,1)(0, 1), (−1,5/4)(-1, 5/4), (−1,−1/2)(-1, -1/2), (0,−1)(0, -1) and (1,−5/4)(1, -5/4).

The terminal set of the linear MPC example. For the double integrator A=[1101]A = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}, B=[0.51]B = \begin{bmatrix} 0.5 \\ 1 \end{bmatrix} with the LQR gain K=(0.434483,1.028466)K = (0.434483, 1.028466) of Q=IQ = I, R=1R = 1, take AK=A−BKA_K = A - B K, the limits ∣xi∣≤5|x_i| \le 5 and ∣Kx∣≤1|K x| \le 1 (c=6c = 6). The algorithm stops at t∗=1t^* = 1 with 8 stored rows, and the redundancy pass leaves 6 facets:

∣x1∣≤5,∣0.434483 x1+1.028466 x2∣≤1,∣0.106756 x1−0.181781 x2∣≤1.|x_1| \le 5, \qquad |0.434483\, x_1 + 1.028466\, x_2| \le 1, \qquad |0.106756\, x_1 - 0.181781\, x_2| \le 1.

The last pair is the input limit one step ahead, ∣KAKx∣≤1|K A_K x| \le 1. This is the terminal set used on the linear MPC page.

Correctness

The proofs are in proofs/correctness.md.

  1. O∞O_\infty is the maximal positively invariant set in O0O_0. If x∈O∞x \in O_\infty, every limit of AxA x is a limit of xx one step later, so Ax∈O∞A x \in O_\infty. If S⊆O0S \subseteq O_0 is positively invariant, every trajectory from SS stays in S⊆O0S \subseteq O_0, so S⊆O∞S \subseteq O_\infty.
  2. The stopping test is correct. The sets satisfy Ot+1={x∈O0:Ax∈Ot}O_{t+1} = \{x \in O_0 : A x \in O_t\}. If Ot+1=OtO_{t+1} = O_t, then Ot+2={x∈O0:Ax∈Ot+1}=Ot+1O_{t+2} = \{x \in O_0 : A x \in O_{t+1}\} = O_{t+1}, and by induction all later sets are equal, so Ot=O∞O_t = O_\infty. The LP of line L5 decides Ot+1=OtO_{t+1} = O_t row by row: the rows of step t+1t + 1 hold on all of OtO_t exactly when each maximum is at most its bound. An unbounded LP means the row cuts OtO_t.
  3. The loop ends under the hypotheses (theorem, Gilbert and Tan 1991). Suppose AA is Schur, (C,A)(C, A) is observable, Y\mathbb{Y} is bounded and contains a ball of radius ρ>0\rho > 0 around 0. Observability and boundedness make On−1O_{n-1} bounded, say ∣x∣≤β|x| \le \beta. Since Ak→0A^k \to 0, there is k0k_0 with ∥CAk∥β≤ρ\|C A^k\| \beta \le \rho for k≥k0k \ge k_0, so all limits of later steps hold automatically on On−1O_{n-1}. Hence t∗≤max⁡(n−1,k0)t^* \le \max(n - 1, k_0).
  4. The LP answers are exact. The simplex method with Bland's rule does not cycle and stops with an optimum, an unbounded ray, or an infeasibility proof. With rational data the arithmetic is exact, so the comparison of line L6 has no rounding error.

The hypotheses of point 3 are sufficient, not necessary. The unbounded-strip example above has 00 in the interior of Y\mathbb{Y} but an unbounded O0O_0, and observability still bounds O1O_1.

Proof: The stopping test O_t = O_(t+1) gives the maximal positively invariant set, and the test is reached under stability, observability and a bounded constraint setfull

The system is xk+1=Axkx_{k+1} = A x_k with output yk=Cxky_k = C x_k, A∈Rn×nA \in \mathbb{R}^{n \times n}, C∈Rp×nC \in \mathbb{R}^{p \times n}. The constraint set is Y={y:Fy≤g}Y = \{y : F y \le g\}. For t≥0t \ge 0 let

Ot={x:FCAkx≤g for k=0,1,…,t},O∞=⋂t≥0Ot.O_t = \{x : F C A^k x \le g \text{ for } k = 0, 1, \dots, t\}, \qquad O_\infty = \bigcap_{t \ge 0} O_t.

So O∞O_\infty is the set of initial states whose output stays in YY for all time. The sets are nested: O0⊇O1⊇⋯⊇O∞O_0 \supseteq O_1 \supseteq \dots \supseteq O_\infty.

Part 1: O∞O_\infty is the maximal positively invariant set in O0O_0

Lemma 1. O∞O_\infty is positively invariant (AO∞⊆O∞A O_\infty \subseteq O_\infty), it lies in O0O_0, and every positively invariant set S⊆O0S \subseteq O_0 lies in O∞O_\infty.

Proof. If x∈O∞x \in O_\infty then FCAk(Ax)=FCAk+1x≤gF C A^k (A x) = F C A^{k+1} x \le g for all k≥0k \ge 0, so Ax∈O∞A x \in O_\infty. O∞⊆O0O_\infty \subseteq O_0 by definition. If S⊆O0S \subseteq O_0 is positively invariant and x∈Sx \in S, then Akx∈S⊆O0A^k x \in S \subseteq O_0 for every kk, that is, FCAkx≤gF C A^k x \le g for all kk, so x∈O∞x \in O_\infty. □\square

Part 2: the stopping test

Lemma 2. Ot+1={x∈O0:Ax∈Ot}O_{t+1} = \{x \in O_0 : A x \in O_t\}.

Proof. Ax∈OtA x \in O_t means FCAkAx≤gF C A^{k} A x \le g for k=0,…,tk = 0, \dots, t, that is, the conditions k=1,…,t+1k = 1, \dots, t + 1 on xx. Together with x∈O0x \in O_0 these are the conditions of Ot+1O_{t+1}. □\square

Lemma 3. If Ot=Ot+1O_t = O_{t+1}, then Ot=O∞O_t = O_\infty.

Proof. Let x∈Otx \in O_t. Then x∈Ot+1x \in O_{t+1}, so Ax∈OtA x \in O_t by Lemma 2. So OtO_t is positively invariant, and Ot⊆O0O_t \subseteq O_0. By Lemma 1, Ot⊆O∞O_t \subseteq O_\infty. The other inclusion holds because the sets are nested. □\square

So once the test succeeds, every later set is the same, and the algorithm may stop.

Lemma 4 (the LP test, lines L4 to L6). Let Rtx≤ctR_t x \le c_t be any description of OtO_t. Then Ot+1=OtO_{t+1} = O_t if and only if, for each row ii of FF,

max⁡{(FCAt+1)i x:Rtx≤ct}≤gi,\max\{ (F C A^{t+1})_i \, x : R_t x \le c_t \} \le g_i,

where an unbounded maximum counts as a failure.

Proof. Ot+1=Ot∩{x:FCAt+1x≤g}O_{t+1} = O_t \cap \{x : F C A^{t+1} x \le g\}. This equals OtO_t if and only if every x∈Otx \in O_t satisfies each new row, which is the condition on the maximum. □\square

Lemma 5 (the stored description). At the start of iteration tt of line L2, the stored rows describe OtO_t.

Proof. Line L1 stores FCF C, the rows of O0O_0. In iteration tt, line L8 adds the rows of FCAt+1F C A^{t+1} whose maximum over the stored set is larger than the bound. A row whose maximum is at most its bound holds at every point of OtO_t, so adding it would not change the set. So the stored rows after the iteration describe Ot∩{FCAt+1x≤g}=Ot+1O_t \cap \{F C A^{t+1} x \le g\} = O_{t+1}. □\square

Theorem 1 (correctness). If the algorithm returns at line L7 with index t∗t^*, the returned rows describe Ot∗=O∞O_{t^*} = O_\infty, the maximal positively invariant subset of O0O_0, and t∗t^* is the smallest tt with Ot=Ot+1O_t = O_{t+1}.

Proof. Line L7 returns when no row of step t+1t + 1 is new, that is, when Ot=Ot+1O_t = O_{t+1} by Lemmas 4 and 5. Lemma 3 and Lemma 1 give the rest. The loop tries t=0,1,…t = 0, 1, \dots in order, so the first success is the smallest such tt. □\square

Part 3: finite determination

The loop is guaranteed to reach the test only under extra hypotheses. Without them it can run forever: for a rotation AA by an angle that is not a rational multiple of π\pi and a box YY, the sets OtO_t keep gaining facets.

Theorem 2. Suppose AA is Schur (all eigenvalues in the open unit disc), (C,A)(C, A) is observable, YY is bounded, and YY contains a ball {y:∣y∣≤ρ}\{y : |y| \le \rho\} with ρ>0\rho > 0. Then Ot=Ot+1O_t = O_{t+1} for some tt, so the algorithm stops.

Proof. Step 1: On−1O_{n-1} is bounded. Since YY is bounded there is cc with ∣y∣≤c|y| \le c for y∈Yy \in Y. The observability matrix O=(C;CA;… ;CAn−1)\mathcal{O} = (C; C A; \dots; C A^{n-1}) has full column rank, so OTO\mathcal{O}^T \mathcal{O} is invertible and ∣x∣≤∥(OTO)−1OT∥ ∣Ox∣|x| \le \|(\mathcal{O}^T \mathcal{O})^{-1} \mathcal{O}^T\| \, |\mathcal{O} x|. For x∈On−1x \in O_{n-1} each block CAkxC A^k x lies in YY, so ∣Ox∣≤n c|\mathcal{O} x| \le \sqrt{n} \, c. Hence ∣x∣≤β|x| \le \beta on On−1O_{n-1} for some β\beta.

Step 2: late constraints are automatic. Since AA is Schur, Ak→0A^k \to 0, so there is k0k_0 with ∥CAk∥β≤ρ\|C A^k\| \beta \le \rho for all k≥k0k \ge k_0. For x∈On−1x \in O_{n-1} and k≥k0k \ge k_0, ∣CAkx∣≤ρ|C A^k x| \le \rho, so CAkx∈YC A^k x \in Y.

Step 3: let t=max⁡(n−1,k0)t = \max(n - 1, k_0). For x∈Ot⊆On−1x \in O_t \subseteq O_{n-1} the condition of step t+1≥k0t + 1 \ge k_0 holds by Step 2. So Ot+1=OtO_{t+1} = O_t. □\square

The bound t∗≤max⁡(n−1,k0)t^* \le \max(n - 1, k_0) from the proof depends on how fast ∥CAk∥\|C A^k\| decays, so the bound grows without limit as the spectral radius of AA tends to 1. The index t∗t^* itself need not grow: for A=sIA = s I with ∣s∣<1|s| < 1 and a box symmetric about 0, t∗=0t^* = 0. This is why the iteration count is part of the output and not a constant.

Part 4: the linear programs

Each LP of line L5 has the form maximize cTxc^T x subject to Rx≤bR x \le b with xx free. The routine writes x=x+−x−x = x^+ - x^- with x±≥0x^\pm \ge 0 and adds a slack per row. Rows with bi<0b_i < 0 get an artificial variable, and phase one maximizes minus the sum of the artificials; a positive optimal sum means no feasible point. Phase two runs the simplex method on the original cost. Both phases use Bland's rule (the first improving column enters, ties in the ratio test are broken by the smallest basic index), which prevents cycling, so each phase stops after finitely many pivots. A column with an improving reduced cost and no positive entry is a ray along which the objective grows without bound, which is the unbounded report. These are the standard correctness facts of the simplex method; see the simplex method page. With integer and rational data the code uses exact rational arithmetic, so the tests v>giv > g_i of line L6 have no rounding error.

Complexity

Costs are in the real-RAM model.

  • One pass. Line L3 costs O(cn2)O(c n^2) if FCAtF C A^{t} is kept and multiplied by AA once per pass (the implementation recomputes the power, which adds O(n3log⁡t)O(n^3 \log t)). Lines L4 to L6 solve cc linear programs in nn variables with at most c(t+1)c (t + 1) rows.
  • All passes. t∗+1t^* + 1 passes give O(t∗(n3+cn2+cL))O(t^* (n^3 + c n^2 + c L)), with LL the cost of one LP. With the simplex method, LL has no polynomial bound in the worst case. An interior point method is polynomial in the bit model, in the size of the LP and the bit length of the data; in the real-RAM model no strongly polynomial LP algorithm is known.
  • The index t∗t^*. It is not bounded by a function of nn and cc alone. The bound max⁡(n−1,k0)\max(n - 1, k_0) grows as the spectral radius of AA tends to 1, and the table above shows the growth (measurement).
  • Space. The stored rows number at most c(t∗+1)c (t^* + 1), each of length nn.

Properties

  • Exact output. In exact arithmetic the returned inequalities describe O∞O_\infty exactly. It is a polyhedron, and a polytope when it is bounded.
  • Convex and symmetric. O∞O_\infty is convex because it is an intersection of half-spaces. If Y\mathbb{Y} is symmetric about 0, so is O∞O_\infty.
  • Contains a neighborhood of 0. If AA is Schur and 0 is in the interior of Y\mathbb{Y}, then O∞O_\infty contains a ball around 0, because ∣CAkx∣≤sup⁡k∥CAk∥ ∣x∣|C A^k x| \le \sup_k \|C A^k\| \, |x| and the supremum is finite.
  • Monotone in the limits. Larger limits give a larger set.
  • Redundant rows. The stored list can contain rows that are redundant at the end. One LP per row removes them.

Variants and improvements

  • Systems with inputs and a fixed gain. The terminal set of MPC: apply the algorithm to A−BKA - B K with the stacked output above.
  • Constant references. For a reference governor, the state is augmented with a constant reference. The matrix then has an eigenvalue 1, the set is in general not finitely determined, and the limits are tightened by a small margin on the steady-state part to restore finite determination. See reference governor.
  • Maximal control invariant set. With a free input, iterate Ωt+1={x∈Ωt:∃u, Ax+Bu∈Ωt, u∈U}\Omega_{t+1} = \{x \in \Omega_t : \exists u, \ A x + B u \in \Omega_t, \ u \in \mathbb{U}\}. Each step needs a projection, for example by Fourier-Motzkin elimination, which is much more expensive. See control-invariant set.
  • Disturbances. For x+=Ax+wx^+ = A x + w with ww in a polytope, tighten each limit of step kk by the support function of CAjwC A^j w summed over j<kj < k. The result is the maximal robust positively invariant set. Robust methods such as tube MPC use sets of this kind.
  • Ellipsoidal sets. A level set {x:xTPx≤γ}\{x : x^T P x \le \gamma\} of a Lyapunov function, with γ\gamma chosen so that it fits inside the limits, is positively invariant and simpler, but in general smaller than O∞O_\infty.

When to use it

Use it to compute the terminal set of linear MPC, to check that a fixed linear controller keeps a constraint for all time from a given state, or to build the admissible sets of a reference governor. It suits small nn and moderate t∗t^*, where the number of LPs is small. For a large nn, or a spectral radius close to 1, the number of rows can grow large; then use an ellipsoidal set or a simpler terminal constraint.

Pitfalls

  • No finite determination. If AA is not Schur, or (C,A)(C, A) is not observable, the loop may not end. Set a pass limit and report failure, as the implementation does. The rotation with s=1s = 1 shows the case.
  • Rounding. In floating point a row whose maximum is very close to its bound can be judged wrongly. Use a tolerance, and check the result by testing AvA v for each vertex vv in two or three dimensions. Rational arithmetic avoids the problem for rational data.
  • Unbounded LPs. When Y\mathbb{Y} does not bound all states, O0O_0 is unbounded, and the LP of line L5 can be unbounded. Treat that answer as "the row is new", not as an error.
  • Not the terminal set by itself. For MPC stability the terminal set must also go with a terminal cost that is a Lyapunov function for A−BKA - B K. The set alone does not give a decreasing cost. See MPC stability theorem.
  • The input limit. For an MPC terminal set, include ∣Kx∣≤umax⁡|K x| \le u_{\max} in the output. Without it, the set does not ensure that u=−Kxu = -K x meets the input limits.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

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()
maximal_positively_invariant_set.py 180 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-positively-invariant-set/. The authors are listed in prov/MVMQPG.jsonl.

"""Maximal positively invariant (maximal output admissible) set of x+ = A x.

The system is x_(k+1) = A x_k with the output y_k = C x_k, which must stay in
the polytope Y = {y : F y <= g} for all k >= 0. The maximal output admissible
set is

    O_inf = {x : F C A^k x <= g for all k >= 0},

the largest positively invariant set inside {x : F C x <= g}. Write O_t for
the set with the constraints k = 0, ..., t only. The algorithm of Gilbert and
Tan (1991) adds the constraints of step t + 1 one block at a time and stops
at the first t with O_t = O_(t+1); then O_t = O_inf. The test O_t = O_(t+1)
is one linear program per row of F: the row of step t + 1 is redundant if
its maximum over O_t is at most its bound.

If A is Schur, (C, A) is observable, and Y is bounded with 0 in its
interior, such a t exists (O_inf is finitely determined).

The linear programs use a dense two phase simplex method with Bland's rule.
With int and Fraction data the arithmetic is exact (tol = 0). With float
data a tolerance is used.
"""

from fractions import Fraction

from ctlmat import mat_power, mul

__all__ = ["lp_max", "mpi_set", "remove_redundant", "Unbounded", "Infeasible"]


class Unbounded(Exception):
    """The linear program is unbounded."""


class Infeasible(Exception):
    """The linear program has no feasible point."""


def _pivot(T, basis, r, c):
    piv = T[r][c]
    T[r] = [v / piv for v in T[r]]
    for i in range(len(T)):
        if i != r and T[i][c] != 0:
            f = T[i][c]
            Ti, Tr = T[i], T[r]
            T[i] = [a - f * b for a, b in zip(Ti, Tr)]
    basis[r] = c


def _simplex(T, basis, cost, ncols, tol):
    """Maximize cost^T y over the tableau T (last column is the right side)."""
    while True:
        enter = None
        for j in range(ncols):  # Bland's rule: the first improving column
            if j in basis:
                continue
            rc = cost[j] - sum(cost[basis[i]] * T[i][j] for i in range(len(T)))
            if rc > tol:
                enter = j
                break
        if enter is None:
            return
        best, leave = None, None
        for i in range(len(T)):
            if T[i][enter] > tol:
                ratio = T[i][-1] / T[i][enter]
                if best is None or ratio < best - tol or (abs(ratio - best) <= tol and basis[i] < basis[leave]):
                    best, leave = ratio, i
        if leave is None:
            raise Unbounded("the linear program is unbounded")
        _pivot(T, basis, leave, enter)


def lp_max(c, rows, b, tol=None):
    """Return (max c^T x, x) subject to rows x <= b, with x free.

    Two phase simplex on x = x_plus - x_minus with slack variables.
    """
    exact = all(isinstance(v, (int, Fraction)) for v in list(c) + list(b) + [a for r in rows for a in r])
    if tol is None:
        tol = 0 if exact else 1e-9
    conv = Fraction if exact else float
    n, mr = len(c), len(rows)
    nart = sum(1 for v in b if v < 0)
    ncols = 2 * n + mr + nart
    T, basis, art = [], [], []
    a_idx = 2 * n + mr
    for i, (row, bi) in enumerate(zip(rows, b)):
        line = [conv(v) for v in row] + [conv(-v) for v in row] + [conv(1 if j == i else 0) for j in range(mr)]
        line += [conv(0)] * nart + [conv(bi)]
        if bi < 0:
            line = [-v for v in line]
            line[a_idx] = conv(1)
            basis.append(a_idx)
            art.append(a_idx)
            a_idx += 1
        else:
            basis.append(2 * n + i)
        T.append(line)
    if art:
        cost1 = [conv(0)] * ncols
        for j in art:
            cost1[j] = conv(-1)
        _simplex(T, basis, cost1, ncols, tol)
        if sum(T[i][-1] for i in range(mr) if basis[i] in art) > tol:
            raise Infeasible("the linear program is infeasible")
        for i in range(mr):  # drive the artificial variables out of the basis
            if basis[i] in art:
                for j in range(2 * n + mr):
                    if abs(T[i][j]) > tol and j not in basis:
                        _pivot(T, basis, i, j)
                        break
        for row in T:
            for j in art:
                row[j] = conv(0)
    cost = [conv(v) for v in c] + [conv(-v) for v in c] + [conv(0)] * (mr + nart)
    _simplex(T, basis, cost, 2 * n + mr, tol)
    y = [conv(0)] * ncols
    for i, j in enumerate(basis):
        y[j] = T[i][-1]
    x = [y[j] - y[n + j] for j in range(n)]
    return sum(ci * xi for ci, xi in zip(cost[:n], x)), x


def mpi_set(A, C, F, g, kmax=200, tol=None):
    """Return (rows, bounds, t_star) with O_inf = {x : rows x <= bounds}.

    t_star is the first t with O_t = O_(t+1). Only the rows that were not
    redundant when they were added are kept, so the description may still
    contain rows that later rows made redundant; see remove_redundant.
    Raises RuntimeError if no t < kmax works, and Infeasible if O_0 is
    empty (possible only if some g_i < 0).
    """
    FC = mul(F, C)
    rows = [list(r) for r in FC]  # @line L1
    bounds = list(g)
    for t in range(kmax):  # @line L2
        FCAk = mul(FC, mat_power(A, t + 1))  # @line L3
        new = []
        for row, gi in zip(FCAk, g):  # @line L4
            try:
                v, _ = lp_max(row, rows, bounds, tol)  # @line L5
            except Unbounded:  # O_t is unbounded in this direction
                v = None
            slack = 0 if tol is None and isinstance(v, Fraction) else (1e-9 if tol is None else tol)
            if v is None or v > gi + slack:  # @line L6
                new.append((row, gi))
        if not new:  # @line L7
            return rows, bounds, t
        for row, gi in new:  # @line L8
            rows.append(row)
            bounds.append(gi)
    raise RuntimeError("mpi_set: not finitely determined within kmax steps")


def remove_redundant(rows, bounds, tol=None):
    """Return a description of the same polytope with no redundant row.

    A row is redundant if its maximum over the other rows, with its own
    bound relaxed by 1, is at most its bound.
    """
    rows, bounds = [list(r) for r in rows], list(bounds)
    i = 0
    while i < len(rows):
        others = rows[:i] + rows[i + 1:]
        ob = bounds[:i] + bounds[i + 1:]
        try:
            v, _ = lp_max(rows[i], others + [rows[i]], ob + [bounds[i] + 1], tol)
        except Unbounded:
            v = None
        slack = 0 if v is None or isinstance(v, Fraction) else (1e-9 if tol is None else tol)
        if v is not None and v <= bounds[i] + slack:
            del rows[i]
            del bounds[i]
        else:
            i += 1
    return rows, bounds
test_maximal_positively_invariant_set.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-positively-invariant-set/. The authors are listed in prov/MVMQPG.jsonl.

import itertools
import random
from fractions import Fraction as Fr

import pytest

from ctlmat import mat_power, matvec, mul
from maximal_positively_invariant_set import Infeasible, Unbounded, lp_max, mpi_set, remove_redundant

BOX_F = [[1, 0], [-1, 0], [0, 1], [0, -1]]
BOX_G = [1, 1, 1, 1]
EYE = [[1, 0], [0, 1]]


def rotation(s):
    """s times the rotation with cos = 3/5 and sin = 4/5."""
    return [[s * Fr(3, 5), -s * Fr(4, 5)], [s * Fr(4, 5), s * Fr(3, 5)]]


def inside(rows, b, x, tol=0):
    return all(sum(a * v for a, v in zip(r, x)) <= bi + tol for r, bi in zip(rows, b))


def vertices(rows, b, tol=0):
    out = []
    for i, j in itertools.combinations(range(len(rows)), 2):
        a1, a2 = rows[i], rows[j]
        d = a1[0] * a2[1] - a1[1] * a2[0]
        if d == 0 or abs(d) < 1e-12:
            continue
        x = [(b[i] * a2[1] - b[j] * a1[1]) / d, (a1[0] * b[j] - a2[0] * b[i]) / d]
        if inside(rows, b, x, tol) and x not in out:
            out.append(x)
    return out


def test_lp_against_vertex_enumeration():
    rng = random.Random(7)
    for _ in range(80):
        rows = [[1.0, 0.0], [-1.0, 0.0], [0.0, 1.0], [0.0, -1.0]]
        b = [rng.uniform(0.5, 3.0) for _ in range(4)]
        for _ in range(rng.randint(0, 5)):
            rows.append([rng.uniform(-1, 1), rng.uniform(-1, 1)])
            b.append(rng.uniform(-0.3, 1.5))
        c = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        verts = vertices(rows, b, 1e-9)
        if not verts:
            with pytest.raises(Infeasible):
                lp_max(c, rows, b)
            continue
        want = max(c[0] * v[0] + c[1] * v[1] for v in verts)
        got, x = lp_max(c, rows, b)
        assert abs(got - want) < 1e-7
        assert inside(rows, b, x, 1e-7)


def test_lp_exact_and_unbounded():
    v, x = lp_max([1, 1], [[1, 2], [3, 1], [-1, 0], [0, -1]], [4, 6, 0, 0])
    assert v == Fr(14, 5) and x == [Fr(8, 5), Fr(6, 5)]
    with pytest.raises(Unbounded):
        lp_max([1, 0], [[0, 1]], [1])
    with pytest.raises(Infeasible):
        lp_max([1, 0], [[1, 0], [-1, 0]], [-1, -1])


def test_exact_octagon_for_s_nine_tenths():
    A = rotation(Fr(9, 10))
    rows, b, t = mpi_set(A, EYE, BOX_F, BOX_G)
    assert t == 1
    r2, b2 = remove_redundant(rows, b)
    assert len(r2) == 8
    verts = vertices(r2, b2)
    want = [(-1, Fr(-14, 27)), (Fr(-23, 36), -1), (Fr(14, 27), -1), (1, Fr(-23, 36)),
            (1, Fr(14, 27)), (Fr(23, 36), 1), (Fr(-14, 27), 1), (-1, Fr(23, 36))]
    assert sorted(tuple(v) for v in verts) == sorted(want)
    for v in verts:  # invariance: A v stays in the set, exactly
        assert inside(r2, b2, matvec(A, v))


@pytest.mark.parametrize("s, t_star, facets", [(Fr(19, 20), 2, 12), (Fr(99, 100), 4, 20)])
def test_determinedness_index(s, t_star, facets):
    rows, b, t = mpi_set(rotation(s), EYE, BOX_F, BOX_G)
    assert t == t_star
    r2, _ = remove_redundant(rows, b)
    assert len(r2) == facets


def test_sampling_invariance_and_maximality():
    rng = random.Random(11)
    A = rotation(Fr(19, 20))
    rows, b, t = mpi_set(A, EYE, BOX_F, BOX_G)
    Af = [[float(v) for v in r] for r in A]
    rf = [[float(v) for v in r] for r in rows]
    bf = [float(v) for v in b]
    inner = outer = 0
    for _ in range(400):
        x = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        if inside(rf, bf, x):
            inner += 1
            y = x
            for _ in range(60):  # stays in the box for all k
                y = matvec(Af, y)
                assert max(abs(v) for v in y) <= 1 + 1e-12
                assert inside(rf, bf, y, 1e-12)
        else:
            outer += 1
            y, left = x, False
            for _ in range(t + 1):  # leaves the box within t* + 1 steps
                y = matvec(Af, y)
                left = left or max(abs(v) for v in y) > 1
            assert left
    assert inner > 50 and outer > 50


def test_lqr_terminal_set_double_integrator():
    K = [0.4344832432759559, 1.0284659329503845]
    AK = [[1.0 - 0.5 * K[0], 1.0 - 0.5 * K[1]], [-K[0], 1.0 - K[1]]]
    C = [[1.0, 0.0], [0.0, 1.0], [-K[0], -K[1]]]
    F = [[1.0, 0, 0], [-1.0, 0, 0], [0, 1.0, 0], [0, -1.0, 0], [0, 0, 1.0], [0, 0, -1.0]]
    rows, b, t = mpi_set(AK, C, F, [5.0] * 4 + [1.0] * 2)
    assert t == 1 and len(rows) == 8
    r2, b2 = remove_redundant(rows, b)
    assert len(r2) == 6
    FCA = mul(mul(F, C), mat_power(AK, 1))
    assert any(max(abs(u - v) for u, v in zip(r, FCA[4])) < 1e-12 for r in r2)
    for v in vertices(r2, b2, 1e-9):
        w = matvec(AK, v)
        assert inside(r2, b2, w, 1e-9)


def test_single_output_with_unbounded_first_set():
    # O_0 = {|x_1| <= 1} is an unbounded strip; observability makes O_1 bounded.
    A = [[Fr(1, 2), 1], [0, Fr(1, 2)]]
    rows, b, t = mpi_set(A, [[1, 0]], [[1], [-1]], [1, 1])
    assert t == 2
    r2, b2 = remove_redundant(rows, b)
    assert len(r2) == 6
    verts = vertices(r2, b2)
    want = [(-1, Fr(-1, 2)), (0, -1), (1, Fr(-5, 4)), (1, Fr(1, 2)), (0, 1), (-1, Fr(5, 4))]
    assert sorted(tuple(v) for v in verts) == sorted(want)
    for v in verts:
        assert inside(r2, b2, matvec(A, v))


def test_not_finitely_determined_without_schur():
    with pytest.raises(RuntimeError):
        mpi_set(rotation(1.0), EYE, [[float(a) for a in r] for r in BOX_F], [1.0] * 4, kmax=15)

History

Gilbert and Tan (1991) defined the maximal output admissible set for linear systems with state and control limits, gave conditions for finite determination, and computed the set with linear programs. Blanchini (1999) surveyed set invariance in control, and the book of Blanchini and Miani covers polyhedral invariant sets and their computation. The book of Borrelli, Bemporad and Morari presents the same iteration as the standard way to compute the terminal set of linear MPC with polyhedral limits.

References

  1. Elmer G. Gilbert and K. T. Tan, Linear systems with state and control constraints, the theory and application of maximal output admissible sets, IEEE Transactions on Automatic Control 36(9), 1008-1020, 1991, the definition of the maximal output admissible set, the conditions for finite determination, and the algorithm that tests redundancy by linear programming
  2. Franco Blanchini, Set invariance in control, Automatica 35(11), 1747-1767, 1999, the survey sections on polyhedral invariant sets for linear systems and their computation
  3. Franco Blanchini and Stefano Miani, Set-Theoretic Methods in Control, 2nd edition, Birkhäuser, 2015, the chapters on invariant sets and on the computation of polyhedral invariant sets
  4. Francesco Borrelli, Alberto Bemporad and Manfred Morari, Predictive Control for Linear and Hybrid Systems, Cambridge University Press, 2017, the chapter on invariant sets, with the algorithm for the maximal positive invariant set of an autonomous linear system

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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