Algorithm Search⌘K

Algorithmresearch

Constraint-based invariant generation

Also called Farkas lemma invariant synthesis.

Finds linear inductive invariants by writing an invariant template and solving the conditions it must meet with Farkas' lemma.

Time
O((|M| + 1)^k L) worst
Space
O(n k (n + m)) extra
Where
L = the cost of one exact linear program with O(n + m) unknowns and O(n k) rows; M = the set of allowed multipliers; k = the number of transitions; m = the number of rows of Init and of all transitions; n = the number of variables
Properties
deterministicofflineiterative
Origin
Michael A. Colon, Sriram Sankaranarayanan, Henny B. Sipma, 2003

Constraint-based invariant generation finds a linear loop invariant by solving for its coefficients. It fixes a template c⋅x+d≤0c \cdot x + d \le 0 with unknown cc and dd, writes the two conditions of an inductive invariant as "this system of inequalities implies that one", and turns each implication into linear constraints on cc, dd and some multipliers with Farkas' lemma. One linear program per choice of cases then gives an invariant, or proves that none of the allowed form exists.

In plain words

Instead of running the loop forward and guessing where it settles, write down the shape of the fact you want, "some number times ii plus some number times jj plus a constant stays below zero", with the numbers left blank. Two things must be true: the fact holds at the start, and one turn of the loop keeps it. Each of these says that some known inequalities force one more inequality. An old result from linear algebra says exactly when that happens: the new inequality must be a sum of the known ones, each times a nonnegative weight. Asking for such weights gives equations in the blanks. Solve them, and every answer is a proven fact about the loop.

The problem

The input is a loop over nn rational variables. Its initial states are Init={x:Px≤p}\mathit{Init} = \{x : Px \le p\}, and it has kk transitions, each a relation τi={(x,x′):Aix+Ai′x′≤ti}\tau_i = \{(x, x') : A_i x + A'_i x' \le t_i\} between the state xx before and the state x′x' after one step. Guards and assignments like if i<n then i:=i+1\mathbf{if}\ i < n\ \mathbf{then}\ i := i + 1 are such relations. The input also has a point xbadx_{\mathrm{bad}} that should be proved unreachable. The output is an inequality c⋅x+d≤0c \cdot x + d \le 0 that holds on Init\mathit{Init}, is kept by every transition over Qn\mathbb{Q}^n, and is false at xbadx_{\mathrm{bad}}; or "none".

This is the linear case of loop invariant synthesis. The general problem is undecidable, by Rice's theorem. Here the program is linear, the template is a single linear inequality and the states are rational, and the question becomes decidable: by Theorem 2 below it is a formula of real arithmetic, which quantifier elimination decides, and with fixed multipliers it is a finite set of linear programs.

The algorithm

  1. FARKAS-INVARIANT(P x <= p, transitions A_i x + A'_i x' <= t_i, x_bad, M)
  2. 1for each choice of one case per transition: (cons, mu) with mu in M, or dis
  3. 2S <- { lambda_0 P = c, lambda_0 p <= -d }
  4. 3for each transition i with multipliers lambda_i >= 0
  5. 4if case_i = (cons, mu): add mu c + lambda_i A_i = 0, lambda_i A'_i = c, lambda_i t_i <= (mu - 1) d
  6. 5else: add c + lambda_i A_i = 0, lambda_i A'_i = 0, lambda_i t_i - d <= -1
  7. 6add c . x_bad + d >= 1
  8. 7if S has a solution with all lambda >= 0 then return (c, d)
  9. 8return none

The unknowns are cc, dd and the multipliers; μ\mu is a number fixed by the choice. Line L2 is initiation: by Farkas' lemma, every point of Px≤pPx \le p satisfies c⋅x≤−dc \cdot x \le -d exactly when cc is a nonnegative combination λ0P\lambda_0 P of the rows with λ0p≤−d\lambda_0 p \le -d. Line L4 is consecution: the rows c⋅x≤−dc \cdot x \le -d (weight μ\mu) and Aix+Ai′x′≤tiA_i x + A'_i x' \le t_i (weights λi\lambda_i) must add up to c⋅x′≤−dc \cdot x' \le -d. Line L5 is the other way to satisfy consecution: the transition cannot fire from any state of the invariant, and the rows add up to the contradiction 0<00 < 0. Line L6 asks the invariant to exclude the bad point; it also fixes the scale, since (c,d)=(0,0)(c, d) = (0, 0) is excluded. Before the loop, the code checks with one linear program that Init\mathit{Init} is not empty, and drops every transition with an empty relation.

The product μc\mu c in line L4 is the only nonlinear term. Colon, Sankaranarayanan and Sipma kept μ\mu as an unknown and solved the nonlinear system by quantifier elimination. Fixing μ\mu to a value from a small set MM, as later work does with M={0,1}M = \{0, 1\}, makes each choice a linear program. μ=0\mu = 0 means the transition forces the invariant by itself, whatever the old state; μ=1\mu = 1 means it keeps c⋅x+dc \cdot x + d from growing. The code solves the programs with an exact two-phase simplex method over the rationals.

Example

The loop of Colon, Sankaranarayanan and Sipma (Fig. 1 of the paper) starts with (i,j)=(2,0)(i, j) = (2, 0) and repeats for ever one of two steps: i:=i+4i := i + 4, or (i,j):=(i+2,j+1)(i, j) := (i + 2, j + 1). The reachable states are (2+4a+2b,b)(2 + 4a + 2b, b) for a,b≥0a, b \ge 0. With M={1,0}M = \{1, 0\}, tried in this order:

bad point first feasible choice invariant found read as
(0,0)(0, 0) (cons 1, cons 1) −i+2≤0-i + 2 \le 0 i≥2i \ge 2
(3,1)(3, 1) (cons 1, cons 1) −i+2j+2≤0-i + 2j + 2 \le 0 i≥2j+2i \ge 2j + 2
(10,−1)(10, -1) (cons 1, cons 1) −j≤0-j \le 0 j≥0j \ge 0
(6,2)(6, 2) none of the 9 none reachable: (2,0)→(4,1)→(6,2)(2,0) \to (4,1) \to (6,2)

Check the second row by hand. Initiation: the rows i=2i = 2 and j=0j = 0 with weights −1-1 and 22 give −i+2j=−2-i + 2j = -2, so −i+2j+2≤0-i + 2j + 2 \le 0 holds at the start; equality rows may have weights of any sign. Consecution of the first step: the row i′−i=4i' - i = 4 with weight −1-1 and j′−j=0j' - j = 0 with weight 22, plus the old invariant with μ=1\mu = 1, sum to −i′+2j′+2≤−4-i' + 2j' + 2 \le -4, which is stronger than needed. The second step gives −i′+2j′+2≤0-i' + 2j' + 2 \le 0 exactly. Target: −3+2+2=1≥1-3 + 2 + 2 = 1 \ge 1. The paper lists j≥0j \ge 0 and i≥2j+2i \ge 2j + 2 as the generators of all inductive inequalities of this loop; i≥2i \ge 2 follows from them. Each run of the algorithm returns one inequality; running it with several bad points collects several.

Correctness

The full proof is in the proof file. Its steps:

  1. Affine Farkas lemma. If Ay≤bAy \le b has a rational solution, then all its solutions satisfy w⋅y≤δw \cdot y \le \delta if and only if λA=w\lambda A = w and λb≤δ\lambda b \le \delta for some λ≥0\lambda \ge 0. The system has no solution if and only if λA=0\lambda A = 0 and λb<0\lambda b < 0 for some λ≥0\lambda \ge 0. Both follow from linear programming duality.
  2. Exact conditions. With Init\mathit{Init} and every transition nonempty, c⋅x+d≤0c \cdot x + d \le 0 is inductive over Q\mathbb{Q} if and only if initiation has multipliers as in L2 and every transition satisfies the case cons for some μ≥0\mu \ge 0 or the case dis. In the case dis, μ\mu can always be scaled to 1, so only the consecution multiplier μ\mu restricts the method.
  3. Soundness. A returned (c,d)(c, d) satisfies these conditions, so it is inductive over Q\mathbb{Q}, hence over Z\mathbb{Z}, and holds in every reachable state by induction on the run. It is false at the bad point by L6.
  4. Completeness relative to MM. If some inductive inequality excludes the bad point and its consecution multipliers lie in MM, scale its coefficients and multipliers by a large enough positive number; it then satisfies the system of its choice of cases with the rows ≤−1\le -1 and ≥1\ge 1. The algorithm tries every choice, so it does not return "none".

With μ\mu free, step 2 is exactly Theorem 2 of the paper: the method is sound and complete for the single linear inequalities that are inductive over the rationals.

Proof: Constraint-based invariant generation is sound, and complete for the template over the rationalsfull

Setting. The states are the points of Qn\mathbb{Q}^n. The initial set is Init={x:Px≤p}\mathit{Init} = \{x : Px \le p\}. There are kk transitions, and transition ii is the relation τi={(x,x′):Aix+Ai′x′≤ti}\tau_i = \{(x, x') : A_i x + A'_i x' \le t_i\}. Equalities are written as two inequalities. The template is the inequality φc,d:c⋅x+d≤0\varphi_{c,d} : c \cdot x + d \le 0 with unknown c∈Qnc \in \mathbb{Q}^n and d∈Qd \in \mathbb{Q}. The inequality is inductive over Q\mathbb{Q} when

  • (I) every x∈Initx \in \mathit{Init} satisfies c⋅x+d≤0c \cdot x + d \le 0, and
  • (C) for every ii and every (x,x′)∈τi(x, x') \in \tau_i with c⋅x+d≤0c \cdot x + d \le 0, also c⋅x′+d≤0c \cdot x' + d \le 0.

All multipliers below are row vectors of rationals, and λ≥0\lambda \ge 0 means every entry is nonnegative.

Lemma 1: affine Farkas lemma

Claim. Let Ay≤bAy \le b be a system over Qm\mathbb{Q}^m.

  1. If the system has a solution, then every solution satisfies w⋅y≤δw \cdot y \le \delta if and only if there is λ≥0\lambda \ge 0 with λA=w\lambda A = w and λb≤δ\lambda b \le \delta.
  2. The system has no solution if and only if there is λ≥0\lambda \ge 0 with λA=0\lambda A = 0 and λb<0\lambda b < 0.

Proof. The "if" parts are one line each. In part 1, a solution yy gives w⋅y=λAy≤λb≤δw \cdot y = \lambda A y \le \lambda b \le \delta, because λ≥0\lambda \ge 0 and Ay≤bAy \le b. In part 2, a solution yy would give 0=λAy≤λb<00 = \lambda A y \le \lambda b < 0, which is false.

For the "only if" parts, use the duality theorem of linear programming, see the dual linear program. The primal problem is to maximize w⋅yw \cdot y subject to Ay≤bAy \le b, with yy free. Its dual is to minimize λb\lambda b subject to λA=w\lambda A = w and λ≥0\lambda \ge 0. Part 1: the primal is feasible and its values are bounded above by δ\delta, so it has an optimum v≤δv \le \delta, and the dual has an optimal λ\lambda with λb=v≤δ\lambda b = v \le \delta. Part 2: take w=0w = 0. The dual is feasible, with λ=0\lambda = 0, and the primal is infeasible, so the dual is unbounded below, and some feasible λ\lambda has λb<0\lambda b < 0. In both parts the data are rational and the simplex method finds an optimal or unbounded basic solution, so λ\lambda can be taken rational. This is the form of Farkas' lemma that Colon, Sankaranarayanan and Sipma state as their Theorem 1. □\square

Lemma 2: the exact conditions

Assume Init\mathit{Init} is not empty and no τi\tau_i is empty. For transition ii let Si={(x,x′)∈τi:c⋅x+d≤0}S_i = \{(x, x') \in \tau_i : c \cdot x + d \le 0\}.

Claim. φc,d\varphi_{c,d} is inductive over Q\mathbb{Q} if and only if

  • (I') there is λ0≥0\lambda_0 \ge 0 with λ0P=c\lambda_0 P = c and λ0p≤−d\lambda_0 p \le -d, and
  • (C') for each ii, one of the two cases holds:
    • cons with μ\mu: there are μ≥0\mu \ge 0 and λ≥0\lambda \ge 0 with μc+λAi=0\mu c + \lambda A_i = 0, λAi′=c\lambda A'_i = c and λti≤(μ−1)d\lambda t_i \le (\mu - 1) d;
    • dis: there is λ≥0\lambda \ge 0 with c+λAi=0c + \lambda A_i = 0, λAi′=0\lambda A'_i = 0 and λti−d<0\lambda t_i - d < 0.

Proof. (I) and (I'): Init\mathit{Init} is the solution set of Px≤pPx \le p, it is not empty, and (I) says that every solution satisfies c⋅x≤−dc \cdot x \le -d. By Lemma 1, part 1, this holds if and only if (I') holds.

(C) and (C') for one transition ii. SiS_i is the solution set of the system with the rows c⋅x≤−dc \cdot x \le -d and Aix+Ai′x′≤tiA_i x + A'_i x' \le t_i over the unknowns (x,x′)(x, x'). Give the first row the multiplier μ\mu and the other rows the multipliers λ\lambda.

  • Suppose SiS_i is not empty. Condition (C) for ii says that every point of SiS_i satisfies c⋅x′≤−dc \cdot x' \le -d, that is, 0⋅x+c⋅x′≤−d0 \cdot x + c \cdot x' \le -d. By Lemma 1, part 1, this holds if and only if there are μ,λ≥0\mu, \lambda \ge 0 with μc+λAi=0\mu c + \lambda A_i = 0 on the xx part, λAi′=c\lambda A'_i = c on the x′x' part, and −μd+λti≤−d-\mu d + \lambda t_i \le -d. The last inequality is λti≤(μ−1)d\lambda t_i \le (\mu - 1) d. This is the case cons with μ\mu.
  • Suppose SiS_i is empty. Then (C) holds for ii with nothing to check. By Lemma 1, part 2, there are μ,λ≥0\mu, \lambda \ge 0 with μc+λAi=0\mu c + \lambda A_i = 0, λAi′=0\lambda A'_i = 0 and −μd+λti<0-\mu d + \lambda t_i < 0. If μ=0\mu = 0, these say λ[Ai  Ai′]=0\lambda [A_i \; A'_i] = 0 and λti<0\lambda t_i < 0, so τi\tau_i is empty by Lemma 1, part 2, against the assumption. So μ>0\mu > 0. Divide μ\mu and λ\lambda by μ\mu; the equalities stay true and the strict inequality keeps its sign. This is the case dis.

Conversely, if the case cons holds for ii, the "if" part of Lemma 1, part 1, gives (C) for ii directly: for (x,x′)∈Si(x, x') \in S_i, c⋅x′=λAi′x′=λ(Aix+Ai′x′)−λAix≤λti+μc⋅x≤(μ−1)d−μd=−dc \cdot x' = \lambda A'_i x' = \lambda (A_i x + A'_i x') - \lambda A_i x \le \lambda t_i + \mu c \cdot x \le (\mu - 1) d - \mu d = -d, where the step μc⋅x≤−μd\mu c \cdot x \le -\mu d uses μ≥0\mu \ge 0. If the case dis holds for ii, then for (x,x′)∈Si(x, x') \in S_i, 0=(c+λAi)x+λAi′x′=c⋅x+λ(Aix+Ai′x′)≤−d+λti<00 = (c + \lambda A_i) x + \lambda A'_i x' = c \cdot x + \lambda (A_i x + A'_i x') \le -d + \lambda t_i < 0, which is false, so SiS_i is empty and (C) holds for ii. □\square

The case cons is nonlinear in the unknowns, because of the product μc\mu c. Once μ\mu is a fixed number, all the conditions of Lemma 2 are linear in cc, dd and the multipliers. The case dis needs only μ=1\mu = 1, by the proof above; only the consecution multiplier μ\mu of the case cons is a real restriction.

The algorithm

The algorithm gets a finite set MM of nonnegative rationals, the allowed values of μ\mu, and a point xbadx_{\mathrm{bad}}. It first returns the inequality 1≤01 \le 0 (that is, c=0c = 0, d=1d = 1) if Init\mathit{Init} is empty, and drops every empty τi\tau_i; both checks are linear programs. Then, for each choice of one case per remaining transition, cons with some μ∈M\mu \in M or dis, it builds the linear system LL of (I'), of the chosen cases, with the strict inequality of dis written as λti−d≤−1\lambda t_i - d \le -1, and of the target row c⋅xbad+d≥1c \cdot x_{\mathrm{bad}} + d \ge 1. It returns (c,d)(c, d) from the first LL that has a solution, and "none" if no LL has one. The linear programs are solved exactly over Q\mathbb{Q}.

Theorem 1: soundness

Claim. If the algorithm returns (c,d)(c, d), then φc,d\varphi_{c,d} is inductive over Q\mathbb{Q} and c⋅xbad+d>0c \cdot x_{\mathrm{bad}} + d > 0. Hence φc,d\varphi_{c,d} holds in every state that a run reaches, over the rationals and over the integers, and xbadx_{\mathrm{bad}} is not reachable.

Proof. If Init\mathit{Init} is empty, the answer is 1≤01 \le 0: (I) holds because there is no initial state, (C) holds because no state satisfies 1≤01 \le 0, and xbadx_{\mathrm{bad}} violates it. An empty τi\tau_i satisfies (C) with nothing to check, so dropping it changes nothing. Otherwise the solution of LL satisfies (I'), and for each remaining transition the chosen case of (C'); the row λti−d≤−1\lambda t_i - d \le -1 implies λti−d<0\lambda t_i - d < 0. By the "if" direction of Lemma 2, φc,d\varphi_{c,d} is inductive over Q\mathbb{Q}. The target row gives c⋅xbad+d≥1>0c \cdot x_{\mathrm{bad}} + d \ge 1 > 0. Normalizing (c,d)(c, d) to coprime integers multiplies it by a positive number, which changes none of this.

Every reachable state satisfies φc,d\varphi_{c,d} by induction on the length of the run: the first state by (I), and each step by (C). An integer program is the same system with states in Zn⊆Qn\mathbb{Z}^n \subseteq \mathbb{Q}^n; its initial states and its steps are among the rational ones, so (I) and (C) hold for it too. □\square

Theorem 2: completeness relative to MM

Claim. Suppose Init\mathit{Init} is not empty and some inequality φc,d\varphi_{c,d} is inductive over Q\mathbb{Q}, false at xbadx_{\mathrm{bad}}, and has, for every nonempty transition ii with SiS_i not empty, a cons multiplier μi∈M\mu_i \in M. Then the algorithm does not return "none".

Proof. Drop the empty transitions; the inequality is still inductive for the rest. By Lemma 2 there are multipliers for (I') and, for each remaining ii, for the case cons with μi\mu_i when SiS_i is not empty, and for the case dis when SiS_i is empty. Let v=c⋅xbad+d>0v = c \cdot x_{\mathrm{bad}} + d > 0 and, over the dis transitions, ε=min⁡i(d−λiti)>0\varepsilon = \min_i (d - \lambda_i t_i) > 0, with ε=1\varepsilon = 1 if there are none. Let s=max⁡(1/v,1/ε)>0s = \max(1/v, 1/\varepsilon) > 0, and multiply cc, dd and every λ\lambda by ss, but not the μi\mu_i. Every equality of (I') and of the cases is homogeneous in (c,d,λ)(c, d, \lambda) once μi\mu_i is fixed, and so are the inequalities λ0p≤−d\lambda_0 p \le -d and λti≤(μi−1)d\lambda t_i \le (\mu_i - 1) d; they stay true. The dis rows become s(λiti−d)≤−sε≤−1s(\lambda_i t_i - d) \le -s \varepsilon \le -1, and the target becomes sv≥1s v \ge 1. So the system LL of this choice of cases has a solution. The algorithm tries every choice of cases, so it stops at this choice or at an earlier one, and the exact solver finds the solution. □\square

Corollary: exactness over the rationals

With μ\mu left as an unknown, the conditions of Lemma 2 describe exactly the inductive inequalities over Q\mathbb{Q} of the template; this is Theorem 2 of Colon, Sankaranarayanan and Sipma. So the method with M=Q≥0M = \mathbb{Q}_{\ge 0}, which needs a solver for the nonlinear products μc\mu c, finds an inductive inequality false at xbadx_{\mathrm{bad}} whenever one exists. With a finite MM it is complete for the inequalities whose consecution multipliers lie in MM, and no more: for x:=1x := 1 followed by the loop x:=2xx := 2x, the inequalities x≥0x \ge 0 and x≥1x \ge 1 are inductive, but every certificate of consecution has μ=2\mu = 2, because λAi′=c\lambda A'_i = c and μc+λAi=0\mu c + \lambda A_i = 0 force μc=2c\mu c = 2c. The tests check this case with M={0,1}M = \{0, 1\} and with M={0,1,2}M = \{0, 1, 2\}.

What completeness does not give

The result is about inductive inequalities over Q\mathbb{Q}. An inequality can be inductive over Z\mathbb{Z} but not over Q\mathbb{Q}. For x:=0x := 0 followed by the loop while 2x≤1 do x:=2x+1\mathbf{while}\ 2x \le 1\ \mathbf{do}\ x := 2x + 1, the reachable states are 00 and 11, and x≤1x \le 1 is inductive over Z\mathbb{Z}, since an integer with 2x≤12x \le 1 has x≤0x \le 0. Over Q\mathbb{Q}, the state x=1/2x = 1/2 satisfies x≤1x \le 1 and the guard and goes to 22. Every rational inductive inequality cx+d≤0c x + d \le 0 holds at 00 and 11, hence at 1/21/2 by convexity, hence at 22 by consecution. So no rational inductive inequality excludes x=2x = 2, and the algorithm correctly returns "none" for it. Replacing the guard by its integer hull x≤0x \le 0 restores the integer invariant. ■\blacksquare

Complexity

There are (∣M∣+1)k(|M| + 1)^k choices of cases, one linear program each, plus k+1k + 1 emptiness checks. Each program has n+1n + 1 free unknowns cc, dd and one multiplier per row, O(n+m)O(n + m) unknowns in all, and O(nk)O(nk) constraints: nn equalities for initiation, 2n2n per transition, and k+2k + 2 inequalities. So the time is O((∣M∣+1)kL)O((|M| + 1)^k L), where LL is the cost of one program. Linear programming is polynomial with the ellipsoid method or interior-point methods; the simplex method of the code is exponential in the worst case but fast on these sizes. The exponential factor in kk comes from the case split; the paper's original method instead pays for quantifier elimination over the reals, which is doubly exponential in the worst case for cylindrical algebraic decomposition. The space is the simplex tableau, O(nk(n+m))O(nk(n + m)) numbers.

Properties

  • No widening. Unlike abstract interpretation with the polyhedra domain, the method does not iterate and extrapolate, so it does not lose an invariant to a widening step. The paper's INCREMENT example shows an invariant i≥1i \ge 1 that the classic polyhedra analysis misses and the constraint method finds.
  • Goal-directed. The target row L6 asks for an invariant that proves something. Without it, the solutions form a polyhedral cone, and its generators are all the inductive inequalities at once, which is what the paper computes.
  • Exact arithmetic matters. A floating-point solver can return coefficients that are inductive only up to rounding. The code works over the rationals, and the tests check each answer with a separate exact linear program.
  • Rational, not integer. The invariants are inductive over Qn\mathbb{Q}^n. For an integer program they are sound, but some integer invariants have no rational counterpart; see the pitfalls.

Variants and improvements

  • Nonlinear solving. The original method keeps μ\mu as an unknown and eliminates the quantifiers over the reals, which is complete for the template but costly. Sankaranarayanan, Sipma and Manna simplified this step so that it scales to larger loops.
  • Several locations. For a program with several cut points, put one template at each and write one table per path between them. The unknowns are shared, so it is still one system per choice of cases.
  • Conjunctions. A template with kk inequalities is much harder, because consecution of one inequality may need the others. In practice one strengthens the transitions with the inequalities already found and runs again.
  • Termination. The same Farkas encoding, applied to "decreases by at least 1 and is bounded below", gives linear ranking function synthesis.
  • Boolean encodings. Gulwani, Srivastava and Venkatesan encode the same constraints, with bounded integer coefficients, into SAT, and handle templates with disjunctions.
  • Nonlinear templates. Polynomial invariants can use the same idea with a Positivstellensatz in place of Farkas' lemma, which leads to semidefinite programs.

When to use it

Use it when the invariant you need is a linear relation between several variables with coefficients you cannot guess, the loop body is linear or can be over-approximated by linear relations, and the loop is small. If you can guess the candidates, Houdini is cheaper. If you need many invariants of a fixed simple shape for a large program, the octagon or interval domains scale better.

Pitfalls

  • Rational is not integer. For x:=0x := 0 followed by while 2x≤1 do x:=2x+1\mathbf{while}\ 2x \le 1\ \mathbf{do}\ x := 2x + 1, the reachable states are 0 and 1, and x≤1x \le 1 is inductive over the integers. But x=1/2x = 1/2 satisfies the guard and goes to 2, so every rational inductive inequality holds at 2, and the algorithm returns "none" for the bad point 2. Tighten the guard to its integer hull x≤0x \le 0 first; then x≤1x \le 1 is found. The tests check both.
  • A finite MM misses invariants. For x:=1x := 1 followed by x:=2xx := 2x for ever, x≥1x \ge 1 is inductive, but its only consecution certificate has μ=2\mu = 2. With M={0,1}M = \{0, 1\} the algorithm returns "none" for the bad point −1-1; with 2∈M2 \in M it finds x≥1x \ge 1.
  • Forgetting the disabled case. Without line L5, a transition that can never fire from the invariant still needs a consecution certificate, and the method can miss invariants that only hold because a guard is false.
  • One inequality is not enough. For x:=1x := 1 followed by x:=x+2x := x + 2 for ever, the reachable set is the odd positive numbers; no linear inequality separates it from 2. A single inequality can only describe a half-space, and conjunctions only a convex set.
  • Mistaking the test oracle for a proof. The linear programs decide inductiveness over Q\mathbb{Q} exactly. The tests also check the answers on a box of integer states and on random runs; those are bounded checks, evidence and not proof.

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.

farkas_invariant_generation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/farkas-invariant-generation/. The authors are listed in prov/K23N8A.jsonl.
"""Constraint-based generation of linear invariants with Farkas' lemma.

A loop has n rational variables x. Init is a list of rows (a, b), each the
inequality a . x <= b. A transition is a list of rows (a, b) with len(a) =
2n, each the inequality a[:n] . x + a[n:] . x' <= b over the old state x and
the new state x'. The template is c . x + d <= 0 with unknown c and d.

invariant_for(loop, bad, mus) looks for an inequality that holds initially,
is kept by every transition over the rationals, and is false at the point
bad. Each transition is handled by one of the cases ("cons", mu) with mu in
mus, where the transition keeps the inequality, or ("dis", 1), where the
transition cannot fire from a state of the inequality. Each choice of cases
gives one linear program, solved exactly with rational arithmetic. The
answer is (c, d) with coprime integers, or None. If Init is empty, the
answer is the inequality 1 <= 0, which is false and inductive.

Result: sound always; complete for the invariants whose consecution
multipliers lie in mus (see the proof file). Cost: (|mus| + 1)^k linear
programs for the k transitions with a nonempty relation, each with
O(n + m) unknowns for m rows in all.
"""

from itertools import product
from math import gcd

from fraclp import feasible_point


class Loop:
    """A loop with rational variables: n, the rows of Init, and the rows of
    each transition over (x, x')."""

    def __init__(self, n, init, trans):
        self.n = n
        self.init = [(list(a), b) for a, b in init]
        self.trans = [[(list(a), b) for a, b in t] for t in trans]


def affine(n, guard, update):
    """The rows of the transition 'if guard then x := U x + u'. guard is a
    list of rows (a, b) over x; update is a list of n pairs (U_k, u_k) and
    sets x'_k = U_k . x + u_k."""
    rows = [(list(a) + [0] * n, b) for a, b in guard]
    for k, (uk, ck) in enumerate(update):
        e = [0] * n
        e[k] = 1
        lhs = [-v for v in uk] + e
        rows.append((lhs, ck))
        rows.append(([-v for v in lhs], -ck))
    return rows


def equal(a, b):
    """The two rows of a . x = b."""
    return [(list(a), b), ([-v for v in a], -b)]


def cases(mus):
    """The order in which the cases of one transition are tried. The case
    ("dis", 0), an empty transition, is handled once in invariant_for."""
    return [("cons", mu) for mu in mus] + [("dis", 1)]


def empty(rows, n):
    """Whether the rows have no rational solution in n variables."""
    return feasible_point(a_ub=[a for a, _ in rows], b_ub=[b for _, b in rows], n=n, free=range(n)) is None


def _merge(rows):
    """Join each pair of rows a . v <= b, -a . v <= -b that follow each
    other into one equality. Its multiplier is then free in sign, which is
    the difference of the two nonnegative ones; the system is the same, only
    smaller. Returns a list of (a, b, is_equality)."""
    out = []
    i = 0
    while i < len(rows):
        a, b = rows[i]
        if i + 1 < len(rows) and rows[i + 1][1] == -b and all(u == -v for u, v in zip(rows[i + 1][0], a)):
            out.append((a, b, True))
            i += 2
        else:
            out.append((a, b, False))
            i += 1
    return out


def _system(loop, bad, choice):
    """The linear system of one choice of cases. Unknowns: c (n, free),
    d (free), then one multiplier per row of Init and of each transition."""
    n = loop.n
    blocks = [_merge(loop.init)] + [_merge(t) for t in loop.trans]
    nvar = n + 1 + sum(len(b) for b in blocks)
    free = list(range(n + 1))
    off = n + 1
    for block in blocks:
        free += [off + i for i, (_, _, eq) in enumerate(block) if eq]
        off += len(block)
    init, trans = blocks[0], blocks[1:]
    a_eq, b_eq, a_ub, b_ub = [], [], [], []

    def row():
        return [0] * nvar

    off = n + 1
    # @line L2 initiation: lambda0 P = c and lambda0 p <= -d
    for k in range(n):
        r = row()
        r[k] = -1
        for i, (a, _, _) in enumerate(init):
            r[off + i] = a[k]
        a_eq.append(r)
        b_eq.append(0)
    r = row()
    r[n] = 1
    for i, (_, b, _) in enumerate(init):
        r[off + i] = b
    a_ub.append(r)
    b_ub.append(0)
    off += len(init)
    # @line L3 one block of constraints per transition
    for t, (kind, mu) in zip(trans, choice):
        for k in range(n):
            # mu c + lambda A = 0, where A is the part over x
            r = row()
            r[k] = mu
            for i, (a, _, _) in enumerate(t):
                r[off + i] = a[k]
            a_eq.append(r)
            b_eq.append(0)
            # lambda A' = c (cons) or lambda A' = 0 (dis)
            r = row()
            if kind == "cons":
                r[k] = -1
            for i, (a, _, _) in enumerate(t):
                r[off + i] = a[n + k]
            a_eq.append(r)
            b_eq.append(0)
        r = row()
        for i, (_, b, _) in enumerate(t):
            r[off + i] = b
        if kind == "cons":
            # @line L4 lambda t <= (mu - 1) d
            r[n] = 1 - mu
            a_ub.append(r)
            b_ub.append(0)
        else:
            # @line L5 lambda t - mu d <= -1
            r[n] = -mu
            a_ub.append(r)
            b_ub.append(-1)
        off += len(t)
    # @line L6 c . bad + d >= 1
    r = row()
    for k in range(n):
        r[k] = -bad[k]
    r[n] = -1
    a_ub.append(r)
    b_ub.append(-1)
    return nvar, free, a_eq, b_eq, a_ub, b_ub


def normalize(c, d):
    """Scale c . x + d <= 0 to coprime integers."""
    vals = list(c) + [d]
    den = 1
    for v in vals:
        den = den * v.denominator // gcd(den, v.denominator)
    ints = [int(v * den) for v in vals]
    g = 0
    for v in ints:
        g = gcd(g, abs(v))
    g = g or 1
    return tuple(v // g for v in ints[:-1]), ints[-1] // g


def invariant_for(loop, bad, mus=(1, 0)):
    """An inductive inequality (c, d), meaning c . x + d <= 0, that is
    false at the point bad, or None. See the module docstring."""
    if empty(loop.init, loop.n):
        return (0,) * loop.n, 1  # Init is empty: false is inductive
    # A transition with an empty relation needs no condition: drop it.
    live = Loop(loop.n, loop.init, [t for t in loop.trans if not empty(t, 2 * loop.n)])
    # @line L1 try every choice of one case per transition
    for choice in product(cases(mus), repeat=len(live.trans)):
        nvar, free, a_eq, b_eq, a_ub, b_ub = _system(live, bad, choice)
        # @line L7 solve the linear program exactly
        sol = feasible_point(a_eq, b_eq, a_ub, b_ub, nvar, free=free)
        if sol is not None:
            return normalize(sol[: loop.n], sol[loop.n])
    # @line L8 no choice is feasible
    return None


def holds(c, d, x):
    """Whether c . x + d <= 0 at the point x."""
    return sum(ci * xi for ci, xi in zip(c, x)) + d <= 0
fraclp.py 179 lines
# SPDX-License-Identifier: MIT
# Shared helper of the vs2 compilers pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact linear programming over the rationals.

lp_solve(c, a_eq, b_eq, a_ub, b_ub, free) minimizes c . x subject to
a_eq x = b_eq, a_ub x <= b_ub, and x_j >= 0 for every j not in free. The
inputs may be int or Fraction. The answer is exact. It returns one of
  ("optimal", x, value), ("infeasible", None, None), ("unbounded", None, None)
with x a list of Fraction.

The method is the two-phase simplex method with Bland's rule, which never
cycles. The tableau holds only integers: each row is kept as an integer
multiple of the true row, the pivot step is a cross multiplication, and
each row is divided by the gcd of its entries. A free variable is split
into two nonnegative ones. Cost: exponential in the worst case, as for
every simplex method; fast on the small systems of these pages.
"""

from fractions import Fraction
from math import gcd


def _int_row(vals):
    """Scale a list of rationals to integers with the same signs."""
    den = 1
    for v in vals:
        v = Fraction(v)
        den = den * v.denominator // gcd(den, v.denominator)
    return [int(Fraction(v) * den) for v in vals]


def _reduce(row):
    g = 0
    for v in row:
        if v:
            g = gcd(g, v)
            if g == 1:
                return row
    if g > 1:
        return [v // g for v in row]
    return row


def _pivot(t, basis, r, j):
    pr = t[r]
    if pr[j] < 0:
        pr = t[r] = [-v for v in pr]
    p = pr[j]
    nz = [k for k, v in enumerate(pr) if v]
    for i, row in enumerate(t):
        f = row[j]
        if i != r and f:
            new = [v * p for v in row]
            for k in nz:
                new[k] -= f * pr[k]
            t[i] = _reduce(new)
    basis[r] = j


def _simplex(t, basis, cost, allowed):
    """Minimize cost . x over the tableau t with the given basis, entering
    only columns in allowed. Return "optimal" or "unbounded"."""
    ncols = len(cost)
    while True:
        enter = -1
        inbasis = set(basis)
        priced = [(Fraction(cost[b], t[i][b]), t[i]) for i, b in enumerate(basis) if cost[b]]
        for j in range(ncols):
            if not allowed[j] or j in inbasis:
                continue
            z = Fraction(cost[j])
            for cb, row in priced:
                if row[j]:
                    z -= cb * row[j]
            if z < 0:
                enter = j
                break
        if enter < 0:
            return "optimal"
        best = -1
        for i, row in enumerate(t):
            a = row[enter]
            if a > 0:
                if best < 0:
                    best = i
                    continue
                # Compare row[-1] / a with the best ratio, then the basis index.
                lhs = row[-1] * t[best][enter]
                rhs = t[best][-1] * a
                if lhs < rhs or (lhs == rhs and basis[i] < basis[best]):
                    best = i
        if best < 0:
            return "unbounded"
        _pivot(t, basis, best, enter)


def lp_solve(c, a_eq=(), b_eq=(), a_ub=(), b_ub=(), free=()):
    """Minimize c . x subject to a_eq x = b_eq, a_ub x <= b_ub and x_j >= 0
    for j not in free. See the module docstring for the result."""
    n = len(c)
    free = set(free)
    # Column map: variable j -> list of (column, sign).
    cols = []
    ncol = 0
    for j in range(n):
        if j in free:
            cols.append([(ncol, 1), (ncol + 1, -1)])
            ncol += 2
        else:
            cols.append([(ncol, 1)])
            ncol += 1
    nslack = len(a_ub)
    rows = [(coeffs, rhs, None) for coeffs, rhs in zip(a_eq, b_eq)]
    rows += [(coeffs, rhs, ncol + k) for k, (coeffs, rhs) in enumerate(zip(a_ub, b_ub))]
    m = len(rows)
    # A row whose slack can start in the basis needs no artificial variable.
    needs = [slack is None or rhs < 0 for _, rhs, slack in rows]
    nart = sum(needs)
    width = ncol + nslack + nart
    t = []
    basis = []
    art = ncol + nslack
    for i, (coeffs, rhs, slack) in enumerate(rows):
        row = [0] * (width + 1)
        for j in range(n):
            a = coeffs[j]
            if a:
                for col, sign in cols[j]:
                    row[col] += sign * a
        if slack is not None:
            row[slack] = 1
        row[-1] = rhs
        if needs[i]:
            if rhs < 0:
                row = [-v for v in row]
            row[art] = 1
            basis.append(art)
            art += 1
        else:
            basis.append(slack)
        if not all(type(v) is int for v in row):
            row = _int_row(row)
        t.append(_reduce(row))
    # Phase 1: minimize the sum of the artificial variables.
    cost1 = [0] * (ncol + nslack) + [1] * nart
    _simplex(t, basis, cost1, [True] * width)
    if any(t[i][-1] for i in range(m) if basis[i] >= ncol + nslack):
        return ("infeasible", None, None)
    # Drive the artificial variables out of the basis, or drop their rows.
    i = 0
    while i < len(t):
        if basis[i] >= ncol + nslack:
            j = next((j for j in range(ncol + nslack) if t[i][j] != 0), None)
            if j is None:
                del t[i]
                del basis[i]
                continue
            _pivot(t, basis, i, j)
        i += 1
    # Phase 2 on the real columns.
    cost2 = [Fraction(0)] * width
    for j in range(n):
        for col, sign in cols[j]:
            cost2[col] = sign * Fraction(c[j])
    allowed = [j < ncol + nslack for j in range(width)]
    if _simplex(t, basis, cost2, allowed) == "unbounded":
        return ("unbounded", None, None)
    val = [Fraction(0)] * width
    for i, b in enumerate(basis):
        val[b] = Fraction(t[i][-1], t[i][b])
    x = [sum(sign * val[col] for col, sign in cols[j]) for j in range(n)]
    return ("optimal", x, sum(Fraction(c[j]) * x[j] for j in range(n)))


def feasible_point(a_eq=(), b_eq=(), a_ub=(), b_ub=(), n=0, free=()):
    """A point of {x : a_eq x = b_eq, a_ub x <= b_ub, x_j >= 0 for j not in
    free} with n variables, or None if the set is empty."""
    status, x, _ = lp_solve([0] * n, a_eq, b_eq, a_ub, b_ub, free)
    return x if status == "optimal" else None
test_farkas_invariant_generation.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/farkas-invariant-generation/. The authors are listed in prov/K23N8A.jsonl.

import itertools
import random
import unittest
from fractions import Fraction

from farkas_invariant_generation import Loop, affine, equal, holds, invariant_for
from fraclp import lp_solve


def dot(a, x):
    return sum(Fraction(ai) * xi for ai, xi in zip(a, x))


def primal_inductive(loop, c, d):
    """The oracle: maximize c . x over Init and c . x' over each transition
    from c . x + d <= 0, exactly, and compare with -d."""
    n = loop.n
    st, _, val = lp_solve([-v for v in c], a_ub=[a for a, _ in loop.init], b_ub=[b for _, b in loop.init], free=range(n))
    if st == "unbounded" or (st == "optimal" and -val + d > 0):
        return False
    for t in loop.trans:
        a_ub = [a for a, _ in t] + [list(c) + [0] * n]
        b_ub = [b for _, b in t] + [-d]
        st, _, val = lp_solve([0] * n + [-v for v in c], a_ub=a_ub, b_ub=b_ub, free=range(2 * n))
        if st == "unbounded" or (st == "optimal" and -val + d > 0):
            return False
    return True


def certificate(loop, c, d, mus=None):
    """Whether Farkas multipliers exist for the fixed inequality (c, d).
    With mus = None the multiplier mu of consecution is a free unknown
    mu >= 0, so every condition is linear; otherwise mu is taken from mus."""
    n = loop.n
    m0 = len(loop.init)
    a_eq = [[a[k] for a, _ in loop.init] for k in range(n)]
    b_eq = [c[k] for k in range(n)]
    if lp_solve([0] * m0, a_eq, b_eq, [[b for _, b in loop.init]], [-d])[0] != "optimal":
        return False
    for t in loop.trans:
        m = len(t)
        ok = False
        options = [("cons", None), ("dis", None)] if mus is None else [("cons", mu) for mu in mus] + [("dis", None)]
        for kind, mu in options:
            # Unknowns: mu, then lambda (m). All nonnegative.
            a_eq, b_eq = [], []
            for k in range(n):
                a_eq.append([c[k] if mu is None or kind == "dis" else 0] + [a[k] for a, _ in t])
                b_eq.append(0 if mu is None or kind == "dis" else -mu * c[k])
                a_eq.append([0] + [a[n + k] for a, _ in t])
                b_eq.append(c[k] if kind == "cons" else 0)
            if kind == "cons" and mu is None:
                a_ub, b_ub = [[-d] + [b for _, b in t]], [-d]
            elif kind == "cons":
                a_ub, b_ub = [[0] + [b for _, b in t]], [(mu - 1) * d]
            else:
                a_ub, b_ub = [[-d] + [b for _, b in t]], [-1]
            if lp_solve([0] * (m + 1), a_eq, b_eq, a_ub, b_ub)[0] == "optimal":
                ok = True
                break
        if not ok:
            return False
    return True


def int_box_inductive(loop, c, d, lo, hi):
    """Initiation and consecution on the integer points of a box, for loops
    built with affine(), whose rows over x' are the update equalities."""
    n = loop.n
    pts = list(itertools.product(range(lo, hi + 1), repeat=n))
    for x in pts:
        if all(dot(a, x) <= b for a, b in loop.init) and not holds(c, d, x):
            return False
    for t in loop.trans:
        for x in pts:
            if not holds(c, d, x):
                continue
            for y in pts:
                if all(dot(a, list(x) + list(y)) <= b for a, b in t) and not holds(c, d, y):
                    return False
    return True


# The loop of Colon, Sankaranarayanan and Sipma, Fig. 1:
# (i, j) := (2, 0); loop forever: i := i + 4, or (i, j) := (i + 2, j + 1).
CSS = Loop(
    2,
    equal([1, 0], 2) + equal([0, 1], 0),
    [affine(2, [], [([1, 0], 4), ([0, 1], 0)]), affine(2, [], [([1, 0], 2), ([0, 1], 1)])],
)


class TestPage(unittest.TestCase):
    def test_css_example(self):
        self.assertEqual(invariant_for(CSS, (0, 0)), ((-1, 0), 2))
        self.assertEqual(invariant_for(CSS, (3, 1)), ((-1, 2), 2))
        self.assertEqual(invariant_for(CSS, (10, -1)), ((0, -1), 0))
        for inv in [((-1, 0), 2), ((-1, 2), 2), ((0, -1), 0)]:
            self.assertTrue(primal_inductive(CSS, *inv))
            self.assertTrue(certificate(CSS, *inv, mus=(1, 0)))

    def test_css_reachable(self):
        # Every reachable state is i = 2 + 4a + 2b, j = b with a, b >= 0.
        for a in range(6):
            for b in range(6):
                x = (2 + 4 * a + 2 * b, b)
                self.assertTrue(holds((-1, 2), 2, x))
                self.assertTrue(holds((0, -1), 0, x))
                self.assertIsNone(invariant_for(CSS, x))

    def test_integer_trap(self):
        # x := 0; while 2x <= 1: x := 2x + 1. The reachable states are 0
        # and 1, and x <= 1 is inductive over the integers, but every
        # rational inductive inequality also holds at x = 2.
        trap = Loop(1, equal([1], 0), [affine(1, [([2], 1)], [([2], 1)])])
        self.assertIsNone(invariant_for(trap, (2,)))
        self.assertTrue(int_box_inductive(trap, (1,), -1, -6, 6))
        self.assertFalse(primal_inductive(trap, (1,), -1))
        self.assertEqual(invariant_for(trap, (3,)), ((1,), -2))
        # With the guard replaced by its integer hull x <= 0, x <= 1 is found.
        hull = Loop(1, equal([1], 0), [affine(1, [([1], 0)], [([2], 1)])])
        self.assertEqual(invariant_for(hull, (2,)), ((1,), -1))

    def test_multiplier_two(self):
        # x := 1; loop forever: x := 2x. Both x >= 0 and x >= 1 are
        # inductive, but their certificates need mu = 2.
        dbl = Loop(1, equal([1], 1), [affine(1, [], [([2], 0)])])
        self.assertIsNone(invariant_for(dbl, (-1,)))
        self.assertEqual(invariant_for(dbl, (-1,), mus=(1, 0, 2)), ((-1,), 1))
        for d in (0, 1):
            self.assertTrue(primal_inductive(dbl, (-1,), d))
            self.assertTrue(certificate(dbl, (-1,), d))
            self.assertFalse(certificate(dbl, (-1,), d, mus=(1, 0)))

    def test_empty_init(self):
        empty = Loop(1, [([1], 0), ([-1], -1)], [affine(1, [], [([1], 1)])])
        self.assertEqual(invariant_for(empty, (0,)), ((0,), 1))


def rand_loop(rng):
    n = 2
    if rng.random() < 0.5:
        init = equal([1, 0], rng.randint(-2, 2)) + equal([0, 1], rng.randint(-2, 2))
    else:
        lx = rng.randint(-2, 1)
        init = [([1, 0], lx + 1), ([-1, 0], -lx)] + equal([0, 1], rng.randint(-2, 2))
    trans = []
    for _ in range(rng.randint(1, 2)):
        guard = []
        if rng.random() < 0.6:
            guard.append(([rng.randint(-1, 1), rng.randint(-1, 1)], rng.randint(-3, 3)))
        update = []
        for k in range(n):
            u = [0, 0]
            u[k] = rng.choice([1, 1, 1, 0, -1])
            if rng.random() < 0.3:
                u[1 - k] = rng.choice([-1, 1])
            update.append((u, rng.randint(-2, 2)))
        trans.append((guard, update))
    loop = Loop(n, init, [affine(n, g, u) for g, u in trans])
    return loop, trans


def runs(loop, trans, rng, walks=3, steps=12):
    """States of random runs from the integer initial states in a box."""
    starts = [x for x in itertools.product(range(-4, 5), repeat=2) if all(dot(a, x) <= b for a, b in loop.init)]
    seen = set(starts)
    for x0 in starts:
        for _ in range(walks):
            x = x0
            for _ in range(steps):
                enabled = [u for g, u in trans if all(dot(a, x) <= b for a, b in g)]
                if not enabled:
                    break
                u = rng.choice(enabled)
                x = tuple(dot(uk, x) + ck for uk, ck in u)
                seen.add(x)
    return seen


class TestRandom(unittest.TestCase):
    def test_found_invariants_are_sound(self):
        rng = random.Random(31)
        found = 0
        for _ in range(500):
            loop, trans = rand_loop(rng)
            bad = (rng.randint(-4, 4), rng.randint(-4, 4))
            inv = invariant_for(loop, bad)
            if inv is None:
                continue
            found += 1
            c, d = inv
            self.assertFalse(holds(c, d, bad))
            self.assertTrue(primal_inductive(loop, c, d))
            self.assertTrue(certificate(loop, c, d, mus=(1, 0)))
            for x in runs(loop, trans, rng):
                self.assertTrue(holds(c, d, x))
        self.assertGreater(found, 150)

    def test_complete_on_grid(self):
        # The oracle enumerates the inequalities with c in {-1, 0, 1}^2 and
        # d in {-3, ..., 3}. Rational inductiveness by the primal LP must
        # agree with the existence of a certificate with mu free (Farkas'
        # lemma), and whenever one with mu in {0, 1} excludes a bad point,
        # the algorithm must find some invariant for it.
        rng = random.Random(5)
        grid = [(c, d) for c in itertools.product((-1, 0, 1), repeat=2) if c != (0, 0) for d in range(-3, 4)]
        checked = 0
        for _ in range(15):
            loop, _ = rand_loop(rng)
            good = []
            for c, d in grid:
                ind = primal_inductive(loop, c, d)
                self.assertEqual(ind, certificate(loop, c, d))
                if ind and certificate(loop, c, d, mus=(1, 0)):
                    good.append((c, d))
            for bad in itertools.product(range(-3, 4), repeat=2):
                if any(not holds(c, d, bad) for c, d in good):
                    checked += 1
                    self.assertIsNotNone(invariant_for(loop, bad))
        self.assertGreater(checked, 100)


if __name__ == "__main__":
    unittest.main()

History

Colon, Sankaranarayanan and Sipma presented the method at CAV 2003. They encoded initiation and consecution of a linear template with Farkas' lemma, observed that consecution is nonlinear because of the multiplier μ\mu, and solved the constraints by quantifier elimination with factorization heuristics. They proved that the constraints describe exactly the inductive inequalities and showed loops where the method beats polyhedra analysis with widening. Sankaranarayanan, Sipma and Manna made the method scale at SAS 2004. In the same years Podelski and Rybalchenko used Farkas' lemma for ranking functions, and Gulwani, Srivastava and Venkatesan later generalized templates and solved them with SAT solvers. Real tools now pass these constraints to LP, SMT or SAT solvers.

References

  1. Michael A. Colon, Sriram Sankaranarayanan and Henny B. Sipma, Linear invariant generation using non-linear constraint solving, Proceedings of CAV 2003, LNCS 2725, Section 2 (Theorem 1, Farkas' lemma), Section 3 (the initiation and consecution tables with the multiplier mu, Theorem 2), Section 4 (solving the constraints) and Fig. 1
  2. Sriram Sankaranarayanan, Henny B. Sipma and Zohar Manna, Constraint-based linear-relations analysis, Proceedings of SAS 2004, LNCS 3148, pp. 53 to 68, the simplifications of the constraint solving step that make the method scale
  3. Sumit Gulwani, Saurabh Srivastava and Ramarathnam Venkatesan, Program analysis as constraint solving, Proceedings of PLDI 2008, the template-based invariant generation with Farkas' lemma and its reduction to SAT
  4. Andreas Podelski and Andrey Rybalchenko, A complete method for the synthesis of linear ranking functions, Proceedings of VMCAI 2004, LNCS 2937, pp. 239 to 251, the same use of Farkas' lemma for termination instead of invariance

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