Algorithm Search⌘K

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
Properties
deterministicofflineiterative
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 nn rational variables. Its body is one relation R={(x,x′):Ax+A′x′≤b}R = \{(x, x') : A x + A' x' \le b\} between the state xx before a turn and the state x′x' after it, with mm rows. A guard and an assignment, while Gx≤g do x:=Ux+u\mathbf{while}\ Gx \le g\ \mathbf{do}\ x := Ux + u, give such a relation, and so does a nondeterministic body like x′≤x−1x' \le x - 1. A linear ranking function is a vector ρ\rho with numbers δ0\delta_0 and δ>0\delta > 0 such that every (x,x′)∈R(x, x') \in R has ρ⋅x≥δ0\rho \cdot x \ge \delta_0 and ρ⋅x−ρ⋅x′≥δ\rho \cdot x - \rho \cdot x' \ge \delta. The output is such a function, scaled so that δ≥1\delta \ge 1, 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 Q\mathbb{Q}. Over the integers the same question is coNP-complete, as Ben-Amram and Genaim proved.

The algorithm

  1. LINEAR-RANKING(A, A', b)
  2. 1find lambda1, lambda2 >= 0 with
  3. 2lambda1 A' = 0
  4. 3(lambda1 - lambda2) A = 0
  5. 4lambda2 (A + A') = 0
  6. 5lambda2 b <= -1
  7. 6if no solution exists then return none
  8. 7rho <- lambda2 A'
  9. 8return (rho, bound -lambda1 b, decrease -lambda2 b)

The multipliers λ1\lambda_1 and λ2\lambda_2 have one entry per row of the loop. λ1\lambda_1 is a certificate that ρ⋅x\rho \cdot x is bounded below: a nonnegative combination of the rows that mentions only xx (line L2) and equals −ρ⋅x≤λ1b-\rho \cdot x \le \lambda_1 b. λ2\lambda_2 is a certificate of the decrease: a combination that equals −ρ⋅x+ρ⋅x′≤λ2b-\rho \cdot x + \rho \cdot x' \le \lambda_2 b. Both must name the same ρ\rho, 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 while x≥y+1 do (x,y):=(x−1,y+1)\mathbf{while}\ x \ge y + 1\ \mathbf{do}\ (x, y) := (x - 1, y + 1). Over the variables (x,y,x′,y′)(x, y, x', y') it has five rows: the guard, and two rows for each of the equalities x′=x−1x' = x - 1 and y′=y+1y' = y + 1.

row Ax+A′x′≤bA x + A' x' \le b λ1\lambda_1 λ2\lambda_2
1 −x+y≤−1-x + y \le -1 1/21/2 0
2 −x+x′≤−1-x + x' \le -1 0 1/21/2
3 x−x′≤1x - x' \le 1 0 0
4 −y+y′≤1-y + y' \le 1 0 0
5 y−y′≤−1y - y' \le -1 0 1/21/2

The sum of the rows with weights λ2\lambda_2 is 12(−x+x′)+12(y−y′)≤−1\tfrac12(-x + x') + \tfrac12(y - y') \le -1, that is, ρ⋅x−ρ⋅x′≥1\rho \cdot x - \rho \cdot x' \ge 1 for ρ=(12,−12)\rho = (\tfrac12, -\tfrac12), which is λ2A′\lambda_2 A'. The sum with weights λ1\lambda_1 is 12(−x+y)≤−12\tfrac12(-x + y) \le -\tfrac12, that is, ρ⋅x≥12\rho \cdot x \ge \tfrac12, with no x′x' in it. So (x−y)/2(x - y)/2 is a ranking function with bound 1/21/2 and decrease 1. From (x,y)=(5,0)(x, y) = (5, 0) it takes the values 5/2,3/2,1/25/2, 3/2, 1/2 at the states that take a step, and the run stops after 3 steps, within the bound (5/2−1/2)/1+1=3(5/2 - 1/2)/1 + 1 = 3.

Correctness

The full proof is in the proof file.

  1. Soundness. From L3 and L4, ρ=λ2A′=−λ2A=−λ1A\rho = \lambda_2 A' = -\lambda_2 A = -\lambda_1 A. For (x,x′)∈R(x, x') \in R: ρ⋅x=−λ1(Ax+A′x′)≥−λ1b\rho \cdot x = -\lambda_1 (A x + A' x') \ge -\lambda_1 b by L2 and λ1≥0\lambda_1 \ge 0, and ρ⋅x−ρ⋅x′=−λ2(Ax+A′x′)≥−λ2b≥1\rho \cdot x - \rho \cdot x' = -\lambda_2 (A x + A' x') \ge -\lambda_2 b \ge 1 by L5.
  2. Completeness over Q\mathbb{Q}. Suppose (ρ,δ0,δ)(\rho, \delta_0, \delta) is a linear ranking function. If RR is empty, Farkas' lemma gives λ\lambda with λ[A  A′]=0\lambda [A \; A'] = 0 and λb<0\lambda b < 0; take λ1=λ2=λ\lambda_1 = \lambda_2 = \lambda, scaled. Otherwise the affine Farkas lemma, applied to the two implications "RR implies −ρ⋅x≤−δ0-\rho \cdot x \le -\delta_0" and "RR implies −ρ⋅x+ρ⋅x′≤−δ-\rho \cdot x + \rho \cdot x' \le -\delta", gives λ1\lambda_1 and λ2\lambda_2 that satisfy L2 to L4 and λ2b≤−δ<0\lambda_2 b \le -\delta < 0. Scale both by 1/min⁡(δ,1)1/\min(\delta, 1).
  3. Termination. With a ranking function, a run from x0x_0 has at most ⌊(ρ⋅x0−δ0)/δ⌋+1\lfloor(\rho \cdot x_0 - \delta_0)/\delta\rfloor + 1 steps, because ρ\rho drops by δ\delta on each step and is at least δ0\delta_0 before each step. This holds over Qn\mathbb{Q}^n and so over Zn\mathbb{Z}^n.
Proof: The Podelski-Rybalchenko linear program is sound and complete for linear ranking functions over the rationalsfull

Setting. A single-path linear loop over nn rational variables is a relation R={(x,x′)∈Qn×Qn:Ax+A′x′≤b}R = \{(x, x') \in \mathbb{Q}^n \times \mathbb{Q}^n : A x + A' x' \le b\}, where AA and A′A' are m×nm \times n matrices and b∈Qmb \in \mathbb{Q}^m. A run is a finite or infinite sequence x0,x1,…x_0, x_1, \ldots with (xj,xj+1)∈R(x_j, x_{j+1}) \in R for each step; the loop terminates when every run is finite. A linear ranking function is a vector ρ∈Qn\rho \in \mathbb{Q}^n with numbers δ0\delta_0 and δ>0\delta > 0 such that for every (x,x′)∈R(x, x') \in R

  • (B) ρ⋅x≥δ0\rho \cdot x \ge \delta_0, and
  • (D) ρ⋅x−ρ⋅x′≥δ\rho \cdot x - \rho \cdot x' \ge \delta.

Multipliers are row vectors in Qm\mathbb{Q}^m; λ≥0\lambda \ge 0 means that every entry is nonnegative. The algorithm solves the linear system

λ1,λ2≥0,λ1A′=0,(λ1−λ2)A=0,λ2(A+A′)=0,λ2b≤−1(∗)\lambda_1, \lambda_2 \ge 0, \quad \lambda_1 A' = 0, \quad (\lambda_1 - \lambda_2) A = 0, \quad \lambda_2 (A + A') = 0, \quad \lambda_2 b \le -1 \qquad (\ast)

and returns ρ=λ2A′\rho = \lambda_2 A', δ0=−λ1b\delta_0 = -\lambda_1 b and δ=−λ2b\delta = -\lambda_2 b, or "none" if (∗)(\ast) has no solution.

Lemma 1: affine Farkas lemma

Claim. Let My≤cMy \le c be a system over Qk\mathbb{Q}^k. (1) If it has a solution, then all its solutions satisfy w⋅y≤γw \cdot y \le \gamma if and only if λM=w\lambda M = w and λc≤γ\lambda c \le \gamma for some λ≥0\lambda \ge 0. (2) It has no solution if and only if λM=0\lambda M = 0 and λc<0\lambda c < 0 for some λ≥0\lambda \ge 0.

Proof. The "if" directions: in (1), w⋅y=λMy≤λc≤γw \cdot y = \lambda M y \le \lambda c \le \gamma; in (2), a solution would give 0=λMy≤λc<00 = \lambda M y \le \lambda c < 0. The "only if" directions follow from the duality theorem of linear programming, see the dual linear program: in (1), the problem "maximize w⋅yw \cdot y subject to My≤cMy \le c" is feasible and bounded by γ\gamma, so its dual "minimize λc\lambda c subject to λM=w\lambda M = w, λ≥0\lambda \ge 0" has an optimal solution with the same value, at most γ\gamma; in (2), with w=0w = 0, the dual is feasible (λ=0\lambda = 0) 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 λ\lambda is rational. This is Farkas' lemma in affine form. □\square

Theorem 1: soundness

Claim. If (λ1,λ2)(\lambda_1, \lambda_2) solves (∗)(\ast), then ρ=λ2A′\rho = \lambda_2 A' is a linear ranking function with δ0=−λ1b\delta_0 = -\lambda_1 b and δ=−λ2b≥1\delta = -\lambda_2 b \ge 1.

Proof. From λ2(A+A′)=0\lambda_2 (A + A') = 0, ρ=λ2A′=−λ2A\rho = \lambda_2 A' = -\lambda_2 A. From (λ1−λ2)A=0(\lambda_1 - \lambda_2) A = 0, also ρ=−λ1A\rho = -\lambda_1 A. Let (x,x′)∈R(x, x') \in R, so Ax+A′x′≤bA x + A' x' \le b.

(B): ρ⋅x=−λ1Ax=−λ1Ax−λ1A′x′=−λ1(Ax+A′x′)≥−λ1b=δ0\rho \cdot x = -\lambda_1 A x = -\lambda_1 A x - \lambda_1 A' x' = -\lambda_1 (A x + A' x') \ge -\lambda_1 b = \delta_0. The second step adds λ1A′x′=0\lambda_1 A' x' = 0, and the inequality uses λ1≥0\lambda_1 \ge 0.

(D): ρ⋅x−ρ⋅x′=−λ2Ax−λ2A′x′=−λ2(Ax+A′x′)≥−λ2b=δ≥1\rho \cdot x - \rho \cdot x' = -\lambda_2 A x - \lambda_2 A' x' = -\lambda_2 (A x + A' x') \ge -\lambda_2 b = \delta \ge 1, using λ2≥0\lambda_2 \ge 0 and the last row of (∗)(\ast). □\square

Theorem 2: completeness over the rationals

Claim. If the loop has a linear ranking function (ρ,δ0,δ)(\rho, \delta_0, \delta), then (∗)(\ast) has a solution.

Proof. Treat (x,x′)(x, x') as one vector of 2n2n unknowns, so RR is the solution set of [A   A′](x,x′)≤b[A \;\, A'] (x, x') \le b.

Case RR empty. By Lemma 1, part 2, there is λ≥0\lambda \ge 0 with λA=0\lambda A = 0, λA′=0\lambda A' = 0 and λb<0\lambda b < 0. Scale it by −1/(λb)-1/(\lambda b), so that λb=−1\lambda b = -1, and take λ1=λ2=λ\lambda_1 = \lambda_2 = \lambda. Every row of (∗)(\ast) holds: the three products are 0 and λ2b=−1\lambda_2 b = -1.

Case RR not empty. Condition (B) says that every point of RR satisfies (−ρ)⋅x+0⋅x′≤−δ0(-\rho) \cdot x + 0 \cdot x' \le -\delta_0. By Lemma 1, part 1, there is λ1≥0\lambda_1 \ge 0 with λ1A=−ρ\lambda_1 A = -\rho, λ1A′=0\lambda_1 A' = 0 and λ1b≤−δ0\lambda_1 b \le -\delta_0. Condition (D) says that every point of RR satisfies (−ρ)⋅x+ρ⋅x′≤−δ(-\rho) \cdot x + \rho \cdot x' \le -\delta. By Lemma 1, part 1, there is λ2≥0\lambda_2 \ge 0 with λ2A=−ρ\lambda_2 A = -\rho, λ2A′=ρ\lambda_2 A' = \rho and λ2b≤−δ\lambda_2 b \le -\delta. Then λ1A′=0\lambda_1 A' = 0; (λ1−λ2)A=−ρ+ρ=0(\lambda_1 - \lambda_2) A = -\rho + \rho = 0; λ2(A+A′)=−ρ+ρ=0\lambda_2 (A + A') = -\rho + \rho = 0; and λ2b≤−δ<0\lambda_2 b \le -\delta < 0. Multiply both λ1\lambda_1 and λ2\lambda_2 by s=1/min⁡(δ,1)>0s = 1/\min(\delta, 1) > 0. The equalities are homogeneous and stay true, the multipliers stay nonnegative, and λ2b≤−sδ≤−1\lambda_2 b \le -s\delta \le -1. □\square

Corollary: the decision procedure

The algorithm returns a function exactly when a linear ranking function exists over Q\mathbb{Q} (Theorems 1 and 2), and the exact simplex method decides whether (∗)(\ast) has a solution. The system has 2m2m unknowns and 3n3n 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 (ρ,δ0,δ)(\rho, \delta_0, \delta) is a linear ranking function, every run from x0x_0 has at most ⌊(ρ⋅x0−δ0)/δ⌋+1\lfloor (\rho \cdot x_0 - \delta_0) / \delta \rfloor + 1 steps, over Qn\mathbb{Q}^n and over Zn\mathbb{Z}^n.

Proof. Let x0,…,xtx_0, \ldots, x_t be a run with t≥1t \ge 1 steps. By (D), ρ⋅xt−1≤ρ⋅x0−(t−1)δ\rho \cdot x_{t-1} \le \rho \cdot x_0 - (t - 1) \delta, and by (B) applied to the step (xt−1,xt)(x_{t-1}, x_t), ρ⋅xt−1≥δ0\rho \cdot x_{t-1} \ge \delta_0. So (t−1)δ≤ρ⋅x0−δ0(t - 1) \delta \le \rho \cdot x_0 - \delta_0. An integer run is a rational run, so the bound also holds over Zn\mathbb{Z}^n. □\square

What the theorems do not give

Termination does not imply a linear ranking function. The loop x≥0x \ge 0, x′=x+yx' = x + y, y′=y−1y' = y - 1 terminates from every rational state. The value of yy after jj steps is y0−jy_0 - j. So after j0=max⁡(0,⌈y0⌉+1)j_0 = \max(0, \lceil y_0 \rceil + 1) steps y≤−1y \le -1, and from then on each step adds y≤−1y \le -1 to xx. Since a step needs x≥0x \ge 0, at most xj0+1x_{j_0} + 1 more steps follow. But no ρ=(p,q)\rho = (p, q) works. For (D), ρ⋅x−ρ⋅x′=−py+q\rho \cdot x - \rho \cdot x' = -p y + q must be at least δ>0\delta > 0 for every yy, since yy is free; so p=0p = 0 and q>0q > 0. For (B), ρ⋅x=qy\rho \cdot x = q y must be bounded below for all yy, which fails for q>0q > 0. So (∗)(\ast) has no solution, and the tests check it.

A rational answer is about rational runs. Theorem 2 is completeness over Q\mathbb{Q}. A loop can terminate over Z\mathbb{Z}, and even have an integer linear ranking function, while it does not terminate over Q\mathbb{Q}. For the guard 2x≥1∧2x≤12x \ge 1 \wedge 2x \le 1 with x′=xx' = x, no integer state enters the loop, so every function is a ranking function over Z\mathbb{Z}, but the rational state x=1/2x = 1/2 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. ■\blacksquare

Complexity

Building the system takes O(mn)O(mn) time. It has 2m2m nonnegative unknowns, 3n3n equalities and one inequality, and one exact linear program solves it, in time LL. 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 3n+13n + 1 rows and O(m+n)O(m + n) 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 Q\mathbb{Q}, "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 Z\mathbb{Z} 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 y≥1y \ge 1 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 2x≥1∧2x≤12x \ge 1 \wedge 2x \le 1, x′=xx' = x never runs over the integers, so every function ranks it there, but the rational state 1/21/2 loops for ever and the method says "none". The loop x≥0x \ge 0, x:=10−2xx := 10 - 2x terminates from every integer, since the distance to 10/310/3 doubles each step, but 10/310/3 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 x≥0x \ge 0, x′=x+yx' = x + y, y′=y−1y' = y - 1 terminates from every rational state, but ρ⋅x−ρ⋅x′=−py+q\rho \cdot x - \rho \cdot x' = -p y + q must be positive for every yy, which forces ρ=(0,q)\rho = (0, q), and then ρ⋅x=qy\rho \cdot x = q y is not bounded below. The tests check that every ρ\rho in {−3,…,3}2\{-3, \ldots, 3\}^2 fails.
  • Forgetting the bound. A function that only decreases, such as xx for x′=x−1x' = x - 1 without a guard, proves nothing; λ1\lambda_1 is there to prove the floor.
  • Decrease by a positive amount, not just down. Over Q\mathbb{Q}, decreasing by ever smaller amounts need not stop. The method asks for a fixed δ>0\delta > 0, 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.

fraclp.pyI0RawGitHub
# 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

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

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