Algorithm Search⌘K

Algorithmadvanced

Algebraic closure

Also called a-closure, path consistency for qualitative calculi.

Refines each label of a qualitative network by the composition through every third node until nothing changes, with a queue of changed pairs, in O(n^3) steps.

Time
O(B n^3) worst
Space
O(n^2) extra
Where
B = the number of base relations of the calculus; n = the number of nodes
Properties
deterministicexactnot in placeofflineiterative
Origin
James F. Allen, Alan K. Mackworth, Gérard Ligozat, Jochen Renz, 1983

Algebraic closure is the basic propagation step for a qualitative constraint network. For every three nodes ii, kk, jj it intersects the label of (i,j)(i, j) with the composition of the labels of (i,k)(i, k) and (k,j)(k, j), read from the composition table of the calculus, and it repeats this until no label changes. It is the same loop as PC-2, but it works on the labels as sets of base relations and never looks at the values of the domain, which is infinite. When the composition of the calculus is strong, as in the point algebra and in Allen's interval algebra, the result is the path consistency closure; when it is only weak, as in RCC8, the two differ. This page gives the generic algorithm for any calculus; Allen's constraint propagation is the incremental form for interval networks.

In plain words

Each pair of objects carries a list of the relations that are still possible between them, for example "a is before b, or a meets b". Look at three objects at a time. If a is before b and b is before c, then a must be before c, so the other entries on the list for a and c can go. A table of all such two-step facts gives, for each pair of entries, the entries that are possible for the third pair.

The algorithm keeps a to-do list of pairs whose list got shorter. It takes a pair off the to-do list, uses it with every third object to shorten other lists, and puts every list that got shorter back on the to-do list. If a list becomes empty, the facts contradict each other. If the to-do list becomes empty, no three objects can shorten any list.

The problem

A qualitative constraint calculus has a finite set BB of base relations, an identity base relation id\mathrm{id}, a converse a⌣a^{\smile} for each a∈Ba \in B, and a composition table that gives a relation a⋄b⊆Ba \diamond b \subseteq B for each pair of base relations. A relation is a subset of BB, and composition extends to relations by union: r⋄s=⋃a∈r,b∈sa⋄br \diamond s = \bigcup_{a \in r, b \in s} a \diamond b.

The input is a network on the nodes 0,…,n−10, \ldots, n-1 with a label Rij⊆BR_{ij} \subseteq B on each pair. A missing constraint has the label BB. The network is kept complete and symmetric: Rji=Rij⌣R_{ji} = R_{ij}^{\smile} and Rii={id}R_{ii} = \{\mathrm{id}\}.

The network is algebraically closed if Rij⊆Rik⋄RkjR_{ij} \subseteq R_{ik} \diamond R_{kj} for all nodes ii, jj, kk. The output is the largest algebraically closed network R∗R^\ast with Rij∗⊆RijR^\ast_{ij} \subseteq R_{ij} for all pairs, or INCONSISTENT if some label of R∗R^\ast is empty. The largest one exists and is unique, because the union of two closed networks is closed.

Cost is counted in compositions and intersections of labels on a word-RAM. A label is a bit mask of ∣B∣|B| bits. A composition of two labels costs at most ∣B∣2|B|^2 table reads, or one read in a table of all pairs of labels when 2∣B∣2^{|B|} is small.

The algorithm

  1. A-CLOSURE(R) ▷ R[i][j] for all i ≠ j, with R[j][i] = conv R[i][j]
  2. 1if some R[i][j] = ∅ then return INCONSISTENT
  3. 2Q ← all pairs {i, j} with i < j
  4. 3while Q ≠ ∅ do
  5. 4remove a pair {i, j} from Q
  6. 5for each node k ∉ {i, j} do
  7. 6T ← R[i][k] ∩ (R[i][j] ⋄ R[j][k])
  8. 7if T ≠ R[i][k] then
  9. 8if T = ∅ then return INCONSISTENT
  10. 9R[i][k] ← T; R[k][i] ← conv T; add {i, k} to Q
  11. 10T ← R[k][j] ∩ (R[k][i] ⋄ R[i][j])
  12. 11if T ≠ R[k][j] then
  13. 12if T = ∅ then return INCONSISTENT
  14. 13R[k][j] ← T; R[j][k] ← conv T; add {k, j} to Q
  15. 14return R

A pair {i,j}\{i, j\} in the queue means "the label of this pair changed, so the triangles that read it may now shorten another label". The label of {i,j}\{i, j\} is read by two kinds of tests: the test of {i,k}\{i, k\} through jj (line L6) and the test of {k,j}\{k, j\} through ii (line L10). The two other orientations of the same triangle give the converse of the same test, because (r⋄s)⌣=s⌣⋄r⌣(r \diamond s)^{\smile} = s^{\smile} \diamond r^{\smile}, so they are not needed. A pair already in the queue is not added twice. Line L1 handles an input with an empty label, which the loop would not test when n=2n = 2.

Example

Take four intervals in Allen's interval algebra with these constraints: 0{b,m}10 \mathrel{\{b, m\}} 1, 1{b,m}21 \mathrel{\{b, m\}} 2, 2{d}32 \mathrel{\{d\}} 3 and 0{o,di,bi}30 \mathrel{\{o, di, bi\}} 3. The pairs {0,2}\{0, 2\} and {1,3}\{1, 3\} start with all 13 base relations. The queue starts as {0,1},{0,2},{0,3},{1,2},{1,3},{2,3}\{0,1\}, \{0,2\}, \{0,3\}, \{1,2\}, \{1,3\}, \{2,3\}.

step pair removed label changed new label reason
1 {0,1}\{0, 1\} R02R_{02} {b}\{b\} {b,m}⋄{b,m}={b}\{b, m\} \diamond \{b, m\} = \{b\} through node 1
1 R13R_{13} {d,f,oi,mi,bi}\{d, f, oi, mi, bi\} R10⋄R03R_{10} \diamond R_{03} through node 0
2 {0,2}\{0, 2\} R03R_{03} {o}\{o\} {b}⋄{d}={b,m,o,s,d}\{b\} \diamond \{d\} = \{b, m, o, s, d\} through node 2
3 {0,3}\{0, 3\} none
4 {1,2}\{1, 2\} R13R_{13} {d}\{d\} {b,m}⋄{d}={b,m,o,s,d}\{b, m\} \diamond \{d\} = \{b, m, o, s, d\} through node 2
5, 6 {1,3}\{1, 3\}, {2,3}\{2, 3\} none

The changed pairs of steps 1, 2 and 4 are already in the queue, so nothing is added. After 6 steps the queue is empty. The result says that interval 0 is before interval 2, overlaps interval 3, and that interval 1 lies during interval 3. Here every base relation that is left occurs in some solution, so the result is the minimal network, but this is not true in general.

Correctness

The invariant is: every label of R∗R^\ast stays inside the current label, and every triangle condition Rij⊆Rik⋄RkjR_{ij} \subseteq R_{ik} \diamond R_{kj} that fails has a side, {i,k}\{i, k\} or {k,j}\{k, j\}, in the queue. A revision at line L6 or L10 never removes a base relation of R∗R^\ast, because R∗R^\ast satisfies the same condition with smaller labels. Removing {i,j}\{i, j\} from the queue is safe because lines L6 and L10 make all the conditions with the side {i,j}\{i, j\} hold, and each write puts the written pair in the queue. So an empty queue means a closed network, which is inside R∗R^\ast and contains it. The algorithm does not use the domain: soundness needs only that the table contains every triple of base relations that occurs, which holds for weak composition. The full proof is in the proof file of this page.

Proof: The queue algorithm computes the algebraic closurefull

Fix a calculus with the finite set BB of base relations, the identity base relation id\mathrm{id}, the converse r⌣r^{\smile} and the composition ⋄\diamond read from the composition table: for relations r,s⊆Br, s \subseteq B, r⋄sr \diamond s is the union of the table entries a⋄ba \diamond b with a∈ra \in r and b∈sb \in s. Two facts about the table are used.

  • (T1) Converse rule. (a⋄b)⌣=b⌣⋄a⌣(a \diamond b)^{\smile} = b^{\smile} \diamond a^{\smile} for base relations a,ba, b, and so for all relations.
  • (T2) Soundness of the table. If xayx \mathrel{a} y, ybzy \mathrel{b} z and xczx \mathrel{c} z hold for three objects of the domain, then c∈a⋄bc \in a \diamond b.

Both hold for every table that is built from the domain as the set of the triples that occur (this is weak composition), and so for a strong composition too. Composition distributes over union by its definition, so it is monotone: r⊆r′r \subseteq r' and s⊆s′s \subseteq s' give r⋄s⊆r′⋄s′r \diamond s \subseteq r' \diamond s'.

A network on the nodes 0,…,n−10, \ldots, n-1 is a family R=(Rij)R = (R_{ij}) with Rji=Rij⌣R_{ji} = R_{ij}^{\smile} and Rii={id}R_{ii} = \{\mathrm{id}\}. For networks R′R' and R′′R'', write R′⊆R′′R' \subseteq R'' and R′∪R′′R' \cup R'' pair by pair. The condition C(ij,k)C(ij, k) for distinct i,j,ki, j, k is Rij⊆Rik⋄RkjR_{ij} \subseteq R_{ik} \diamond R_{kj}. By (T1), C(ij,k)C(ij, k) and C(ji,k)C(ji, k) say the same thing, so we index the conditions by the unordered target {i,j}\{i, j\} and the third node kk. The two sides of C(ij,k)C(ij, k) are the pairs {i,k}\{i, k\} and {k,j}\{k, j\}. RR is algebraically closed if all conditions hold. Fix the input network R0R^0, and consider only networks R⊆R0R \subseteq R^0.

Lemma 1 (the closure). The union of two algebraically closed networks is algebraically closed. So there is a largest algebraically closed network R∗⊆R0R^\ast \subseteq R^0. For every solution vv of R0R^0, the scenario SvS^v with Sijv={S^v_{ij} = \{the base relation of (vi,vj)}(v_i, v_j)\} satisfies Sv⊆R∗S^v \subseteq R^\ast.

Proof. Let R′R' and R′′R'' be closed. Then Rij′⊆Rik′⋄Rkj′⊆(Rik′∪Rik′′)⋄(Rkj′∪Rkj′′)R'_{ij} \subseteq R'_{ik} \diamond R'_{kj} \subseteq (R'_{ik} \cup R''_{ik}) \diamond (R'_{kj} \cup R''_{kj}) by monotonicity, and the same holds for Rij′′R''_{ij}, so the union satisfies C(ij,k)C(ij, k). The network of empty relations is closed, so the union of all closed networks inside R0R^0 (finitely many) is the largest one. For a solution vv, (T2) applied to vi,vk,vjv_i, v_k, v_j shows that SvS^v satisfies every condition, and Sv⊆R0S^v \subseteq R^0 because vv satisfies R0R^0. So Sv⊆R∗S^v \subseteq R^\ast. □\square

Lemma 2 (a revision keeps the closure). If R∗⊆RR^\ast \subseteq R before line L6 or line L10, then R∗⊆RR^\ast \subseteq R after line L9 or line L13.

Proof. Line L6 sets T=Rik∩(Rij⋄Rjk)T = R_{ik} \cap (R_{ij} \diamond R_{jk}). Since R∗R^\ast satisfies C(ik,j)C(ik, j), Rik∗⊆Rij∗⋄Rjk∗⊆Rij⋄RjkR^\ast_{ik} \subseteq R^\ast_{ij} \diamond R^\ast_{jk} \subseteq R_{ij} \diamond R_{jk}, so Rik∗⊆TR^\ast_{ik} \subseteq T. Line L9 writes TT and its converse, so R∗⊆RR^\ast \subseteq R still holds. Line L10 is the same with the target {k,j}\{k, j\} and the third node ii. □\square

Lemma 3 (the queue). Each time line L3 is reached, every condition that fails in RR has a side in QQ.

Proof. At the first test, QQ holds all pairs. Consider one iteration, which removes {i,j}\{i, j\} at line L4. Inside the loop of line L5, RijR_{ij} never changes, because every write is to a pair {i,k}\{i, k\} or {k,j}\{k, j\} with k∉{i,j}k \notin \{i, j\}.

Take a condition CC that holds before the iteration, or fails before it with a side in QQ. We show that at the end of the iteration, CC holds or has a side in QQ.

  • A write to a pair puts that pair in QQ (lines L9 and L13). If a side of CC is written, CC has a side in QQ.
  • A write that shrinks the target of CC keeps CC true if it was true, because the right hand side does not change.
  • If neither happens, CC reads the same relations as before. Its truth does not change, and the side it had in QQ is still in QQ, unless that side is {i,j}\{i, j\}.

So it is enough to look at the conditions with the side {i,j}\{i, j\} whose sides were not written. These are C(ik,j)C(ik, j) and C(kj,i)C(kj, i) for the nodes k∉{i,j}k \notin \{i, j\}. In the pass of the loop for kk, line L6 makes Rik⊆Rij⋄RjkR_{ik} \subseteq R_{ij} \diamond R_{jk}, so C(ik,j)C(ik, j) holds after line L9. Line L10 then makes C(kj,i)C(kj, i) hold, with the current RkiR_{ki}. Later passes, for other values of kk, do not write RijR_{ij}, RikR_{ik}, RjkR_{jk} or the target {k,j}\{k, j\} of this kk. Line L10 of the same pass can write RkjR_{kj}, which is a side of C(ik,j)C(ik, j), but then {k,j}\{k, j\} goes into QQ. So each of these conditions holds or has a side in QQ at the end. □\square

Termination. A pair goes into QQ only when its label shrinks and stays non-empty. A label has at most ∣B∣|B| base relations, so it shrinks at most ∣B∣−1|B| - 1 times before it would become empty. So at most (n2)(∣B∣−1)\binom{n}{2}(|B| - 1) pairs are added after line L2, and at most (n2)∣B∣\binom{n}{2} |B| pairs leave the queue.

Theorem. The algorithm stops. It returns INCONSISTENT exactly when R∗R^\ast has an empty label, and then R0R^0 has no solution. Otherwise it returns R∗R^\ast.

Proof. By Lemma 2 and induction, R∗⊆RR^\ast \subseteq R at all times. If line L1, L8 or L12 returns INCONSISTENT, some label of RR is empty, so the same label of R∗R^\ast is empty. A solution vv would give Sv⊆R∗S^v \subseteq R^\ast with a non-empty label on each pair (Lemma 1), so there is none.

Otherwise the loop ends with Q=∅Q = \emptyset, and by Lemma 3 every condition holds. The conditions with a repeated node hold too: Rij⊆{id}⋄RijR_{ij} \subseteq \{\mathrm{id}\} \diamond R_{ij} because id⋄a={a}\mathrm{id} \diamond a = \{a\}, and {id}⊆Rik⋄Rki\{\mathrm{id}\} \subseteq R_{ik} \diamond R_{ki} for a non-empty RikR_{ik} because id∈a⋄a⌣\mathrm{id} \in a \diamond a^{\smile}. Both facts follow from (T2) with two equal objects. So RR is closed, R⊆R∗R \subseteq R^\ast by Lemma 1, and R=R∗R = R^\ast. If R∗R^\ast had an empty label, so would RR, and line L1, L8 or L12 would have returned. ■\blacksquare

Remark. The theorem does not say that a returned network is consistent. Closure is a necessary condition. It is also sufficient for some calculi and subclasses (the point algebra, ORD-Horn networks, atomic Allen networks), but not for all of Allen's interval algebra.

Complexity

Steps. A pair goes into the queue only when its label shrinks and stays non-empty. A label has at most ∣B∣|B| base relations, so each of the (n2)\binom{n}{2} pairs enters the queue at most ∣B∣|B| times, counting the start. Each removal does 2(n−2)2(n-2) compositions and intersections. The total is at most (n2)∣B∣⋅2(n−2)=O(∣B∣n3)\binom{n}{2} |B| \cdot 2(n-2) = O(|B| n^3) compositions. For a fixed calculus this is O(n3)O(n^3), the bound of Vilain, Kautz and van Beek for interval networks, with ∣B∣=13|B| = 13.

Space. The complete network has n2n^2 labels and the queue has at most (n2)\binom{n}{2} pairs, so the extra space is O(n2)O(n^2) words, plus the table, which has ∣B∣2|B|^2 entries.

The algorithm decides only closure, not consistency. The problem of consistency for the whole interval algebra is NP-complete (NP-completeness of interval algebra satisfiability), so no polynomial closure can decide it unless P = NP.

Properties

  • Sound. No base relation that occurs in a solution is removed, for any calculus whose table is sound.
  • Exact closure. The result is the unique largest algebraically closed subnetwork. It does not depend on the order of the queue.
  • Decides consistency on some classes. On point algebra networks, on networks whose labels are all ORD-Horn relations, and on atomic interval networks (one base relation per pair), a closed network with no empty label is consistent. On RCC8 networks over the tractable class H^8\hat{H}_8 the same holds (tractable subclasses of RCC8).
  • Incomplete in general. The interval network with 0{o,si}10 \mathrel{\{o, si\}} 1, 0{fi,si}20 \mathrel{\{fi, si\}} 2, 0{o,fi}30 \mathrel{\{o, fi\}} 3, 1{m,mi}21 \mathrel{\{m, mi\}} 2, 1{b,f}31 \mathrel{\{b, f\}} 3 and 2{b,s}32 \mathrel{\{b, s\}} 3 is algebraically closed, but it has no solution.
  • Equal to path consistency only for strong composition. With strong composition, r⋄sr \diamond s is the exact relational composition over the domain, so a revision removes exactly the pairs of objects that have no witness. With weak composition the table entry can be larger than the real composition, and a closed network need not be path consistent.

Variants and improvements

  • Allen's incremental form. Start from a closed network, add one constraint, and if it shrinks the label put only that pair in the queue. This is Allen's constraint propagation. Over a run of aa additions the total cost is O(n3+a)O(n^3 + a), since an addition that changes no label stops at once.
  • Triangle queue. Keep triples (i,k,j)(i, k, j) in the queue instead of pairs, as PC-2 does. This gives the same result with more queue entries.
  • Queue order. Van Beek and Manchak (1996) measured that the order in which pairs leave the queue changes the running time on interval networks, and they gave heuristics for it. The result does not change.
  • Partial closure. Close only the triangles of a chordal graph that contains the constraint graph. This keeps the network sparse. It gives the same answer as full closure for some classes, but not in general.
  • Precomputed composition. For the point algebra (232^3 labels) and for Allen (2132^{13} labels) one can store r⋄sr \diamond s for all pairs of labels, or compose bit masks by the union of rows, so each composition costs a few word operations.

When to use it

Use algebraic closure as the first step on any qualitative network: it finds many contradictions in cubic time and makes the labels smaller. It decides consistency when every label is in a tractable subclass, so a solver can split the labels until they are in such a class and run the closure at each node of the search; for intervals the Nebel-Bürckert theorem says which class to split into. For a point algebra network alone, the point algebra consistency algorithm is faster, O(n2)O(n^2), and returns a solution. For constraints with metric distances, use the simple temporal problem methods instead.

Pitfalls

  • Revising one direction only. Line L9 and line L13 must also write the converse label. If R[k][i]R[k][i] keeps its old value, line L10 reads a wrong label and the result is too large.
  • Testing only the target pair. After {i,j}\{i, j\} changes, the tests to repeat are those that read {i,j}\{i, j\} as a side, that is lines L6 and L10 with the third node kk. Revising R[i][j]R[i][j] again through kk does not use the change.
  • Not starting from the complete network. Line L2 must queue all pairs, including the pairs with the universal label. Otherwise the labels of unconstrained pairs, such as R02R_{02} in the example, are never derived.
  • Forgetting the empty test. Without line L8 and line L12 the loop runs on with an empty label and returns a network that looks closed but has no solution.
  • Calling a closed network consistent. Line L14 returns a closed network, not a proof of consistency. The 4-node network above is closed and has no solution.
  • Using the wrong table for weak calculi. For RCC8 and other calculi with weak composition, the table must contain every triple that occurs. A table copied from a paper with a typing error makes line L6 unsound. Generate the table from a model where you can, as the implementation here does for points and intervals.

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.

algebraic_closure.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algebraic-closure/. The authors are listed in prov/DTG755.jsonl.

"""Algebraic closure of a qualitative constraint network.

The network is closed when R[i][j] is a subset of R[i][k] composed with
R[k][j] for all nodes i, j, k, with composition read from the composition
table of the calculus. The algorithm keeps a queue of pairs whose label
changed and revises the two triangles of each pair with every third node.
"""

from collections import deque
from itertools import combinations

from qcn import Calculus, Network, label


def algebraic_closure(calc: Calculus, n: int, net: Network,
                      stats: dict[str, int] | None = None) -> Network | None:
    """Return the largest algebraically closed subnetwork of net, or None if
    it has an empty label (then net is inconsistent).

    net maps pairs (i, j), i < j, of the nodes 0 .. n-1 to relation masks; a
    missing pair has the universal relation. The input is not changed.
    Cost: at most n(n-1)/2 * (1 + |B|) pairs leave the queue, and each costs
    O(n) compositions, so O(|B| n^3) table operations.
    """
    if stats is None:
        stats = {}
    stats["pops"] = 0
    r = [[label(calc, net, i, j) for j in range(n)] for i in range(n)]
    if any(r[i][j] == 0 for i, j in combinations(range(n), 2)):  # @line L1
        return None
    queue = deque(combinations(range(n), 2))  # @line L2
    queued = set(queue)

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

    while queue:  # @line L3
        i, j = queue.popleft()  # @line L4
        queued.discard((i, j))
        stats["pops"] += 1
        for k in range(n):  # @line L5
            if k == i or k == j:
                continue
            t = r[i][k] & calc.compose(r[i][j], r[j][k])  # @line L6
            if t != r[i][k]:  # @line L7
                if t == 0:  # @line L8
                    return None
                r[i][k], r[k][i] = t, calc.converse(t)  # @line L9
                push(i, k)
            t = r[k][j] & calc.compose(r[k][i], r[i][j])  # @line L10
            if t != r[k][j]:  # @line L11
                if t == 0:  # @line L12
                    return None
                r[k][j], r[j][k] = t, calc.converse(t)  # @line L13
                push(k, j)
    return {(i, j): r[i][j] for i, j in combinations(range(n), 2)}  # @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_algebraic_closure.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algebraic-closure/. The authors are listed in prov/DTG755.jsonl.

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

from algebraic_closure import algebraic_closure
from qcn import allen, consistent, label, minimal_network, network, point_algebra

PA = point_algebra()
IA = allen()


def closed(calc, n, net) -> bool:
    for i, j, k in permutations(range(n), 3):
        rij = label(calc, net, i, j)
        if rij & ~calc.compose(label(calc, net, i, k), label(calc, net, k, j)):
            return False
    return True


def reference(calc, n, net):
    """Revise every triple in passes until a pass changes nothing."""
    r = {(i, j): label(calc, 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)] & calc.compose(r[(i, k)], r[(k, j)])
            if t != r[(i, j)]:
                r[(i, j)], r[(j, i)] = t, calc.converse(t)
                changed = True
    if any(v == 0 for v in r.values()):
        return None
    return {(i, j): r[(i, j)] for i, j in combinations(range(n), 2)}


def random_network(rng, calc, n, keep, density=0.7):
    cons = []
    for i, j in combinations(range(n), 2):
        if rng.random() < density:
            r = 0
            while r == 0:
                r = sum(1 << b for b in range(calc.size) if rng.random() < keep)
            cons.append((i, j, r))
    return network(calc, n, cons)


def test_point_algebra_table() -> None:
    lt, eq, gt = PA.rel("<"), PA.rel("="), PA.rel(">")
    assert PA.size == 3 and PA.identity == eq
    assert [[PA.table[a][b] for b in range(3)] for a in range(3)] == [
        [lt, lt, PA.universal], [lt, eq, gt], [PA.universal, gt, gt]]


def test_allen_table() -> None:
    assert IA.size == 13 and IA.identity == IA.rel("eq")
    assert sum(len(row) for row in IA.table) == 169
    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 sizes == {1: 97, 3: 42, 5: 24, 9: 3, 13: 3}
    assert sum(k * v for k, v in sizes.items()) == 409

    def comp(x, y):
        return set(IA.names_of(IA.table[IA.names.index(x)][IA.names.index(y)]))

    assert comp("m", "m") == {"b"} and comp("d", "d") == {"d"} and comp("s", "f") == {"d"}
    assert comp("o", "o") == {"b", "m", "o"} and comp("o", "d") == {"o", "s", "d"}
    assert comp("m", "mi") == {"f", "eq", "fi"} and comp("b", "d") == {"b", "m", "o", "s", "d"}
    full = {(x, y) for x in IA.names for y in IA.names if len(comp(x, y)) == 13}
    assert full == {("b", "bi"), ("bi", "b"), ("d", "di")}
    for a in range(13):  # the converse rule and associativity on base relations
        for b in range(13):
            assert IA.converse(IA.table[a][b]) == IA.table[IA.conv[b]][IA.conv[a]]
            for c in range(13):
                assert IA.compose(IA.table[a][b], 1 << c) == IA.compose(1 << a, IA.table[b][c])


def test_example_chain() -> None:
    net = network(IA, 4, [(0, 1, IA.rel("b", "m")), (1, 2, IA.rel("b", "m")),
                          (2, 3, IA.rel("d")), (0, 3, IA.rel("o", "di", "bi"))])
    out = algebraic_closure(IA, 4, net)
    assert out[(0, 2)] == IA.rel("b")
    assert out[(0, 3)] == IA.rel("o")
    assert out == reference(IA, 4, net)


def test_closed_but_inconsistent() -> None:
    net = network(IA, 4, [(0, 1, IA.rel("o", "si")), (0, 2, IA.rel("fi", "si")),
                          (0, 3, IA.rel("o", "fi")), (1, 2, IA.rel("m", "mi")),
                          (1, 3, IA.rel("b", "f")), (2, 3, IA.rel("b", "s"))])
    assert algebraic_closure(IA, 4, net) == net
    assert consistent(IA, 4, net) is None


def test_edges() -> None:
    assert algebraic_closure(IA, 0, {}) == {}
    assert algebraic_closure(IA, 1, {}) == {}
    assert algebraic_closure(IA, 2, {(0, 1): 0}) is None
    assert algebraic_closure(PA, 2, {}) == {(0, 1): PA.universal}
    lt = PA.rel("<")
    assert algebraic_closure(PA, 3, network(PA, 3, [(0, 1, lt), (1, 2, lt), (2, 0, lt)])) is None
    net = {(0, 1): PA.rel("<", "=")}
    algebraic_closure(PA, 3, net)
    assert net == {(0, 1): PA.rel("<", "=")}  # the input is not changed


def check_against_brute_force(calc, n, net) -> bool:
    stats: dict[str, int] = {}
    out = algebraic_closure(calc, n, net, stats)
    assert stats["pops"] <= n * (n - 1) // 2 * (1 + calc.size)
    assert out == reference(calc, n, net)
    minimal = minimal_network(calc, n, net)
    if out is None:
        assert all(v == 0 for v in minimal.values()) and n >= 2
        return False
    assert closed(calc, n, out)
    for p, r in out.items():  # sound: no base relation of a solution is removed
        assert r & net[p] == r
        assert minimal[p] & ~r == 0
    return consistent(calc, n, out) is not None


def test_point_algebra_against_brute_force() -> None:
    rng = random.Random(11)
    for _ in range(400):
        n = rng.randint(2, 5)
        net = random_network(rng, PA, n, 0.5)
        ok = check_against_brute_force(PA, n, net)
        # composition in the point algebra is strong, and closure decides consistency
        assert ok == (algebraic_closure(PA, n, net) is not None)


def test_allen_against_brute_force() -> None:
    rng = random.Random(12)
    for _ in range(250):
        n = rng.randint(2, 4)
        check_against_brute_force(IA, n, random_network(rng, IA, n, 0.3, 1.0))


def test_allen_atomic_networks_are_decided() -> None:
    rng = random.Random(13)
    for _ in range(300):
        n = rng.randint(3, 5)
        net = {p: 1 << rng.randrange(13) for p in combinations(range(n), 2)}
        out = algebraic_closure(IA, n, net)
        assert (out is not None) == (consistent(IA, n, net) is not None)
        assert out is None or out == net

History

Montanari (1974) and Mackworth (1977) introduced path consistency for networks of binary constraints over finite domains. Allen (1983) applied the same idea to intervals: he replaced the relations over values by unions of his 13 base relations and their composition by a transitivity table, and he propagated each new constraint with a queue. Vilain and Kautz (1986) and the revised report with van Beek (1990) proved the O(n3)O(n^3) bound, showed that for the point algebra without ≠\ne the propagation finds every consequence, and showed that consistency of interval networks is NP-complete. Ligozat and Renz (2004) gave a general definition of a qualitative calculus and used the name algebraic closure for this operation. Renz and Ligozat (2005) made the difference between weak and strong composition explicit and showed when algebraic closure and path consistency differ.

References

  1. Gérard Ligozat and Jochen Renz, What is a qualitative calculus? A general framework, PRICAI 2004, Lecture Notes in Artificial Intelligence 3157, Springer, 2004, pages 53 to 64 (calculi as non-associative algebras, weak representations, and algebraically closed networks)
  2. Jochen Renz and Gérard Ligozat, Weak composition for qualitative spatial and temporal reasoning, CP 2005, Lecture Notes in Computer Science 3709, Springer, 2005, pages 534 to 548 (weak composition, and the cases where algebraic closure and path consistency differ)
  3. James F. Allen, Maintaining knowledge about temporal intervals, Communications of the ACM 26(11), 1983, pages 832 to 843 (the transitivity table and the propagation of interval constraints with a queue)
  4. Alan K. Mackworth, Consistency in networks of relations, Artificial Intelligence 8(1), 1977, pages 99 to 118 (path consistency and the queue algorithm PC-2)
  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 propagation algorithm runs in O(n^3) time because each label changes at most 13 times)
  6. 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 (queue orders and other engineering choices for path consistency on interval networks, measured)
  7. Frank Dylla, Jae Hee Lee, Till Mossakowski, Thomas Schneider, André van Delden, Jasper van de Ven and Diedrich Wolter, A survey of qualitative spatial and temporal calculi, algebraic and computational properties, ACM Computing Surveys 50(1), 2017, survey of calculi, weak and strong composition, and when algebraic closure decides consistency

Where this leads

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