Algorithm Search⌘K

Algorithmadvanced

Allen's constraint propagation

Also called Allen's propagation algorithm.

Allen's incremental method for interval networks. Each new constraint is intersected into its label and pushed through the 13 by 13 table until no label changes.

Time
O(n^3) worst
Space
O(n^2) extra
Where
a = the number of added constraints; n = the number of intervals
Properties
deterministicnot exactin placeonlineiterative
Origin
James F. Allen, 1983

Allen's constraint propagation keeps a network of interval relations up to date while new facts arrive. Each pair of intervals carries a label, a set of the 13 relations of Allen's interval algebra. When a new constraint arrives, the algorithm intersects it into the label, and every label that gets smaller is pushed through the composition table to the other intervals, until no label changes. The method is the incremental, interval-specific form of algebraic closure: algebraic closure takes a whole network of any qualitative calculus at once, while this page handles one constraint at a time on a network that is already closed, which gives a total cost of O(n3+a)O(n^3 + a) for aa additions. Like path consistency in general CSPs, it is fast but incomplete: it finds every contradiction that shows up in three intervals, not every contradiction.

In plain words

Think of a calendar where you only know how events relate: the talk is during the conference, the dinner is after the talk. Each pair of events has a list of the orders that are still possible. When you learn a new fact, you cross out the orders on that pair's list that it rules out. Then you look at every third event: what you now know about the first pair, plus what you know about the second, may cross out more of the third pair's list. Each list that got shorter is checked again in the same way. If a list loses all its entries, the facts contradict each other.

The problem

The input is a stream of constraints iSji \mathrel{S} j on nn intervals, where SS is a set of base relations. The algorithm keeps a matrix of labels RijR_{ij}, with Rii={eq}R_{ii} = \{\mathrm{eq}\} and RjiR_{ji} the converse of RijR_{ij}, and keeps it closed: Rik⊆Rij∘RjkR_{ik} \subseteq R_{ij} \circ R_{jk} for all distinct i,j,ki, j, k, where ∘\circ is the composition of the composition table. After each addition it reports a contradiction or a closed network that has the same solutions as all the constraints so far. The cost is counted in label operations on a word-RAM; a label is a 13-bit mask, and one composition is a constant number of table look-ups.

The algorithm

  1. ADD(R, i, j, S) ▷ R is closed before the call
  2. 1T ← R[i][j] ∩ S
  3. 2if T = ∅ then return CONTRADICTION
  4. 3if T = R[i][j] then return OK ▷ nothing new
  5. 4R[i][j] ← T; R[j][i] ← conv T; Q ← a queue that holds {i, j}
  6. 5while Q is not empty do
  7. 6{p, q} ← pop the front of Q
  8. 7for each interval k ∉ {p, q} do
  9. 8T ← R[p][k] ∩ (R[p][q] ∘ R[q][k])
  10. 9if T = ∅ then return CONTRADICTION
  11. 10if T ≠ R[p][k] then R[p][k] ← T; R[k][p] ← conv T; push {p, k} on Q unless it is there
  12. 11T ← R[k][q] ∩ (R[k][p] ∘ R[p][q])
  13. 12if T = ∅ then return CONTRADICTION
  14. 13if T ≠ R[k][q] then R[k][q] ← T; R[q][k] ← conv T; push {k, q} on Q unless it is there
  15. 14return OK

The network starts with the universal label on every pair, which is closed. Line L8 uses the popped pair as the first step of a two-step path from pp to kk, and line L11 uses it as the second step of a path from kk to qq. The two other triples that contain the popped pair follow from these by the converse rule of the table, so two revisions per third interval are enough.

Example

Take four intervals: a talk 0, a conference 1, a dinner 2 and a party 3. All labels start universal.

call what changes pops
ADD(0, 1, {d}) R01={d}R_{01} = \{\mathrm{d}\}; no third interval has a label to combine with 1
ADD(1, 2, {b}) R12={b}R_{12} = \{\mathrm{b}\}; popping {1,2}\{1, 2\} with k=0k = 0 gives R02=d∘b={b}R_{02} = \mathrm{d} \circ \mathrm{b} = \{\mathrm{b}\}, so {0,2}\{0, 2\} is pushed and popped with no further change 2
ADD(2, 3, {o, s}) popping {2,3}\{2, 3\} gives R13=b∘{o,s}={b}R_{13} = \mathrm{b} \circ \{\mathrm{o}, \mathrm{s}\} = \{\mathrm{b}\} and R03={b}R_{03} = \{\mathrm{b}\} 3
ADD(0, 3, {bi}) line L1 gives {b}∩{bi}=∅\{\mathrm{b}\} \cap \{\mathrm{bi}\} = \emptyset; CONTRADICTION at line L2 0

The talk must be before the party, because it is during the conference, the conference is before the dinner and the dinner starts no later than the party starts. The algorithm finds this from three-interval steps only, and the last fact is rejected without any search.

Correctness

Each revision at lines L8 and L11 removes only base relations that no solution can use, because the table is sound: if xryx \mathrel{r} y and yszy \mathrel{s} z then x(r∘s)zx \mathrel{(r \circ s)} z. So no solution is lost, and an empty label proves a contradiction. The queue holds every pair whose label shrank and whose triples have not been revised since. When the queue is empty, no triple can shrink a label, so the network is closed. A closed network can still have no solution: the tests of this page contain a closed network on 4 intervals with no solution. For networks whose labels are in the ORD-Horn subclass, a closed network with no empty label always has a solution, by the Nebel-Bürckert theorem. The full proof is in the proof file of this page.

Proof: Allen's propagation keeps every solution and ends with a closed networkfull

The network holds a label RabR_{ab} for each ordered pair of distinct intervals, a set of Allen's 13 base relations, with Rba=Rab⌣R_{ba} = R_{ab}^{\smile} at all times, because lines L4, L10 and L13 write a label and its converse together. A solution is an assignment of real intervals that satisfies every constraint added so far. The network is closed when Rac⊆Rab∘RbcR_{ac} \subseteq R_{ab} \circ R_{bc} for all distinct a,b,ca, b, c. Two facts about the table are used:

  • (T1) converse rule. (r∘s)⌣=s⌣∘r⌣(r \circ s)^{\smile} = s^{\smile} \circ r^{\smile}.
  • (T2) soundness. If xryx \mathrel{r} y and yszy \mathrel{s} z for intervals x,y,zx, y, z, then x(r∘s)zx \mathrel{(r \circ s)} z. This holds because the table is the exact set of base relations between xx and zz over all configurations of three intervals.

Both are checked by the tests of this page over the whole table.

Claim. Suppose the network is closed and every solution of the earlier constraints satisfies all labels. Then ADD(i,j,S)(i, j, S) returns OK or CONTRADICTION after at most 1+12(n2)1 + 12 \binom{n}{2} pops. On OK, the network is closed and its solutions are exactly the solutions of the earlier constraints together with iSji \mathrel{S} j. On CONTRADICTION, there is no such solution.

Lemma 1 (no solution is lost). Every solution of the constraints added so far, including iSji \mathrel{S} j, satisfies every label at every step.

Proof. Line L1 intersects RijR_{ij} with SS, and a solution of the new constraint satisfies both. Lines L8 and L11 intersect a label with a composition of two labels. By (T2), a solution that satisfies those two labels also satisfies the composition. By induction on the steps, no solution is removed. □\square

So if a label becomes empty at line L2, L9 or L12, there is no solution, and CONTRADICTION is correct.

Lemma 2 (queue invariant). While the loop runs, every violated triple (a,b,c)(a, b, c), one with Rac⊈Rab∘RbcR_{ac} \not\subseteq R_{ab} \circ R_{bc}, has {a,b}\{a, b\} or {b,c}\{b, c\} in the queue.

Proof. Before ADD, the network is closed. Line L4 shrinks only the label of {i,j}\{i, j\}. A smaller RacR_{ac} cannot break Rac⊆Rab∘RbcR_{ac} \subseteq R_{ab} \circ R_{bc}, so every new violated triple has {i,j}\{i, j\} as {a,b}\{a, b\} or {b,c}\{b, c\}, and {i,j}\{i, j\} is in the queue.

When line L6 pops {p,q}\{p, q\}, the triples that rely on it are those with {p,q}\{p, q\} as one of the two composed pairs. For a third interval kk there are four: (p,q,k)(p, q, k), (k,p,q)(k, p, q), (q,p,k)(q, p, k) and (k,q,p)(k, q, p). Line L8 makes (p,q,k)(p, q, k) hold and line L11 makes (k,p,q)(k, p, q) hold. By (T1), (q,p,k)(q, p, k) is the converse of (k,p,q)(k, p, q) and (k,q,p)(k, q, p) is the converse of (p,q,k)(p, q, k), so they hold too. Later steps can break one of these triples only by shrinking one of its composed labels other than RpqR_{pq}, which the loop never changes while it handles {p,q}\{p, q\}; every such shrink, at line L10 or L13, pushes that pair. Every other triple that a shrink can break has the shrunk pair as a composed pair, and that pair is pushed. So the invariant holds after each step. □\square

Proof of the claim. When the queue is empty, Lemma 2 says no triple is violated, so the network is closed. By Lemma 1 every solution of all constraints satisfies all labels, and the labels hold every constraint (the earlier ones by assumption and SS by line L1), so a solution of the labels is a solution of the constraints. For the count: a pair enters the queue only when its label shrinks (lines L4, L10 and L13), and a label of at most 13 base relations that stays non-empty shrinks at most 12 times over the whole life of the network. ■\blacksquare

Termination and cost. Over any sequence of aa calls of ADD on a network of nn intervals, the number of pops is at most 12(n2)12 \binom{n}{2} in total, and each pop does 2(n−2)2(n - 2) revisions of constant cost, because the table has fixed size. A call that changes nothing stops at line L3. The total is O(n3+a)O(n^3 + a), and a single call takes O(n3)O(n^3) time in the worst case.

What the claim does not say. A closed network can have no solution; the tests of this page contain one with 4 intervals. Closure decides consistency only for some subclasses, such as the ORD-Horn relations (Nebel and Bürckert 1995).

Complexity

Time. A label is a set of at most 13 base relations and every change removes at least one, so each of the (n2)\binom{n}{2} labels shrinks at most 12 times over the whole life of the network. A pair enters the queue only after it shrinks, so the total number of pops is at most 12(n2)12 \binom{n}{2}, and each pop costs O(n)O(n) revisions. Over aa calls the total is O(n3+a)O(n^3 + a). A single call can do all of this work, so the worst case of one call is O(n3)O(n^3).

Space. The matrix takes O(n2)O(n^2) labels, and the queue holds at most (n2)\binom{n}{2} pairs.

Deciding consistency of a general interval network is NP-complete (NP-completeness of the interval algebra), so no polynomial propagation can be complete for all networks unless P = NP.

Properties

  • Sound. It removes only base relations that no solution uses, and it reports a contradiction only when there is none.
  • Incomplete. It decides consistency for some subclasses, such as ORD-Horn and the pointisable relations, but not for all networks.
  • Online. It accepts constraints one at a time, and the total cost over all additions is the cost of one batch closure.
  • Order does not matter. The final network is the largest closed network inside the constraints, whatever the order of the additions and of the queue.
  • No undo. After a contradiction the labels are not meaningful. A search that adds and retracts constraints must save and restore the matrix.

Variants and improvements

  • Batch closure. Algebraic closure starts with all pairs in the queue and works for any calculus with a composition table; PC-2 is the same queue idea for general binary CSPs.
  • Search. Backtracking over the base relations of each label, with this propagation at each node, decides consistency. Nebel (1997) makes this faster by splitting labels into ORD-Horn pieces instead of single base relations, because propagation is complete on the pieces.
  • Queue order. Van Beek and Manchak (1996) compare orders of the queue and other changes to the propagation loop, and report large gains in practice.
  • Points instead of intervals. If every label is pointisable, translate to endpoints and use the point algebra consistency algorithm, which is exact and faster.

When to use it

Use it to maintain a set of qualitative facts about intervals while they arrive, for example in planning, scheduling with unknown durations, or story understanding, where each new fact should give its consequences at once. It is the standard filter inside a search for interval networks. Do not use it alone as a consistency test for arbitrary labels: it can accept a network with no solution.

Pitfalls

  • Writing one direction. Lines L4, L10 and L13 must write the converse into the opposite cell. Otherwise a later revision reads an old label and the network is not closed.
  • Revising only one side. Line L11 is needed as well as line L8. With only line L8, triples where the popped pair is the second step are never revised.
  • Pushing without a change. Lines L10 and L13 push a pair only when its label got smaller. Pushing on every revision makes the loop run forever on a closed network.
  • Skipping the early exit. Line L3 makes a repeated or weaker constraint cost O(1)O(1). Without it, every call costs at least one pop of O(n)O(n).
  • Trusting OK. Line L14 means "closed", not "consistent". Treat OK as a proof of consistency only for tractable subclasses.

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.

allen_constraint_propagation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/allen-constraint-propagation/. The authors are listed in prov/7P7E2R.jsonl.

"""Allen's incremental constraint propagation for interval networks.

The network keeps a full matrix of labels. A label is a mask over Allen's 13
base relations, in the order of qcn.ALLEN_NAMES. add(i, j, s) intersects the
label of (i, j) with s and propagates the change through the composition table
until no label changes. The labels are then path consistent (algebraically
closed). That is necessary for consistency, and for some subclasses, such as
the ORD-Horn relations, it is also sufficient.
"""

from collections import deque

from qcn import Calculus, allen


class AllenNetwork:
    """An interval network on the nodes 0 .. n-1 that starts with no constraints."""

    def __init__(self, n: int, calc: Calculus | None = None) -> None:
        self.calc = calc if calc is not None else allen()
        self.n = n
        u, e = self.calc.universal, self.calc.identity
        self.r = [[e if i == j else u for j in range(n)] for i in range(n)]
        self.ok = True  # False after a contradiction; the labels are then not meaningful

    def label(self, i: int, j: int) -> int:
        return self.r[i][j]

    def add(self, i: int, j: int, s: int, stats: dict | None = None) -> bool:
        """Add the constraint (i s j), with i != j, and propagate it.

        Return False if the network is now known to be inconsistent. Otherwise
        every label is algebraically closed. Over any sequence of a additions the
        total cost is O(n^3 + a) compositions, because a label can shrink at most
        13 times and each shrink costs O(n) work later.
        """
        if not self.ok:
            return False
        calc, r = self.calc, self.r
        t = r[i][j] & s  # @line L1
        if t == 0:  # @line L2
            self.ok = False
            return False
        if t == r[i][j]:  # @line L3
            return True
        r[i][j], r[j][i] = t, calc.converse(t)  # @line L4
        queue = deque([(i, j)])
        queued = {(min(i, j), max(i, j))}

        def push(a: int, b: int) -> None:
            key = (min(a, b), max(a, b))
            if key not in queued:
                queued.add(key)
                queue.append((a, b))

        while queue:  # @line L5
            p, q = queue.popleft()  # @line L6
            queued.discard((min(p, q), max(p, q)))
            if stats is not None:
                stats["pops"] = stats.get("pops", 0) + 1
            for k in range(self.n):  # @line L7
                if k == p or k == q:
                    continue
                t = r[p][k] & calc.compose(r[p][q], r[q][k])  # @line L8
                if t == 0:  # @line L9
                    self.ok = False
                    return False
                if t != r[p][k]:  # @line L10
                    r[p][k], r[k][p] = t, calc.converse(t)
                    push(p, k)
                t = r[k][q] & calc.compose(r[k][p], r[p][q])  # @line L11
                if t == 0:  # @line L12
                    self.ok = False
                    return False
                if t != r[k][q]:  # @line L13
                    r[k][q], r[q][k] = t, calc.converse(t)
                    push(k, q)
        return True  # @line L14
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_allen_constraint_propagation.py 216 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/allen-constraint-propagation/. The authors are listed in prov/7P7E2R.jsonl.

import random
from collections import Counter
from itertools import combinations, permutations

from allen_constraint_propagation import AllenNetwork
from qcn import ALLEN_NAMES, allen, consistent, consistent_scenarios, label, network

IA = allen()


def rel(*names: str) -> int:
    return IA.rel(*names)


def reference(n, cons):
    """Path consistency by passes over all triples, from scratch."""
    net = network(IA, n, cons)
    r = {(i, j): label(IA, 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)] & IA.compose(r[(i, k)], r[(k, j)])
            if t != r[(i, j)]:
                r[(i, j)], r[(j, i)] = t, IA.converse(t)
                changed = True
    if any(v == 0 for v in r.values()):
        return None
    return r


def labels_of(net: AllenNetwork):
    return {(i, j): net.label(i, j) for i, j in permutations(range(net.n), 2)}


def closed_scenarios(net: AllenNetwork):
    """Every atomic refinement of the labels in which each triangle obeys the table."""
    n = net.n
    pairs = list(combinations(range(n), 2))
    atoms: dict[tuple[int, int], int] = {}

    def get(i, j):
        return atoms[(i, j)] if i < j else IA.conv[atoms[(j, i)]]

    def ok(i, j) -> bool:
        for k in range(n):
            if k in (i, j):
                continue
            if (min(i, k), max(i, k)) in atoms and (min(k, j), max(k, j)) in atoms:
                if not IA.table[get(i, k)][get(k, j)] >> atoms[(i, j)] & 1:
                    return False
        return True

    def search(t):
        if t == len(pairs):
            yield dict(atoms)
            return
        i, j = pairs[t]
        for b in range(13):
            if net.label(i, j) >> b & 1:
                atoms[(i, j)] = b
                if ok(i, j):
                    yield from search(t + 1)
                del atoms[(i, j)]

    yield from search(0)


def random_label(rng, keep):
    r = 0
    while r == 0:
        r = sum(1 << b for b in range(13) if rng.random() < keep)
    return r


def ord_horn_relations() -> list[int]:
    """The ORD-Horn relations, computed from the clauses. Each base relation is
    turned into its endpoint order; a clause is a set of literals p != q with at
    most one literal p <= q, over the 4 endpoints x-, x+, y-, y+."""
    cfg = []
    for b in range(13):
        (a0, a1), (b0, b1) = IA.realize(2, {(0, 1): b})
        cfg.append((a0, a1, b0, b1))
    pts = range(4)
    negs = list(combinations(pts, 2))
    masks = set()
    for chosen in range(1 << len(negs)):
        neg = [negs[t] for t in range(len(negs)) if chosen >> t & 1]
        for pos in [None] + [(p, q) for p in pts for q in pts if p != q]:
            m = 0
            for b, c in enumerate(cfg):
                if any(c[p] != c[q] for p, q in neg) or (pos is not None and c[pos[0]] <= c[pos[1]]):
                    m |= 1 << b
            masks.add(m)
    out = []
    for r in range(1, 1 << 13):
        hull = IA.universal
        for m in masks:
            if r & m == r:
                hull &= m
        if hull == r:
            out.append(r)
    return out


def test_base_relations_and_table() -> None:
    assert IA.names == ALLEN_NAMES and IA.size == 13
    assert IA.identity == rel("eq")
    assert IA.conv == [12 - b for b in range(13)]
    sizes = Counter(bin(IA.table[a][b]).count("1") for a in range(13) for b in range(13))
    assert sum(sizes.values()) == 169
    assert sum(k * v for k, v in sizes.items()) == 409
    assert sizes == {1: 97, 3: 42, 5: 24, 9: 3, 13: 3}
    assert IA.table[IA.names.index("m")][IA.names.index("m")] == rel("b")
    assert IA.table[IA.names.index("d")][IA.names.index("d")] == rel("d")
    assert IA.table[IA.names.index("o")][IA.names.index("o")] == rel("b", "m", "o")


def test_example() -> None:
    net = AllenNetwork(4, IA)
    assert net.add(0, 1, rel("d"))
    assert net.add(1, 2, rel("b"))
    assert net.label(0, 2) == rel("b")
    assert net.add(2, 3, rel("o", "s"))
    assert net.label(0, 3) == rel("b") and net.label(1, 3) == rel("b")
    assert not net.add(0, 3, rel("bi"))
    assert not net.ok


def test_closed_but_inconsistent() -> None:
    cons = [(0, 1, rel("o", "si")), (0, 2, rel("fi", "si")), (0, 3, rel("o", "fi")),
            (1, 2, rel("m", "mi")), (1, 3, rel("b", "f")), (2, 3, rel("b", "s"))]
    net = AllenNetwork(4, IA)
    assert all(net.add(i, j, r) for i, j, r in cons)
    assert labels_of(net) == reference(4, cons)
    assert consistent(IA, 4, network(IA, 4, cons)) is None
    assert list(closed_scenarios(net)) == []


def test_edges() -> None:
    net = AllenNetwork(1, IA)
    assert net.label(0, 0) == rel("eq")
    net = AllenNetwork(3, IA)
    stats: dict = {}
    assert net.add(0, 1, IA.universal, stats) and stats == {}
    assert net.add(0, 1, rel("b", "m"), stats) and stats["pops"] == 1
    assert net.add(1, 0, rel("bi"))
    assert net.label(0, 1) == rel("b") and net.label(1, 0) == rel("bi")
    assert not net.add(0, 1, rel("eq"))
    assert not net.add(1, 2, IA.universal)


def test_against_naive_fixpoint() -> None:
    rng = random.Random(31)
    for _ in range(150):
        n = rng.randint(2, 6)
        net = AllenNetwork(n, IA)
        cons = []
        stats: dict = {}
        for _ in range(rng.randint(1, 12)):
            i, j = rng.sample(range(n), 2)
            cons.append((i, j, random_label(rng, 0.4)))
            ok = net.add(*cons[-1], stats)
            ref = reference(n, cons)
            assert ok == (ref is not None)
            if not ok:
                break
            assert labels_of(net) == ref
        assert stats.get("pops", 0) <= len(cons) + 12 * n * (n - 1) // 2


def test_scenarios_inside_and_realized() -> None:
    rng = random.Random(32)
    outcomes = Counter()
    for _ in range(120):
        n = rng.randint(3, 4)
        cons = [(i, j, random_label(rng, 0.2)) for i, j in combinations(range(n), 2)]
        net = AllenNetwork(n, IA)
        ok = all(net.add(i, j, r) for i, j, r in cons)
        real = {tuple(sorted(a.items())) for a, _ in consistent_scenarios(IA, n, network(IA, n, cons))}
        if not ok:
            assert real == set()
            outcomes["contradiction"] += 1
            continue
        kept = set()
        for atoms in closed_scenarios(net):
            vals = IA.realize(n, atoms)
            assert vals is not None  # integer endpoints
            assert all(vals[i][0] < vals[i][1] for i in range(n))
            assert all(IA.base_of(vals[i], vals[j]) == b for (i, j), b in atoms.items())
            kept.add(tuple(sorted(atoms.items())))
        assert kept == real
        outcomes["consistent" if real else "closed but inconsistent"] += 1
    assert outcomes["contradiction"] > 10 and outcomes["consistent"] > 10


def test_ord_horn_networks_are_decided() -> None:
    horn = ord_horn_relations()
    assert len(horn) == 867
    # The closed but inconsistent network uses 5 labels that are not ORD-Horn.
    assert [rel(*s.split()) in horn for s in ("o si", "fi si", "o fi", "m mi", "b f", "b s")] == [
        False, False, True, False, False, False]
    small = [r for r in horn if bin(r).count("1") <= 4]
    rng = random.Random(33)
    seen = Counter()
    for _ in range(300):
        n = rng.randint(3, 4)
        net = AllenNetwork(n, IA)
        cons = [(i, j, rng.choice(small)) for i, j in combinations(range(n), 2) if rng.random() < 0.9]
        ok = all(net.add(i, j, r) for i, j, r in cons)
        assert ok == (consistent(IA, n, network(IA, n, cons)) is not None)
        seen[ok] += 1
    assert min(seen.values()) > 60

History

Allen (1983) introduced the 13 interval relations, their transitivity table and this propagation procedure. Vilain and Kautz (1986) showed that consistency of interval networks is NP-hard, so the procedure must be incomplete unless P = NP. Ladkin and Maddux (1994) placed it in the theory of relation algebras, where it is the computation of the algebraic closure. Nebel and Bürckert (1995) proved that it decides consistency for the ORD-Horn subclass, and van Beek and Manchak (1996) studied fast versions of it inside search.

References

  1. James F. Allen, Maintaining knowledge about temporal intervals, Communications of the ACM 26(11), 1983, pages 832 to 843 (the 13 relations, the transitivity table and the propagation procedure with its queue of changed pairs)
  2. Marc Vilain and Henry Kautz, Constraint propagation algorithms for temporal reasoning, Proceedings of AAAI-86, 1986, pages 377 to 382, the propagation is polynomial and incomplete; consistency of interval networks is NP-hard
  3. Bernhard Nebel and Hans-Jürgen Bürckert, Reasoning about temporal relations, a maximal tractable subclass of Allen's interval algebra, Journal of the ACM 42(1), 1995, pages 43 to 66 (path consistency decides consistency of ORD-Horn networks)
  4. Peter van Beek and Dennis W. Manchak, The design and experimental analysis of algorithms for temporal reasoning, Journal of Artificial Intelligence Research 4, 1996, pages 1 to 18 (efficient path consistency for interval networks and backtracking search on top of it)
  5. Frank Dylla and others, A survey of qualitative spatial and temporal calculi, algebraic and computational properties, ACM Computing Surveys 50(1), 2017, pages 1 to 39 (algebraic closure and its role in qualitative calculi)

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