Algorithmresearch
Linear ranking function synthesis
Also called Podelski-Rybalchenko ranking functions.
Decides whether a simple linear loop has a linear ranking function and finds one, by linear programming.
- Time
- O(m n + L) worst
- Space
- O(n (m + n)) extra
- Where
- L = the cost of one exact linear program with 2m unknowns and 3n + 1 constraints; m = the number of rows of the loop relation; n = the number of variables
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andreas Podelski, Andrey Rybalchenko, 2004
Linear ranking function synthesis decides whether a loop of the form "while some linear constraints hold, update the variables linearly" has a linear function of the variables that is bounded below and drops by at least 1 on every turn, and finds one if it exists. Podelski and Rybalchenko showed that the whole question is one linear program: two vectors of nonnegative multipliers, three matrix equations and one inequality, obtained with Farkas' lemma. A solution gives the ranking function directly, which is a termination proof; no solution means that no linear ranking function exists over the rationals.
In plain words
To show that a loop stops, find a number that you can compute from the variables, that goes down by at least one on every turn, and that can never go below some floor. It can only go down so many times, so the loop must stop. This page looks for the simplest kind of such number, a weighted sum of the variables. The conditions "it goes down on every turn" and "it stays above the floor" must follow from the loop's own conditions. An old result says this happens exactly when the needed inequality is a sum of the loop's inequalities with nonnegative weights. So the search for the weights of the function becomes a search for those other weights, and that is a standard problem with an exact answer.
The problem
The loop is a single-path linear loop over rational variables. Its body is one relation between the state before a turn and the state after it, with rows. A guard and an assignment, , give such a relation, and so does a nondeterministic body like . A linear ranking function is a vector with numbers and such that every has and . The output is such a function, scaled so that , or "none".
Termination of general programs is undecidable, by the halting problem and Rice's theorem, so every method is incomplete for some programs. This one is complete for its class: it decides in polynomial time whether a linear ranking function exists over . Over the integers the same question is coNP-complete, as Ben-Amram and Genaim proved.
The algorithm
LINEAR-RANKING(A, A', b)- 1
find lambda1, lambda2 >= 0 with - 2
lambda1 A' = 0 - 3
(lambda1 - lambda2) A = 0 - 4
lambda2 (A + A') = 0 - 5
lambda2 b <= -1 - 6
if no solution exists then return none - 7
rho <- lambda2 A' - 8
return (rho, bound -lambda1 b, decrease -lambda2 b)
The multipliers and have one entry per row of the loop. is a certificate that is bounded below: a nonnegative combination of the rows that mentions only (line L2) and equals . is a certificate of the decrease: a combination that equals . Both must name the same , which is line L3 together with line L4, and the decrease must be positive, which is line L5 after scaling. The code solves the system with an exact two-phase simplex method over the rationals and minimizes the sum of the multipliers to keep the numbers small.
Example
The loop is . Over the variables it has five rows: the guard, and two rows for each of the equalities and .
| row | |||
|---|---|---|---|
| 1 | 0 | ||
| 2 | 0 | ||
| 3 | 0 | 0 | |
| 4 | 0 | 0 | |
| 5 | 0 |
The sum of the rows with weights is , that is, for , which is . The sum with weights is , that is, , with no in it. So is a ranking function with bound and decrease 1. From it takes the values at the states that take a step, and the run stops after 3 steps, within the bound .
Correctness
The full proof is in the proof file.
- Soundness. From L3 and L4, . For : by L2 and , and by L5.
- Completeness over . Suppose is a linear ranking function. If is empty, Farkas' lemma gives with and ; take , scaled. Otherwise the affine Farkas lemma, applied to the two implications " implies " and " implies ", gives and that satisfy L2 to L4 and . Scale both by .
- Termination. With a ranking function, a run from has at most steps, because drops by on each step and is at least before each step. This holds over and so over .
Proof: The Podelski-Rybalchenko linear program is sound and complete for linear ranking functions over the rationalsfull
Setting. A single-path linear loop over rational variables is a relation , where and are matrices and . A run is a finite or infinite sequence with for each step; the loop terminates when every run is finite. A linear ranking function is a vector with numbers and such that for every
- (B) , and
- (D) .
Multipliers are row vectors in ; means that every entry is nonnegative. The algorithm solves the linear system
and returns , and , or "none" if has no solution.
Lemma 1: affine Farkas lemma
Claim. Let be a system over . (1) If it has a solution, then all its solutions satisfy if and only if and for some . (2) It has no solution if and only if and for some .
Proof. The "if" directions: in (1), ; in (2), a solution would give . The "only if" directions follow from the duality theorem of linear programming, see the dual linear program: in (1), the problem "maximize subject to " is feasible and bounded by , so its dual "minimize subject to , " has an optimal solution with the same value, at most ; in (2), with , the dual is feasible () and the primal is infeasible, so the dual is unbounded below. The data are rational and an optimal or unbounded direction can be taken at a basic solution, so is rational. This is Farkas' lemma in affine form.
Theorem 1: soundness
Claim. If solves , then is a linear ranking function with and .
Proof. From , . From , also . Let , so .
(B): . The second step adds , and the inequality uses .
(D): , using and the last row of .
Theorem 2: completeness over the rationals
Claim. If the loop has a linear ranking function , then has a solution.
Proof. Treat as one vector of unknowns, so is the solution set of .
Case empty. By Lemma 1, part 2, there is with , and . Scale it by , so that , and take . Every row of holds: the three products are 0 and .
Case not empty. Condition (B) says that every point of satisfies . By Lemma 1, part 1, there is with , and . Condition (D) says that every point of satisfies . By Lemma 1, part 1, there is with , and . Then ; ; ; and . Multiply both and by . The equalities are homogeneous and stay true, the multipliers stay nonnegative, and .
Corollary: the decision procedure
The algorithm returns a function exactly when a linear ranking function exists over (Theorems 1 and 2), and the exact simplex method decides whether has a solution. The system has unknowns and equalities and one inequality, so by the polynomial algorithms for linear programming the existence of a linear ranking function over the rationals is decidable in polynomial time.
Theorem 3: a ranking function proves termination
Claim. If is a linear ranking function, every run from has at most steps, over and over .
Proof. Let be a run with steps. By (D), , and by (B) applied to the step , . So . An integer run is a rational run, so the bound also holds over .
What the theorems do not give
Termination does not imply a linear ranking function. The loop , , terminates from every rational state. The value of after steps is . So after steps , and from then on each step adds to . Since a step needs , at most more steps follow. But no works. For (D), must be at least for every , since is free; so and . For (B), must be bounded below for all , which fails for . So has no solution, and the tests check it.
A rational answer is about rational runs. Theorem 2 is completeness over . A loop can terminate over , and even have an integer linear ranking function, while it does not terminate over . For the guard with , no integer state enters the loop, so every function is a ranking function over , but the rational state loops for ever. So "none" from this algorithm does not mean that an integer program fails to terminate, and it does not even mean that it has no integer linear ranking function. Theorem 1 does transfer: a rational ranking function is also one for the integer runs.
Complexity
Building the system takes time. It has nonnegative unknowns, equalities and one inequality, and one exact linear program solves it, in time . Linear programming is polynomial with the ellipsoid method or interior-point methods, so the problem is in polynomial time over the rationals; the simplex method of the code is exponential in the worst case but fast at these sizes. The tableau has rows and columns.
On 500 random loops of the tests (seed 77, two variables, one or two random guard rows, a random affine update with small integer coefficients), 158 got a ranking function and 342 got "none"; for 80 of the 342, an integer run from a sampled start state repeated a state, so the loop does not terminate.
Properties
- A decision procedure. For single-path linear loops over , "none" is a proof that no linear ranking function exists, not a timeout.
- Certificates both ways. A solution is a checkable certificate of termination. When the system has no solution, Farkas' lemma applied to it gives a certificate of that too.
- Nondeterminism is free. The relation need not be a function: any polyhedron of pairs works, so havoc, bounds on inputs and abstracted operations fit.
- Only one phase. The function must decrease on every turn from every state. Loops whose progress has phases need a lexicographic or multiphase function.
Variants and improvements
- Lexicographic ranking functions. A tuple of linear functions, ordered by the lexicographic order, proves termination of loops with several paths or phases. Ben-Amram and Genaim give complete PTIME synthesis over the rationals for these too.
- Integer loops. Over one first replaces the relation by its integer hull, which can be exponentially larger; Ben-Amram and Genaim show that the integer problem is coNP-complete.
- Many paths. For a program with several paths, Terminator by Cook, Podelski and Rybalchenko finds a path that is not yet covered, synthesizes a ranking function for it with this method, and checks the transition invariant built from all of them.
- Earlier methods. Colon and Sipma synthesized linear ranking functions with polyhedral cones in 2001. Bagnara, Mesnard, Pescetti and Zaffanella compare the complete methods.
- With invariants. A loop often needs an invariant to terminate, such as that comes from the code before it. Add it to the guard first, or find it together with the ranking function with the constraint-based method, which uses the same Farkas encoding.
When to use it
Use it inside a termination prover, on each loop or each path a model checker finds, after strengthening the loop with known invariants. It is cheap, exact and gives a certificate. If it says "none", try a lexicographic or multiphase ranking function, look for a missing invariant, or for integer programs try the integer hull. For whole programs with recursion, size-change termination is a different decidable method.
Pitfalls
- Rational is not integer. The loop , never runs over the integers, so every function ranks it there, but the rational state loops for ever and the method says "none". The loop , terminates from every integer, since the distance to doubles each step, but is a rational fixed point. A "none" says nothing about integer termination. A function that is found does prove integer termination.
- Termination without a linear ranking function. The loop , , terminates from every rational state, but must be positive for every , which forces , and then is not bounded below. The tests check that every in fails.
- Forgetting the bound. A function that only decreases, such as for without a guard, proves nothing; is there to prove the floor.
- Decrease by a positive amount, not just down. Over , decreasing by ever smaller amounts need not stop. The method asks for a fixed , scaled to 1.
- Reading the tests as a proof. The linear program is exact. The tests also sample integer and rational transitions and run the loop; those checks are bounded, 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
# 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
ranking_function_synthesis.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ranking-function-synthesis/. The authors are listed in prov/HA12CT.jsonl.
"""Linear ranking functions for single-path linear loops (Podelski and
Rybalchenko).
A loop over n rational variables is one relation between the state x
before and the state x' after one turn, given as rows (a, b) with
len(a) = 2n, each meaning a[:n] . x + a[n:] . x' <= b. Write A and A' for
the two halves of the rows. The loop is "while the rows can be satisfied,
move to some x' that satisfies them".
linear_ranking(n, rows) solves one linear program in the multipliers
lambda1, lambda2 >= 0 and returns (rho, bound, decrease) with Fraction
entries, or None. When it returns, every rational (x, x') of the relation
satisfies rho . x >= bound and rho . x - rho . x' >= decrease >= 1. It
returns None exactly when no linear ranking function exists over the
rationals. Cost: one linear program with 2m unknowns and 3n + 1 rows for m
rows of the loop; polynomial in theory, the simplex method in practice.
"""
from fractions import Fraction
from fraclp import lp_solve
def loop_rows(n, guard, update):
"""The rows of 'while guard do 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 linear_ranking(n, rows):
"""A linear ranking function (rho, bound, decrease) or None."""
m = len(rows)
a_eq, b_eq = [], []
# Unknowns: lambda1 (m entries), then lambda2 (m entries).
# @line L1 the multipliers lambda1, lambda2 >= 0
for k in range(n):
# @line L2 lambda1 A' = 0
a_eq.append([a[n + k] for a, _ in rows] + [0] * m)
b_eq.append(0)
# @line L3 (lambda1 - lambda2) A = 0
a_eq.append([a[k] for a, _ in rows] + [-a[k] for a, _ in rows])
b_eq.append(0)
# @line L4 lambda2 (A + A') = 0
a_eq.append([0] * m + [a[k] + a[n + k] for a, _ in rows])
b_eq.append(0)
# @line L5 lambda2 b <= -1
a_ub = [[0] * m + [b for _, b in rows]]
b_ub = [-1]
# Minimizing the sum of the multipliers keeps the numbers small.
status, lam, _ = lp_solve([1] * (2 * m), a_eq, b_eq, a_ub, b_ub)
if status != "optimal":
# @line L6 no multipliers: no linear ranking function
return None
lam1, lam2 = lam[:m], lam[m:]
# @line L7 rho = lambda2 A'
rho = tuple(sum(l * a[n + k] for l, (a, _) in zip(lam2, rows)) for k in range(n))
# @line L8 the bound -lambda1 b and the decrease -lambda2 b
bound = -sum(l * b for l, (_, b) in zip(lam1, rows))
decrease = -sum(l * b for l, (_, b) in zip(lam2, rows))
return rho, bound, decrease
def value(rho, x):
"""rho . x as an exact rational."""
return sum(Fraction(r) * v for r, v in zip(rho, x))
test_ranking_function_synthesis.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ranking-function-synthesis/. The authors are listed in prov/HA12CT.jsonl.
import itertools
import random
import unittest
from fractions import Fraction
from fraclp import lp_solve
from ranking_function_synthesis import linear_ranking, loop_rows, value
def dot(a, x):
return sum(Fraction(ai) * xi for ai, xi in zip(a, x))
def step(guard, update, x):
"""The successor of x, or None when the guard is false."""
if not all(dot(a, x) <= b for a, b in guard):
return None
return tuple(dot(uk, x) + ck for uk, ck in update)
def primal_is_ranking(n, rows, rho):
"""The oracle: with exact linear programs over the relation, is
x -> rho . x bounded below and decreasing by some delta > 0? Returns
(bound, delta) or None."""
a_ub = [a for a, _ in rows]
b_ub = [b for _, b in rows]
st, _, low = lp_solve(list(rho) + [0] * n, a_ub=a_ub, b_ub=b_ub, free=range(2 * n))
if st == "infeasible":
return (0, 1)
if st == "unbounded":
return None
st, _, dec = lp_solve(list(rho) + [-r for r in rho], a_ub=a_ub, b_ub=b_ub, free=range(2 * n))
if st != "optimal" or dec <= 0:
return None
return (low, dec)
def check_samples(test, guard, update, res, points):
rho, bound, dec = res
test.assertGreaterEqual(dec, 1)
for x in points:
y = step(guard, update, x)
if y is None:
continue
test.assertGreaterEqual(value(rho, x), bound)
test.assertGreaterEqual(value(rho, x) - value(rho, y), dec)
BOX = list(itertools.product(range(-5, 6), repeat=2))
class TestPage(unittest.TestCase):
def test_page_example(self):
# while x >= y + 1: (x, y) := (x - 1, y + 1)
guard = [([-1, 1], -1)]
update = [([1, 0], -1), ([0, 1], 1)]
res = linear_ranking(2, loop_rows(2, guard, update))
self.assertEqual(res, ((Fraction(1, 2), Fraction(-1, 2)), Fraction(1, 2), Fraction(1)))
check_samples(self, guard, update, res, BOX)
def test_terminating_without_linear_ranking(self):
# x >= 0: (x, y) := (x + y, y - 1). Every run stops, but no linear
# function decreases on every step.
guard = [([-1, 0], 0)]
update = [([1, 1], 0), ([0, 1], -1)]
rows = loop_rows(2, guard, update)
self.assertIsNone(linear_ranking(2, rows))
for x in BOX:
for _ in range(60):
y = step(guard, update, x)
if y is None:
break
x = y
self.assertIsNone(step(guard, update, x))
for rho in itertools.product(range(-3, 4), repeat=2):
self.assertIsNone(primal_is_ranking(2, rows, rho))
def test_nonterminating(self):
# x >= 0: x := x has a fixed point; x >= 0: x := x + 1 runs away.
for update in ([([1], 0)], [([1], 1)]):
self.assertIsNone(linear_ranking(1, loop_rows(1, [([-1], 0)], update)))
def test_integer_trap(self):
# 2x >= 1 and 2x <= 1: x := x. No integer state enters the loop, so
# every integer run stops at once. Over the rationals x = 1/2 loops
# for ever, so there is no rational ranking function.
guard = [([-2], -1), ([2], 1)]
rows = loop_rows(1, guard, [([1], 0)])
self.assertIsNone(linear_ranking(1, rows))
self.assertTrue(all(step(guard, [([1], 0)], (x,)) is None for x in range(-20, 21)))
self.assertEqual(step(guard, [([1], 0)], (Fraction(1, 2),)), (Fraction(1, 2),))
def test_rational_fixed_point(self):
# x >= 0: x := 10 - 2x. Integer runs stop, since |x - 10/3| doubles,
# but the rational state 10/3 is a fixed point.
guard, update = [([-1], 0)], [([-2], 10)]
self.assertIsNone(linear_ranking(1, loop_rows(1, guard, update)))
self.assertEqual(step(guard, update, (Fraction(10, 3),)), (Fraction(10, 3),))
def test_nondeterministic_relation(self):
# x >= 0 and x' <= x - 1: any smaller value.
res = linear_ranking(1, [([-1, 0], 0), ([-1, 1], -1)])
self.assertEqual(res, ((Fraction(1),), Fraction(0), Fraction(1)))
def test_empty_relation(self):
rows = loop_rows(1, [([-1], -1), ([1], 0)], [([1], 1)])
rho, _, dec = linear_ranking(1, rows)
self.assertEqual((rho, dec), ((Fraction(0),), Fraction(1)))
def rand_loop(rng):
guard = []
for _ in range(rng.randint(1, 2)):
guard.append(([rng.randint(-2, 2), rng.randint(-2, 2)], rng.randint(-3, 3)))
update = []
for k in range(2):
u = [0, 0]
u[k] = rng.choice([1, 1, 1, 0, -1, 2])
if rng.random() < 0.4:
u[1 - k] = rng.choice([-1, 1])
update.append((u, rng.randint(-2, 2)))
return guard, update
def rational_points(rng, count=40):
return [(Fraction(rng.randint(-15, 15), rng.randint(1, 3)), Fraction(rng.randint(-15, 15), rng.randint(1, 3))) for _ in range(count)]
def cycles(guard, update, x, limit=40):
"""True if the integer run from x repeats a state within limit steps."""
seen = {x}
for _ in range(limit):
x = step(guard, update, x)
if x is None:
return False
if x in seen:
return True
seen.add(x)
return False
GRID = [rho for rho in itertools.product(range(-2, 3), repeat=2) if rho != (0, 0)]
class TestRandom(unittest.TestCase):
def test_random_loops(self):
rng = random.Random(77)
found = looping = 0
for _ in range(500):
guard, update = rand_loop(rng)
rows = loop_rows(2, guard, update)
res = linear_ranking(2, rows)
if any(cycles(guard, update, x) for x in BOX[::7]):
# A loop that does not terminate has no ranking function.
looping += 1
self.assertIsNone(res)
if res is None:
# The oracle: no small integer direction is a ranking function.
for rho in GRID:
self.assertIsNone(primal_is_ranking(2, rows, rho))
continue
found += 1
rho, bound, dec = res
exact = primal_is_ranking(2, rows, rho)
self.assertIsNotNone(exact)
self.assertGreaterEqual(exact[0], bound)
self.assertGreaterEqual(exact[1], dec)
check_samples(self, guard, update, res, BOX + rational_points(rng))
# Each integer run is at most (rho . x0 - bound) / dec + 1 steps.
for x in BOX[::5]:
limit = max(0, (value(rho, x) - bound) / dec) + 1
steps = 0
while True:
y = step(guard, update, x)
if y is None:
break
x, steps = y, steps + 1
self.assertLessEqual(steps, limit)
self.assertGreater(found, 100)
self.assertGreater(looping, 50)
if __name__ == "__main__":
unittest.main()
History
Floyd's method of 1967 already proved termination with a function into a well-founded set. Colon and Sipma gave an algorithm for linear ranking functions with polyhedral cones in 2001. Podelski and Rybalchenko gave the linear-programming characterization at VMCAI 2004 and proved it complete for single-path linear loops over the rationals. They built on it in the same year with transition invariants, and in 2006 with Cook in the Terminator tool, which proved termination of Windows device drivers. Ben-Amram and Genaim settled the integer case in 2014: deciding whether a linear ranking function exists over the integers is coNP-complete.
References
- 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 theorem with the multipliers lambda1, lambda2 and the conditions lambda1 A' = 0, (lambda1 - lambda2) A = 0, lambda2 (A + A') = 0, lambda2 b < 0, and the construction of the ranking function and its bound
- Amir M. Ben-Amram and Samir Genaim, Ranking functions for linear-constraint loops, Journal of the ACM 61(4), 2014, article 26, the proof that the existence of a linear ranking function over the integers is coNP-complete, and the PTIME result over the rationals
- Michael A. Colon and Henny B. Sipma, Synthesis of linear ranking functions, Proceedings of TACAS 2001, LNCS 2031, pp. 67 to 81, the earlier synthesis method with polyhedral cones
- Byron Cook, Andreas Podelski and Andrey Rybalchenko, Termination proofs for systems code, Proceedings of PLDI 2006, the Terminator tool, which calls a ranking function synthesizer on each path it finds
- Roberto Bagnara, Fred Mesnard, Andrea Pescetti and Enea Zaffanella, The automatic synthesis of linear ranking functions, the complete unabridged version, arXiv 1004.0944, the comparison of the Podelski-Rybalchenko method with the other complete methods for linear ranking functions
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 HA12CT Edit this page History Report an error Markdown