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
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with unknown and , writes the two conditions of an inductive invariant as "this system of inequalities implies that one", and turns each implication into linear constraints on , 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 plus some number times 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 rational variables. Its initial states are , and it has transitions, each a relation between the state before and the state after one step. Guards and assignments like are such relations. The input also has a point that should be proved unreachable. The output is an inequality that holds on , is kept by every transition over , and is false at ; 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
FARKAS-INVARIANT(P x <= p, transitions A_i x + A'_i x' <= t_i, x_bad, M)- 1
for each choice of one case per transition: (cons, mu) with mu in M, or dis - 2
S <- { lambda_0 P = c, lambda_0 p <= -d } - 3
for each transition i with multipliers lambda_i >= 0 - 4
if case_i = (cons, mu): add mu c + lambda_i A_i = 0, lambda_i A'_i = c, lambda_i t_i <= (mu - 1) d - 5
else: add c + lambda_i A_i = 0, lambda_i A'_i = 0, lambda_i t_i - d <= -1 - 6
add c . x_bad + d >= 1 - 7
if S has a solution with all lambda >= 0 then return (c, d) - 8
return none
The unknowns are , and the multipliers; is a number fixed by the choice. Line L2 is initiation: by Farkas' lemma, every point of satisfies exactly when is a nonnegative combination of the rows with . Line L4 is consecution: the rows (weight ) and (weights ) must add up to . 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 . Line L6 asks the invariant to exclude the bad point; it also fixes the scale, since is excluded. Before the loop, the code checks with one linear program that is not empty, and drops every transition with an empty relation.
The product in line L4 is the only nonlinear term. Colon, Sankaranarayanan and Sipma kept as an unknown and solved the nonlinear system by quantifier elimination. Fixing to a value from a small set , as later work does with , makes each choice a linear program. means the transition forces the invariant by itself, whatever the old state; means it keeps 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 and repeats for ever one of two steps: , or . The reachable states are for . With , tried in this order:
| bad point | first feasible choice | invariant found | read as |
|---|---|---|---|
| (cons 1, cons 1) | |||
| (cons 1, cons 1) | |||
| (cons 1, cons 1) | |||
| none of the 9 | none | reachable: |
Check the second row by hand. Initiation: the rows and with weights and give , so holds at the start; equality rows may have weights of any sign. Consecution of the first step: the row with weight and with weight , plus the old invariant with , sum to , which is stronger than needed. The second step gives exactly. Target: . The paper lists and as the generators of all inductive inequalities of this loop; 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:
- Affine Farkas lemma. If has a rational solution, then all its solutions satisfy if and only if and for some . The system has no solution if and only if and for some . Both follow from linear programming duality.
- Exact conditions. With and every transition nonempty, is inductive over if and only if initiation has multipliers as in L2 and every transition satisfies the case cons for some or the case dis. In the case dis, can always be scaled to 1, so only the consecution multiplier restricts the method.
- Soundness. A returned satisfies these conditions, so it is inductive over , hence over , and holds in every reachable state by induction on the run. It is false at the bad point by L6.
- Completeness relative to . If some inductive inequality excludes the bad point and its consecution multipliers lie in , scale its coefficients and multipliers by a large enough positive number; it then satisfies the system of its choice of cases with the rows and . The algorithm tries every choice, so it does not return "none".
With 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 . The initial set is . There are transitions, and transition is the relation . Equalities are written as two inequalities. The template is the inequality with unknown and . The inequality is inductive over when
- (I) every satisfies , and
- (C) for every and every with , also .
All multipliers below are row vectors of rationals, and means every entry is nonnegative.
Lemma 1: affine Farkas lemma
Claim. Let be a system over .
- If the system has a solution, then every solution satisfies if and only if there is with and .
- The system has no solution if and only if there is with and .
Proof. The "if" parts are one line each. In part 1, a solution gives , because and . In part 2, a solution would give , 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 subject to , with free. Its dual is to minimize subject to and . Part 1: the primal is feasible and its values are bounded above by , so it has an optimum , and the dual has an optimal with . Part 2: take . The dual is feasible, with , and the primal is infeasible, so the dual is unbounded below, and some feasible has . In both parts the data are rational and the simplex method finds an optimal or unbounded basic solution, so can be taken rational. This is the form of Farkas' lemma that Colon, Sankaranarayanan and Sipma state as their Theorem 1.
Lemma 2: the exact conditions
Assume is not empty and no is empty. For transition let .
Claim. is inductive over if and only if
- (I') there is with and , and
- (C') for each , one of the two cases holds:
- cons with : there are and with , and ;
- dis: there is with , and .
Proof. (I) and (I'): is the solution set of , it is not empty, and (I) says that every solution satisfies . By Lemma 1, part 1, this holds if and only if (I') holds.
(C) and (C') for one transition . is the solution set of the system with the rows and over the unknowns . Give the first row the multiplier and the other rows the multipliers .
- Suppose is not empty. Condition (C) for says that every point of satisfies , that is, . By Lemma 1, part 1, this holds if and only if there are with on the part, on the part, and . The last inequality is . This is the case cons with .
- Suppose is empty. Then (C) holds for with nothing to check. By Lemma 1, part 2, there are with , and . If , these say and , so is empty by Lemma 1, part 2, against the assumption. So . Divide and by ; the equalities stay true and the strict inequality keeps its sign. This is the case dis.
Conversely, if the case cons holds for , the "if" part of Lemma 1, part 1, gives (C) for directly: for , , where the step uses . If the case dis holds for , then for , , which is false, so is empty and (C) holds for .
The case cons is nonlinear in the unknowns, because of the product . Once is a fixed number, all the conditions of Lemma 2 are linear in , and the multipliers. The case dis needs only , by the proof above; only the consecution multiplier of the case cons is a real restriction.
The algorithm
The algorithm gets a finite set of nonnegative rationals, the allowed values of , and a point . It first returns the inequality (that is, , ) if is empty, and drops every empty ; both checks are linear programs. Then, for each choice of one case per remaining transition, cons with some or dis, it builds the linear system of (I'), of the chosen cases, with the strict inequality of dis written as , and of the target row . It returns from the first that has a solution, and "none" if no has one. The linear programs are solved exactly over .
Theorem 1: soundness
Claim. If the algorithm returns , then is inductive over and . Hence holds in every state that a run reaches, over the rationals and over the integers, and is not reachable.
Proof. If is empty, the answer is : (I) holds because there is no initial state, (C) holds because no state satisfies , and violates it. An empty satisfies (C) with nothing to check, so dropping it changes nothing. Otherwise the solution of satisfies (I'), and for each remaining transition the chosen case of (C'); the row implies . By the "if" direction of Lemma 2, is inductive over . The target row gives . Normalizing to coprime integers multiplies it by a positive number, which changes none of this.
Every reachable state satisfies 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 ; its initial states and its steps are among the rational ones, so (I) and (C) hold for it too.
Theorem 2: completeness relative to
Claim. Suppose is not empty and some inequality is inductive over , false at , and has, for every nonempty transition with not empty, a cons multiplier . 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 , for the case cons with when is not empty, and for the case dis when is empty. Let and, over the dis transitions, , with if there are none. Let , and multiply , and every by , but not the . Every equality of (I') and of the cases is homogeneous in once is fixed, and so are the inequalities and ; they stay true. The dis rows become , and the target becomes . So the system 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.
Corollary: exactness over the rationals
With left as an unknown, the conditions of Lemma 2 describe exactly the inductive inequalities over of the template; this is Theorem 2 of Colon, Sankaranarayanan and Sipma. So the method with , which needs a solver for the nonlinear products , finds an inductive inequality false at whenever one exists. With a finite it is complete for the inequalities whose consecution multipliers lie in , and no more: for followed by the loop , the inequalities and are inductive, but every certificate of consecution has , because and force . The tests check this case with and with .
What completeness does not give
The result is about inductive inequalities over . An inequality can be inductive over but not over . For followed by the loop , the reachable states are and , and is inductive over , since an integer with has . Over , the state satisfies and the guard and goes to . Every rational inductive inequality holds at and , hence at by convexity, hence at by consecution. So no rational inductive inequality excludes , and the algorithm correctly returns "none" for it. Replacing the guard by its integer hull restores the integer invariant.
Complexity
There are choices of cases, one linear program each, plus emptiness checks. Each program has free unknowns , and one multiplier per row, unknowns in all, and constraints: equalities for initiation, per transition, and inequalities. So the time is , where 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 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, 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 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 . 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 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 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 followed by , the reachable states are 0 and 1, and is inductive over the integers. But 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 first; then is found. The tests check both.
- A finite misses invariants. For followed by for ever, is inductive, but its only consecution certificate has . With the algorithm returns "none" for the bad point ; with it finds .
- 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 followed by 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 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.
# 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 , 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag K23N8A Edit this page History Report an error Markdown