Algorithm Search⌘K

Algorithmadvanced

Point algebra consistency algorithm

Also called van Beek's algorithm.

Decides consistency of a point algebra network, including not-equal labels, with strongly connected components of the order graph, and returns a solution, in O(n^2) time.

Time
O(n + e) worst
Space
O(n + e) extra
Where
e = the number of labelled pairs; n = the number of points
Properties
deterministicexactnot in placeofflineiterative
Origin
Peter van Beek, Peter B. Ladkin, Roger D. Maddux, 1990

The point algebra consistency algorithm decides whether a network of point algebra constraints has a solution, and it returns one. A label on a pair of points is a union of <<, == and >>, so it can say ≤\le, ≥\ge or ≠\ne. The algorithm builds a directed graph with an edge for each label that says "at most", finds its strongly connected components, rejects the network if a label inside one component forbids equality, and numbers the components in topological order. It runs in O(n+e)O(n + e) time, which is O(n2)O(n^2), against O(n3)O(n^3) for algebraic closure, which also decides this problem. The component step is the plain graph algorithm; what this page adds is the reduction from labels to edges and the test for ≠\ne.

In plain words

Each constraint compares two moments in time. "a is at most b" is an arrow from a to b. If the arrows go round in a circle, every moment on the circle must be the same moment, so they collapse to one. If a constraint inside such a circle says "these two are different" or "this one is strictly earlier", there is no answer. Otherwise the collapsed groups can be put in a line that follows all the arrows, and giving each group its position in that line gives times that keep every constraint, including the "different" ones, because different groups get different times.

The problem

The input is a network on the points 0,…,n−10, \ldots, n-1 with a label Rij⊆{<,=,>}R_{ij} \subseteq \{<, =, >\} on some pairs i<ji < j. A missing pair has the universal label, and RjiR_{ji} is the converse of RijR_{ij}, which swaps << and >>. There are 23=82^3 = 8 labels: ∅\emptyset, <<, ==, >>, ≤\le, ≥\ge, ≠\ne and the universal label. The question is whether there are numbers v0,…,vn−1v_0, \ldots, v_{n-1} with sign(vi−vj)∈Rij\mathrm{sign}(v_i - v_j) \in R_{ij} for every pair; if so, return them. The cost is counted on a word-RAM, in the number of points nn and of labelled pairs e≤(n2)e \le \binom{n}{2}.

The algorithm

  1. PA-CONSISTENCY(n, R) ▷ R[i][j] ⊆ {<, =, >}, with R[j][i] = conv R[i][j]
  2. 1if some R[i][j] = ∅ then return INCONSISTENT
  3. 2G ← the directed graph on the points 0 .. n-1 with no edges
  4. 3for each ordered pair (i, j) with R[i][j] ⊆ {<, =} do add the edge i → j
  5. 4C ← the strongly connected components of G, numbered in topological order
  6. 5for each labelled pair {i, j} with C(i) = C(j) do
  7. 6if = ∉ R[i][j] then return INCONSISTENT
  8. 7return v with v[i] ← the number of C(i)

Line L3 reads each label in both directions. The labels <<, ≤\le and == give an edge from ii to jj, and >>, ≥\ge and == give an edge from jj to ii; so == gives edges both ways. The labels ≠\ne and universal give no edge, because they do not order the points. Line L4 uses Tarjan's algorithm, which outputs the components in reverse topological order. Line L6 catches both kinds of contradiction: a strict << along a cycle of ≤\le, and a ≠\ne between two points that a cycle forces to be equal.

Example

Take 4 points with x0≤x1x_0 \le x_1, x1≤x2x_1 \le x_2, x0≥x2x_0 \ge x_2, x2≠x3x_2 \ne x_3 and x0≥x3x_0 \ge x_3.

step what happens
L3 edges 0→10 \to 1, 1→21 \to 2, 2→02 \to 0 (from x0≥x2x_0 \ge x_2) and 3→03 \to 0 (from x0≥x3x_0 \ge x_3); no edge for x2≠x3x_2 \ne x_3
L4 components {0,1,2}\{0, 1, 2\} and {3}\{3\}, with {3}\{3\} first in topological order
L5, L6 the pairs {0,1}\{0, 1\}, {1,2}\{1, 2\} and {0,2}\{0, 2\} are inside one component; each label contains ==
L7 v=(1,1,1,0)v = (1, 1, 1, 0)

The answer x0=x1=x2=1x_0 = x_1 = x_2 = 1 and x3=0x_3 = 0 satisfies x2≠x3x_2 \ne x_3 because the two points are in different components. If we add x1=x3x_1 = x_3, line L3 adds the edges 1→31 \to 3 and 3→13 \to 1, all four points form one component, and line L6 finds the label ≠\ne of {2,3}\{2, 3\} inside it. The network is then inconsistent.

Correctness

If the algorithm rejects, there is no solution: along a directed cycle of ≤\le edges every solution has equal values, which the label checked at line L6 forbids. If it accepts, take any labelled pair. Inside one component the two values are equal and the label allows ==. In different components the values differ, and if the label did not allow the order that vv gives, the label in the other direction would be inside {<,=}\{<, =\}, so there would be an edge that points against the topological order, which is impossible. So vv is a solution. The full proof is in the proof file of this page.

Proof: The component test decides point algebra consistencyfull

The input is a point algebra network on the points 0,…,n−10, \ldots, n-1: each pair i<ji < j has a label Rij⊆{<,=,>}R_{ij} \subseteq \{<, =, >\}, a missing pair has the universal label, and Rji=Rij⌣R_{ji} = R_{ij}^{\smile}, where the converse swaps << and >> and keeps ==. A solution is a map vv from the points to the real numbers with sign(vi−vj)\mathrm{sign}(v_i - v_j) in RijR_{ij} for every pair. The graph GG of line L3 has the edge i→ji \to j exactly when RijR_{ij} is non-empty and Rij⊆{<,=}R_{ij} \subseteq \{<, =\}.

Lemma 1 (edges are order constraints). If i→ji \to j is an edge of GG, every solution has vi≤vjv_i \le v_j. If ii and jj are in the same strongly connected component, every solution has vi=vjv_i = v_j.

Proof. The label of (i,j)(i, j) allows only << and ==, so vi≤vjv_i \le v_j. In one component there is a directed path from ii to jj and one from jj to ii. Along each path the values do not decrease, so vi≤vj≤viv_i \le v_j \le v_i. □\square

Lemma 2 (the numbering). Tarjan's algorithm numbers the components so that every edge u→wu \to w of GG has comp(u)≥comp(w)\mathrm{comp}(u) \ge \mathrm{comp}(w), with equality exactly when uu and ww are in the same component. So vu=t−comp(u)v_u = t - \mathrm{comp}(u) at line L7, where tt is the largest number, gives vu≤vwv_u \le v_w on every edge, with vu<vwv_u < v_w when the components differ.

Proof. Tarjan's algorithm outputs a component only after all components that can be reached from it, so a component reached by an edge gets a smaller number. This is the standard property of the algorithm; see Tarjan's algorithm. □\square

Theorem. The algorithm returns INCONSISTENT exactly when the network has no solution. When it returns vv, vv is a solution with integer values in 0,…,n−10, \ldots, n-1.

Proof. Suppose it returns INCONSISTENT. At line L1 some label is empty, and no value of sign(vi−vj)\mathrm{sign}(v_i - v_j) is allowed. At line L6 the points ii and jj are in the same component and =∉Rij= \notin R_{ij}; by Lemma 1 every solution has vi=vjv_i = v_j, which the label forbids. In both cases there is no solution.

Suppose it returns vv, and take a pair (i,j)(i, j) with the label r=Rijr = R_{ij}, which is not empty.

  • If ii and jj are in the same component, vi=vjv_i = v_j, and line L6 checked that =∈r= \in r.
  • Otherwise the components differ and vi≠vjv_i \ne v_j, because each component gets its own number. Say vi<vjv_i < v_j. If <∉r< \notin r, then r⊆{=,>}r \subseteq \{=, >\}, so Rji=r⌣⊆{<,=}R_{ji} = r^{\smile} \subseteq \{<, =\} and j→ij \to i is an edge of GG. By Lemma 2, vj<viv_j < v_i, a contradiction. So <∈r< \in r. The case vi>vjv_i > v_j is the same with the roles of ii and jj swapped.

So every label holds. The values are t−comp(u)t - \mathrm{comp}(u) with 0≤comp(u)≤t<n0 \le \mathrm{comp}(u) \le t < n. ■\blacksquare

Termination and cost. Line L1 reads each label once. Line L3 adds at most two edges for each labelled pair, so GG has at most e≤(n2)e \le \binom{n}{2} edges, and Tarjan's algorithm takes O(n+e)O(n + e) time. Lines L5 and L6 read each label once more, and line L7 takes O(n)O(n) time. The total is O(n+e)=O(n2)O(n + e) = O(n^2).

Complexity

Time. Lines L1 and L3 read each labelled pair once and add at most 2 edges per pair, so GG has O(e)O(e) edges. Tarjan's algorithm takes O(n+e)O(n + e) time. Lines L5 to L7 take O(n+e)O(n + e) more. The total is O(n+e)=O(n2)O(n + e) = O(n^2), which is linear in the size of the input when the network is given as a complete matrix.

Space. The graph and the component numbers take O(n+e)O(n + e) words.

Finding the minimal labels, the set of base relations of each pair that occur in some solution, is harder: van Beek (1992) needs O(n4)O(n^4) time when ≠\ne is allowed, because path consistency does not remove every impossible base relation. Without ≠\ne, path consistency gives the minimal labels.

Properties

  • Exact. It decides consistency and returns a solution, for all 8 labels, including ≠\ne.
  • Linear in the input. It reads each label a constant number of times.
  • Solutions with few values. The values are integers in 0,…,n−10, \ldots, n-1, one per component. Points in different components always get different values, so the solution is as "spread out" as the constraints allow.
  • Not incremental. Adding one constraint can merge components, and the algorithm is run again from the start. For a stream of additions, algebraic closure in the incremental form keeps all labels up to date.

Variants and improvements

  • Path consistency. Algebraic closure with the 3×33 \times 3 table also decides consistency of point algebra networks (Ladkin and Maddux 1994), in O(n3)O(n^3) time, and it also tightens the labels.
  • Minimal labels. Van Beek (1992) computes the minimal network in O(n4)O(n^4) time with an extra step for the ≠\ne labels that path consistency misses.
  • Pointisable interval networks. An interval network whose labels can all be written as point algebra constraints on the endpoints (the pointisable relations, 188 of the 2132^{13} including the empty relation) is solved by this algorithm on its 2n2n endpoints.
  • Metric constraints. With bounds on differences, a≤xj−xi≤ba \le x_j - x_i \le b, the problem is the simple temporal problem, solved by shortest paths. Strict inequalities and ≠\ne need extra care there.

When to use it

Use it when every constraint compares two time points or two numbers by <<, ≤\le, ==, ≥\ge, >> or ≠\ne: event orders, version orders, the endpoints of pointisable interval networks. It is the fastest exact method for this class. If you also need the tightest label of each pair, run algebraic closure or van Beek's minimal-label algorithm. If the constraints relate intervals with disjunctions that are not pointisable, use Allen's propagation with search instead.

Pitfalls

  • Treating ≠\ne as an edge. Line L3 must not add an edge for ≠\ne. An edge for ≠\ne would force an order between two points that have none.
  • Checking only the strict labels. Line L6 must test every labelled pair inside a component for ==, not only the pairs labelled <<. A ≠\ne inside a cycle of ≤\le is also a contradiction, and a test that looks only at the edges of GG does not see it, because ≠\ne makes no edge.
  • Reading one direction. Line L3 must look at RjiR_{ji} as well as RijR_{ij}. A label ≥\ge stored on the pair (i,j)(i, j) gives the edge j→ij \to i.
  • Numbering in the wrong direction. Tarjan's algorithm finds sink components first. Line L7 must reverse that order; otherwise every strict constraint between components is violated.
  • Empty labels. Line L1 is needed: an empty label on an isolated pair makes no edge and would not be found by the later lines.

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.

point_algebra_consistency.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/point-algebra-consistency/. The authors are listed in prov/TYA2PW.jsonl.

"""Consistency of a point algebra network by strongly connected components.

A label is a mask over the base relations <, =, > (bits 0, 1, 2), as in
qcn.point_algebra(). The pair (i, j) with label {<, =} means x_i <= x_j.
"""

LT, EQ, GT = 1, 2, 4
LE = LT | EQ  # {<, =}


def _converse(r: int) -> int:
    return (r & EQ) | (LT if r & GT else 0) | (GT if r & LT else 0)


def _scc(n: int, succ: list[list[int]]) -> list[int]:
    """Tarjan's algorithm without recursion. comp[v] numbers the components
    in reverse topological order: an edge u -> v has comp[u] >= comp[v]."""
    index = [-1] * n
    low = [0] * n
    comp = [-1] * n
    stack: list[int] = []
    counter = ncomp = 0
    for root in range(n):
        if index[root] != -1:
            continue
        work = [(root, 0)]
        index[root] = low[root] = counter
        counter += 1
        stack.append(root)
        while work:
            v, pos = work[-1]
            if pos < len(succ[v]):
                work[-1] = (v, pos + 1)
                w = succ[v][pos]
                if index[w] == -1:
                    index[w] = low[w] = counter
                    counter += 1
                    stack.append(w)
                    work.append((w, 0))
                elif comp[w] == -1:
                    low[v] = min(low[v], index[w])
                continue
            work.pop()
            if work:
                u = work[-1][0]
                low[u] = min(low[u], low[v])
            if low[v] == index[v]:
                while True:
                    w = stack.pop()
                    comp[w] = ncomp
                    if w == v:
                        break
                ncomp += 1
    return comp


def point_algebra_consistency(n: int, net: dict[tuple[int, int], int]) -> list[int] | None:
    """Return integers v[0 .. n-1] that satisfy every label, or None if the
    network is inconsistent.

    net maps pairs (i, j), i < j, to masks over {<, =, >}; a missing pair has
    the universal label. Cost: O(n + e) for e labelled pairs, so O(n^2).
    """
    if any(r == 0 for r in net.values()):  # @line L1
        return None
    succ: list[list[int]] = [[] for _ in range(n)]  # @line L2
    for (i, j), r in net.items():  # @line L3
        for a, b, s in ((i, j, r), (j, i, _converse(r))):
            if s & LE == s:
                succ[a].append(b)
    comp = _scc(n, succ)  # @line L4
    for (i, j), r in net.items():  # @line L5
        if comp[i] == comp[j] and not r & EQ:  # @line L6
            return None
    top = max(comp, default=-1)
    return [top - comp[v] for v in range(n)]  # @line L7
qcn.py 232 lines
# SPDX-License-Identifier: MIT
# Shared helper of the qualitative calculus pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Qualitative calculi and qualitative constraint networks.

A calculus has the base relations 0 .. m-1. A relation is a set of base
relations, stored as an int bit mask: bit b is set when base relation b is in
the set. The calculus keeps the converse of each base relation and the
composition table: table[a][b] is the mask of the base relations that can hold
between x and z when x a y and y b z. The table is computed from concrete
values (integers for points, integer pairs for intervals). It is never typed in.

A network on the nodes 0 .. n-1 is a dict that maps a pair (i, j) with i < j
to a mask. A missing pair has the universal relation. label(calc, net, i, j)
reads a label in either direction.

consistent_scenarios(calc, n, net) is the brute force oracle. It tries the
scenarios of the network (one base relation on each pair) and yields those
that have a realization by concrete values. It is for n <= 5 only. It does not
use the composition table.
"""

from collections.abc import Callable, Iterator
from itertools import combinations

Network = dict[tuple[int, int], int]
Atoms = dict[tuple[int, int], int]


class Calculus:
    """A finite set of base relations with converse and a composition table."""

    def __init__(self, names: list[str], base_of: Callable, values: list,
                 realize: Callable[[int, Atoms], list | None]) -> None:
        """base_of(x, y) is the base relation between two values. values must
        realize every configuration of three values. realize(n, atoms) returns
        n values that satisfy the atomic constraints, or None if there are none."""
        self.names = list(names)
        self.size = len(self.names)
        self.universal = (1 << self.size) - 1
        self.base_of = base_of
        self.realize = realize
        self.conv = [-1] * self.size
        self.table = [[0] * self.size for _ in range(self.size)]
        self.identity = 0
        for x in values:
            self.identity |= 1 << base_of(x, x)
            for y in values:
                a = base_of(x, y)
                assert self.conv[a] in (-1, base_of(y, x))
                self.conv[a] = base_of(y, x)
                for z in values:
                    self.table[a][base_of(y, z)] |= 1 << base_of(x, z)
        assert -1 not in self.conv
        self._comp: dict[tuple[int, int], int] = {}

    def rel(self, *names: str) -> int:
        """The mask of the named base relations."""
        m = 0
        for nm in names:
            m |= 1 << self.names.index(nm)
        return m

    def names_of(self, r: int) -> list[str]:
        return [nm for b, nm in enumerate(self.names) if r >> b & 1]

    def converse(self, r: int) -> int:
        out = 0
        for b in range(self.size):
            if r >> b & 1:
                out |= 1 << self.conv[b]
        return out

    def compose(self, r: int, s: int) -> int:
        """The union of table[a][b] over a in r and b in s. Memoized."""
        key = (r, s)
        out = self._comp.get(key)
        if out is None:
            out = 0
            for a in range(self.size):
                if r >> a & 1:
                    for b in range(self.size):
                        if s >> b & 1:
                            out |= self.table[a][b]
            self._comp[key] = out
        return out


def label(calc: Calculus, net: Network, i: int, j: int) -> int:
    """The label of the pair (i, j) in either direction."""
    if i == j:
        return calc.identity
    if i < j:
        return net.get((i, j), calc.universal)
    return calc.converse(net.get((j, i), calc.universal))


def network(calc: Calculus, n: int, constraints) -> Network:
    """The complete network on n nodes: each label is the universal relation
    intersected with every constraint (i, j, mask) on the pair."""
    net = {(i, j): calc.universal for i, j in combinations(range(n), 2)}
    for i, j, r in constraints:
        if i < j:
            net[(i, j)] &= r
        else:
            net[(j, i)] &= calc.converse(r)
    return net


def order_points(n: int, cons: list[tuple[int, int, int]]) -> list[int] | None:
    """Integers v[0 .. n-1] with sign(v[p] - v[q]) == c for each (p, q, c),
    or None. Merges the = classes, then sorts the < graph topologically."""
    parent = list(range(n))

    def find(p: int) -> int:
        while parent[p] != p:
            parent[p] = parent[parent[p]]
            p = parent[p]
        return p

    for p, q, c in cons:
        if c == 0:
            parent[find(p)] = find(q)
    succ: dict[int, set[int]] = {find(p): set() for p in range(n)}
    for p, q, c in cons:
        if c != 0:
            lo, hi = (find(p), find(q)) if c < 0 else (find(q), find(p))
            if lo == hi:
                return None
            succ[lo].add(hi)
    indeg = {u: 0 for u in succ}
    for u in succ:
        for w in succ[u]:
            indeg[w] += 1
    level = {u: 0 for u in succ}
    stack = [u for u in succ if indeg[u] == 0]
    seen = 0
    while stack:
        u = stack.pop()
        seen += 1
        for w in succ[u]:
            level[w] = max(level[w], level[u] + 1)
            indeg[w] -= 1
            if indeg[w] == 0:
                stack.append(w)
    if seen < len(succ):
        return None
    return [level[find(p)] for p in range(n)]


def _sign(x: int) -> int:
    return (x > 0) - (x < 0)


def point_algebra() -> Calculus:
    """The point algebra: base relations <, =, > between numbers."""
    def base_of(x: int, y: int) -> int:
        return _sign(x - y) + 1

    def realize(n: int, atoms: Atoms) -> list[int] | None:
        return order_points(n, [(i, j, b - 1) for (i, j), b in atoms.items()])

    return Calculus(["<", "=", ">"], base_of, [0, 1, 2], realize)


ALLEN_NAMES = ["b", "m", "o", "s", "d", "f", "eq", "fi", "di", "si", "oi", "mi", "bi"]
# sign(x- - y-), sign(x- - y+), sign(x+ - y-), sign(x+ - y+) for each base relation
ALLEN_SIGNS = [(-1, -1, -1, -1), (-1, -1, 0, -1), (-1, -1, 1, -1), (0, -1, 1, -1),
               (1, -1, 1, -1), (1, -1, 1, 0), (0, -1, 1, 0), (-1, -1, 1, 0),
               (-1, -1, 1, 1), (0, -1, 1, 1), (1, -1, 1, 1), (1, 0, 1, 1), (1, 1, 1, 1)]


def allen() -> Calculus:
    """Allen's interval algebra: intervals are integer pairs (start, end), start < end."""
    index = {sg: b for b, sg in enumerate(ALLEN_SIGNS)}

    def base_of(x: tuple[int, int], y: tuple[int, int]) -> int:
        return index[(_sign(x[0] - y[0]), _sign(x[0] - y[1]),
                      _sign(x[1] - y[0]), _sign(x[1] - y[1]))]

    def realize(n: int, atoms: Atoms) -> list[tuple[int, int]] | None:
        cons = [(2 * i, 2 * i + 1, -1) for i in range(n)]
        for (i, j), b in atoms.items():
            for (p, q), c in zip(((0, 0), (0, 1), (1, 0), (1, 1)), ALLEN_SIGNS[b]):
                cons.append((2 * i + p, 2 * j + q, c))
        v = order_points(2 * n, cons)
        return None if v is None else [(v[2 * i], v[2 * i + 1]) for i in range(n)]

    values = [(a, b) for a in range(6) for b in range(a + 1, 6)]
    return Calculus(ALLEN_NAMES, base_of, values, realize)


def consistent_scenarios(calc: Calculus, n: int, net: Network) -> Iterator[tuple[Atoms, list]]:
    """Yield (scenario, realization) for every scenario of net that has a
    realization. A partial scenario with no realization is cut off, which is
    safe because a scenario that extends it has no realization either."""
    assert n <= 5, "brute force is for at most 5 nodes"
    pairs = list(combinations(range(n), 2))
    atoms: Atoms = {}

    def search(t: int) -> Iterator[tuple[Atoms, list]]:
        if t == len(pairs):
            vals = calc.realize(n, atoms)
            assert vals is not None
            assert all(calc.base_of(vals[i], vals[j]) == b for (i, j), b in atoms.items())
            yield dict(atoms), vals
            return
        r = net.get(pairs[t], calc.universal)
        for b in range(calc.size):
            if r >> b & 1:
                atoms[pairs[t]] = b
                if calc.realize(n, atoms) is not None:
                    yield from search(t + 1)
                del atoms[pairs[t]]

    yield from search(0)


def consistent(calc: Calculus, n: int, net: Network) -> list | None:
    """A realization of net, or None if it is inconsistent (brute force)."""
    for _, vals in consistent_scenarios(calc, n, net):
        return vals
    return None


def minimal_network(calc: Calculus, n: int, net: Network) -> Network:
    """For each pair, the union of the base relations that occur in some
    consistent scenario (brute force)."""
    out = {p: 0 for p in combinations(range(n), 2)}
    for atoms, _ in consistent_scenarios(calc, n, net):
        for p, b in atoms.items():
            out[p] |= 1 << b
    return out
test_point_algebra_consistency.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/point-algebra-consistency/. The authors are listed in prov/TYA2PW.jsonl.

import random
from itertools import combinations, permutations, product

from point_algebra_consistency import EQ, GT, LE, LT, point_algebra_consistency
from qcn import consistent, label, network, point_algebra

PA = point_algebra()
NE = LT | GT
ALL = LT | EQ | GT


def holds(v, net) -> bool:
    return all(r >> PA.base_of(v[i], v[j]) & 1 for (i, j), r in net.items())


def integer_solution(n, net):
    """Search all assignments with values in 0 .. n-1. Any solution can be
    renumbered into this range, so this decides consistency."""
    for v in product(range(n), repeat=n):
        if holds(v, net):
            return v
    return None


def path_consistent(n, net) -> bool:
    """Path consistency written out with the 3 x 3 table, for comparison."""
    r = {(i, j): label(PA, net, i, j) for i, j in permutations(range(n), 2)}
    changed = True
    while changed:
        changed = False
        for i, j, k in permutations(range(n), 3):
            t = r[(i, j)] & PA.compose(r[(i, k)], r[(k, j)])
            if t != r[(i, j)]:
                r[(i, j)], r[(j, i)] = t, PA.converse(t)
                changed = True
    return all(r.values())


def random_net(rng, n, density, labels):
    return {p: rng.choice(labels) for p in combinations(range(n), 2) if rng.random() < density}


def test_masks_match_qcn() -> None:
    assert (LT, EQ, GT) == (PA.rel("<"), PA.rel("="), PA.rel(">"))


def test_example() -> None:
    # x0 <= x1 <= x2 <= x0 forces x0 = x1 = x2; x3 != x2 and x3 <= x0 then give x3 < x0.
    net = {(0, 1): LE, (1, 2): LE, (0, 2): EQ | GT, (2, 3): NE, (0, 3): EQ | GT}
    v = point_algebra_consistency(4, net)
    assert v is not None and holds(v, net)
    assert v[0] == v[1] == v[2] > v[3]
    net[(1, 3)] = EQ
    assert point_algebra_consistency(4, net) is None


def test_not_equal_inside_a_cycle() -> None:
    assert point_algebra_consistency(2, {(0, 1): LE | GT}) is not None
    assert point_algebra_consistency(3, {(0, 1): LE, (1, 2): LE, (0, 2): GT | EQ}) is not None
    assert point_algebra_consistency(3, {(0, 1): LE, (1, 2): LE, (0, 2): GT}) is None
    cycle = {(0, 1): LE, (1, 2): LE, (0, 2): GT | EQ, (0, 3): EQ}
    assert point_algebra_consistency(4, cycle) is not None
    assert point_algebra_consistency(4, {**cycle, (1, 3): NE}) is None


def test_edges() -> None:
    assert point_algebra_consistency(0, {}) == []
    assert point_algebra_consistency(1, {}) == [0]
    assert point_algebra_consistency(2, {(0, 1): 0}) is None
    assert point_algebra_consistency(2, {(0, 1): ALL}) is not None
    v = point_algebra_consistency(3, {(0, 1): EQ, (1, 2): LT})
    assert v[0] == v[1] < v[2]


def test_against_brute_force_and_integers() -> None:
    rng = random.Random(21)
    labels = [LT, GT, LT, GT, EQ, LE, EQ | GT, NE, ALL]
    seen = [0, 0]
    for _ in range(600):
        n = rng.randint(1, 5)
        net = random_net(rng, n, 0.6 + 0.4 * rng.random(), labels)
        v = point_algebra_consistency(n, net)
        full = network(PA, n, [(i, j, r) for (i, j), r in net.items()])
        oracle = consistent(PA, n, full)
        ints = integer_solution(n, net) if n <= 4 else oracle
        assert (v is None) == (oracle is None) == (ints is None)
        assert (v is not None) == path_consistent(n, full)
        if v is not None:
            assert holds(v, net)
            assert sorted(set(v)) == list(range(len(set(v))))
        seen[v is None] += 1
    assert min(seen) > 100


def test_larger_networks_against_path_consistency() -> None:
    rng = random.Random(22)
    labels = [LT, LE, EQ | GT, NE, NE, ALL, EQ]
    for _ in range(40):
        n = rng.randint(6, 12)
        net = random_net(rng, n, 0.3, labels)
        v = point_algebra_consistency(n, net)
        assert (v is not None) == path_consistent(n, network(PA, n, [(i, j, r) for (i, j), r in net.items()]))
        if v is not None:
            assert holds(v, net)


def test_long_chain() -> None:
    n = 3000
    net = {(i, i + 1): LE for i in range(n - 1)}
    v = point_algebra_consistency(n, net)
    assert v == list(range(n))
    net[(0, n - 1)] = EQ | GT  # closes the cycle: all points equal
    v = point_algebra_consistency(n, net)
    assert v == [0] * n
    net[(5, 6)] = LT
    assert point_algebra_consistency(n, net) is None

History

Vilain and Kautz (1986) introduced the point algebra and showed that propagation is polynomial for it. Van Beek (AAAI 1990, journal version 1992) gave the algorithm on this page for a consistent scenario, in O(n2)O(n^2) time, and an O(n4)O(n^4) algorithm for the minimal labels when ≠\ne is present. Ladkin and Maddux (1994) proved, in the language of relation algebras, that path consistency decides consistency of point algebra networks. The component step is Tarjan's linear-time algorithm (1972).

References

  1. Peter van Beek, Reasoning about qualitative temporal information, Artificial Intelligence 58(1-3), 1992, pages 297 to 326 (the O(n^2) algorithm for a consistent scenario of a point algebra network, and the O(n^4) algorithm for its minimal labels)
  2. Peter van Beek, Reasoning about qualitative temporal information, Proceedings of AAAI-90, AAAI Press, 1990, pages 728 to 734, the conference version of the same results
  3. Peter B. Ladkin and Roger D. Maddux, On binary constraint problems, Journal of the ACM 41(3), 1994, pages 435 to 469 (path consistency decides consistency of point algebra networks, and a solution can then be found in O(n^2) time)
  4. Robert Tarjan, Depth-first search and linear graph algorithms, SIAM Journal on Computing 1(2), 1972, pages 146 to 160 (strongly connected components in linear time)
  5. Marc Vilain, Henry Kautz and Peter van Beek, Constraint propagation algorithms for temporal reasoning, a revised report, in Readings in Qualitative Reasoning about Physical Systems, Morgan Kaufmann, 1990, pages 373 to 381 (the point algebra, and propagation for networks of points)
  6. Rina Dechter, Constraint Processing, Morgan Kaufmann, 2003, Chapter 12, Temporal constraint networks (qualitative point networks)

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