Algorithm Search⌘K

Algorithmadvanced

SLG resolution

Also called tabled resolution, tabling.

Goal-directed evaluation that keeps a table of answers for each call and delays negative literals it cannot decide yet. It terminates on finite ground programs and computes the well-founded semantics.

Time
O(s³) worst
Space
O(s) extra
Where
s = the size of the part of the program that the query reaches, the number of rules plus the number of body literals
Properties
deterministic
Origin
Weidong Chen, David S. Warren, 1996

SLG resolution answers queries top-down, like SLDNF resolution, but it keeps a table for each atom it calls. A repeated call does not start a new search: it waits for the answers in the table. A negative literal whose atom is still under evaluation in a cycle is delayed: the answer carries it as a condition, and the condition is resolved later. When a group of mutually dependent calls can give no new answers, the group is completed. Chen and Warren (1996) proved that this gives the well-founded semantics, and that the evaluation terminates on programs with a finite ground instance, where SLDNF resolution can loop. This page describes SLG for finite ground normal programs. Unlike the alternating fixpoint, which computes the whole well-founded model bottom-up, SLG evaluates only the atoms that the query reaches.

In plain words

Prolog answers a question by working backward through the rules. With recursion and negation this can run forever: to decide p it asks about q, and q asks about p again. SLG resolution keeps a table for each question it has asked. When a question comes back, it waits for the answers in the table instead of starting again. When a question depends on its own negation, the method cannot decide it yet, so it puts that condition aside and attaches it to the answer. When a group of questions can produce no new answers, the method closes their tables: a question with no answers is false, and the conditions put aside are checked again. What stays open at the end is unknown. The result agrees with the well-founded model, and only the part of the program that the question reaches is used.

The problem

The input is a finite ground normal program PP, a set of rules h←b1,…,bm,not c1,…,not ckh \leftarrow b_1, \ldots, b_m, \mathit{not}\ c_1, \ldots, \mathit{not}\ c_k, and a query atom qq. The output is the value of qq in the well-founded model of PP: true, false or undefined. The evaluation also gives the values of all the atoms it calls. Programs with variables are handled by the real engines through calls with substitutions; the page leaves them out.

The algorithm

A node (h←G∣D)(h \leftarrow G \mid D) stands for a rule of hh with the goals GG still to solve and the set DD of delayed literals. A table holds the answers of its atom: an answer (h∣D)(h \mid D) with D=∅D = \emptyset makes the atom true, and the other answers are conditional. A table is false when it is complete and has no answers, and undefined when it is complete and has only conditional answers. A literal bb is true when bb is true and false when bb is false; not b\mathit{not}\ b is the opposite. The call graph has an edge h→bh \to b when a node of hh selects a literal on bb.

  1. SLG(P, q) ▷ P: a finite ground normal program, q: the query atom
  2. 1CALL(q) from no caller
  3. 2loop
  4. 3while the work list W is not empty do
  5. 4take a node (h ← G | D) from W, and skip it if h is true
  6. 5if G is empty then ANSWER(h, D), and continue with the next node
  7. 6L ← the first literal of G, R ← the rest of G, b ← the atom of L; CALL(b) from h
  8. 7if L = b then
  9. 8if b is true then push (h ← R | D)
  10. 9else if b has answers then push (h ← R | D ∪ {b}) ▷ delay b
  11. 10else if b is not complete then add (h ← R | D) to the consumers of b ▷ else b is false: drop the node
  12. 11else ▷ L = not b
  13. 12if b is true then drop the node
  14. 13else if b is complete and has no answers then push (h ← R | D)
  15. 14else if b is complete then push (h ← R | D ∪ {not b}) ▷ b is undefined
  16. 15else add (h ← R | D) to the negative waiters of b
  17. 16SIMPLIFY
  18. 17if every table is complete then return the status of each table
  19. 18C ← a strongly connected component of the call graph on the incomplete tables, with no edge to another one
  20. 19if a node of a table of C waits on not b for a table b of C then
  21. 20move each such node (h ← R | D) to W as (h ← R | D ∪ {not b}) ▷ delaying
  22. 21else
  23. 22mark the tables of C complete ▷ completion
  24. 23repeat
  25. 24SIMPLIFY
  26. 25S ← the least set of atoms of C such that a ∈ S if a has an answer whose delayed positive atoms in C are all in S
  27. 26delete the answers of the atoms of C that are not in S ▷ answer completion
  28. 27until line L26 deletes nothing
  29. 28move each negative waiter on a table of C to W, handled as at lines L12 to L14
  30. CALL(b) from h
  31. 29if there is a caller h then add the edge h → b to the call graph
  32. 30if b has no table then create an incomplete table for b, and push (b ← body | ∅) for each rule of b
  33. ANSWER(h, D)
  34. 31remove the true literals from D; return if D has a false literal, if h is true, or if h has the answer D
  35. 32if D is empty then make h true: delete its answers, mark it complete, drop its negative waiters
  36. 33else add the answer (h | D)
  37. 34if this is the first answer of h then move its consumers to W, handled as at lines L8 and L9
  38. SIMPLIFY
  39. 35until nothing changes: in each answer remove the true literals; delete the answer if a literal is false; make the head true as at line L32 if the delay becomes empty

A component chosen at line L18 has edges only to complete tables, so a node of CC can only wait on tables of CC. If one of these waits is negative, nothing else can move, and line L20 delays the literal. If none is, no table of CC can get a new answer, and line L22 completes CC: a table with no answers becomes false, and its positive consumers are dropped. Line L26 removes answers that are kept only by a positive loop through delayed literals, since such atoms are unfounded.

Example

Take the program below and the query pp. Its well-founded model makes rr false and leaves pp and qq undefined.

p ← not q.   q ← not p.   q ← r.   r ← r.

The work list is a stack, and the rules of an atom are pushed in order, so the last rule runs first.

step node or event action
1 CALL(pp) create the table pp; push p←not qp \leftarrow \mathit{not}\ q
2 p←not qp \leftarrow \mathit{not}\ q CALL(qq): create the table qq; push q←not pq \leftarrow \mathit{not}\ p and q←rq \leftarrow r. The table qq is incomplete, so the node waits on not q\mathit{not}\ q
3 q←rq \leftarrow r CALL(rr): create the table rr; push r←rr \leftarrow r. The table rr has no answers, so the node becomes a consumer of rr
4 r←rr \leftarrow r rr has no answers: the node becomes a consumer of rr
5 q←not pq \leftarrow \mathit{not}\ p pp is incomplete: the node waits on not p\mathit{not}\ p
6 WW is empty the call graph is p→qp \to q, q→pq \to p, q→rq \to r, r→rr \to r; the component {r}\{r\} has no edge out and no negative wait, so it is completed. It has no answers: rr is false, and its consumers are dropped
7 WW is empty the component {p,q}\{p, q\} has the waits of pp on not q\mathit{not}\ q and of qq on not p\mathit{not}\ p; delaying pushes p← ∣{not q}p \leftarrow\ \mid \{\mathit{not}\ q\} and q← ∣{not p}q \leftarrow\ \mid \{\mathit{not}\ p\}
8 q← ∣{not p}q \leftarrow\ \mid \{\mathit{not}\ p\} the answer q∣{not p}q \mid \{\mathit{not}\ p\}
9 p← ∣{not q}p \leftarrow\ \mid \{\mathit{not}\ q\} the answer p∣{not q}p \mid \{\mathit{not}\ q\}
10 WW is empty complete {p,q}\{p, q\}: no literal can be simplified, S={p,q}S = \{p, q\}, and nothing is deleted

The result is pp and qq undefined, rr false. The conditional answers p∣{not q}p \mid \{\mathit{not}\ q\} and q∣{not p}q \mid \{\mathit{not}\ p\} are the residual program: they record why pp and qq are undefined. SLDNF resolution loops on this query, because the subsidiary tree for qq calls pp again.

Correctness

The correctness proof has the details for this ground version. Termination: each rule of a tabled atom starts one chain of nodes, each node has at most one successor, and each wait ends at most once, so there are at most ss nodes. Soundness: every node (h←G∣D)(h \leftarrow G \mid D) comes from a rule of PP whose other body literals were true when they were removed, so a true table is true in the well-founded model; and the tables that become false at a completion form an unfounded set, because each of their rules stopped at a false literal or at a positive literal of the same set. Completeness: the final statuses, extended by the well-founded values of the atoms without a table, are a pre-fixpoint of the operator of Van Gelder, Ross and Schlipf, so they are at least as defined as its least fixpoint. Answer completion is needed for the false atoms of positive loops through delayed literals. Chen and Warren (1996) prove soundness and completeness for programs with variables and a finite ground instance.

Proof: The ground SLG evaluator terminates and gives each tabled atom its well-founded valuefull

Chen and Warren (1996) proved that SLG resolution is sound and complete for the well-founded semantics of programs with finite ground instances. This file proves the same for the small evaluator of the page and its Python file, which works on a finite ground normal program PP and one query atom qq. The line numbers refer to the pseudocode on the page.

Notation

Let (T∗,F∗)(T^*, F^*) be the well-founded model of PP: the least fixpoint of the operator WP(T,F)=(TP(T,F),GUS(T,F))W_P(T, F) = (T_P(T, F), \mathrm{GUS}(T, F)) of Van Gelder, Ross and Schlipf, where TP(T,F)T_P(T, F) is the set of heads of the rules whose body is true in (T,F)(T, F) and GUS\mathrm{GUS} is the greatest unfounded set. A set XX is unfounded with respect to (T,F)(T, F) if each rule with its head in XX has (i) a body literal that is false in (T,F)(T, F), or (ii) a positive body atom in XX. The operator is monotone, so (T∗,F∗)≤I(T^*, F^*) \le I for every II with WP(I)≤IW_P(I) \le I.

A table is true once it has an answer with an empty delay, false once it is complete and has no answers, and undefined if it is complete and has conditional answers. A node (h←G∣D)(h \leftarrow G \mid D) belongs to a rule of hh; at line L4 it is taken from the work list, and each step gives it at most one successor: the same rule with one literal fewer in GG.

Termination

Each rule of a tabled atom starts one chain of nodes (line L30), and each node has at most one successor, which it gets at once (lines L8, L9, L13, L14) or after a wait in exactly one list, from which it leaves at most once (line L34 for a consumer, line L20 or L28 for a negative waiter, or never). So the number of nodes is at most the number of rules plus the number of body literals, ss. Each answer comes from the last node of a chain, so there are at most as many answers as rules. SIMPLIFY stops because each change deletes a literal or an answer or makes a table true. Each pass of the main loop that does not stop either moves at least one waiting node to the work list (line L20) or completes at least one table (line L22). So there are at most 2s2s passes, and the evaluation stops.

Soundness of true and false

We show by induction over the sequence of events that every table that becomes true is in T∗T^* and every table that becomes false is in F∗F^*. The induction uses one invariant:

(N) For each node (h←G∣D)(h \leftarrow G \mid D) and each answer (h∣D)(h \mid D), there is a rule of PP with head hh whose body consists of the literals of GG, the literals of DD, and literals that were true by the table statuses when they were removed.

It holds for the first node of each chain. Each step either removes a literal that is true at that time (line L8: bb true; line L13: bb false, so not b\mathit{not}\ b true; SIMPLIFY and line L31: true literals), or moves a literal from GG to DD (lines L9, L14, L20, L28). Statuses never go back: a true table stays true, and a false table is complete and gets no new answer, because no node of a complete table is left (see the last section).

True. A table becomes true when an answer has an empty delay. By (N) and the induction hypothesis, the body of its rule is true in (T∗,F∗)(T^*, F^*), so the head is in TP(T∗,F∗)=T∗T_P(T^*, F^*) = T^*.

False. Tables become false only while a component CC is completed, at line L22 (the tables of CC with no answers) and at line L26 (the deleted atoms). Let YY be the set of atoms of CC that have no answers after one of these events, together with the atoms deleted at that event. We show that YY is unfounded with respect to (T∗,F∗)(T^*, F^*), so Y⊆F∗Y \subseteq F^*. Take a∈Ya \in Y and a rule rr of aa. The chain of rr ended in one of these ways.

  • It was dropped because a literal was false: not b\mathit{not}\ b with bb true (line L12, or line L31 or SIMPLIFY), or bb with bb false. By induction, this literal of rr is false in (T∗,F∗)(T^*, F^*): case (i).
  • It waits as a consumer of bb, which has had no answer since then. If bb was complete earlier, it is false, and case (i) holds. Otherwise bb is incomplete when CC is chosen; since CC is a sink of the call graph on the incomplete tables, b∈Cb \in C, and bb has no answers, so b∈Yb \in Y: case (ii).
  • It waits negatively. This is not possible: CC is completed only when no node of a table of CC waits on a table of CC, and a wait on a table outside CC ended when that table was completed.
  • It gave an answer that is still present when the atom is deleted at line L26. Then a∉Sa \notin S, so the delay of the answer has a positive literal bb with b∈C∖Sb \in C \setminus S. The table bb is not true, because SIMPLIFY at line L24 removed the true literals, so bb has no answers or is itself deleted: b∈Yb \in Y, and bb is in the body of rr by (N): case (ii).
  • It gave an answer whose delay equals that of an answer already present. The same argument applies to that delay, which by (N) is also part of the body of rr.

The head of rr is not true, since a∈Ya \in Y. So every rule of aa satisfies (i) or (ii).

Completeness

Let VV be the final statuses. At the end every table is complete. Let I′=(T′,F′)I' = (T', F'), where T′T' is the set of true tables together with the atoms of T∗T^* that have no table, and F′F' the set of false tables together with the atoms of F∗F^* that have no table. By soundness, I′≤(T∗,F∗)I' \le (T^*, F^*). We show that WP(I′)≤I′W_P(I') \le I'; then (T∗,F∗)≤I′(T^*, F^*) \le I', so the two are equal, and each undefined table is neither in T∗T^* nor in F∗F^*.

Final answers. After CC is completed, each delay of an answer of CC mentions only tables of CC or of components completed before. These tables have no nodes left and do not change again, by induction on the order of completion, so the answers of CC do not change either. By the last SIMPLIFY, the literals of the final delays are all on undefined tables.

TP(I′)⊆T′T_P(I') \subseteq T'. Let rr be a rule of aa whose body is true in I′I'. If aa has no table, the body is true in (T∗,F∗)(T^*, F^*), since I′≤(T∗,F∗)I' \le (T^*, F^*), so a∈T∗a \in T^*. Otherwise follow the chain of rr. Each literal it reaches is called, so it is on a table, and it is true in VV. A positive literal bb on a true table either continues the chain at once (line L8 or L9) or waits until the first answer of bb, which comes because bb ends true (line L34). A negative literal not b\mathit{not}\ b with bb false continues the chain at line L13 or L14, or waits until line L20 or L28 moves it on. So the chain gives an answer (a∣D)(a \mid D) in which every literal ends true, unless aa is already true. Such an answer is never deleted: SIMPLIFY deletes only answers with a false literal, and line L26 does not delete it either. To see this, order the atoms of CC that end true by the time at which they become true. At an iteration of lines L23 to L27, the first of them that is not yet true has an answer whose positive delayed atoms of CC became true before it, so there are none left after line L24, and the atom is in SS; by induction on the order, every later one is in SS too. The answer (a∣D)(a \mid D) has only such atoms as positive delayed atoms of CC, so a∈Sa \in S. In the end all literals of DD are removed, and aa is true.

GUS(I′)⊆F′\mathrm{GUS}(I') \subseteq F'. Let XX be unfounded with respect to I′I'. Since I′≤(T∗,F∗)I' \le (T^*, F^*), XX is also unfounded with respect to (T∗,F∗)(T^*, F^*), so X⊆F∗X \subseteq F^*. The atoms of XX without a table are then in F′F', and no atom of XX is a true table. Suppose that some atoms of XX are undefined tables, and let CC be the first completed component that contains one of them. Take such an atom a∈X∩Ca \in X \cap C and a final answer (a∣D)(a \mid D), from a rule rr. By (N), the body of rr is DD plus literals true in I′I'. The literals of DD are on undefined tables, so no literal of rr is false in I′I', and the positive literals outside DD are in T′T', which is disjoint from XX. As XX is unfounded, DD contains a positive literal b∈Xb \in X. The table bb is undefined, and it is in CC or in a component completed before CC; by the choice of CC, b∈Cb \in C. So every final answer of every atom of X∩CX \cap C has a positive delayed atom in X∩CX \cap C. The last iteration of lines L23 to L27 for CC deleted nothing, so SS contained every atom of CC with an answer, including the atoms of X∩CX \cap C. But the least fixpoint SS never adds a first atom of X∩CX \cap C, because each of its answers needs another atom of X∩CX \cap C to be in SS already. This is a contradiction, so every atom of XX with a table is false.

Why answer completion is needed

Without lines L23 to L27, a positive loop through delayed literals can keep an atom undefined when it is false. Take a←not ba \leftarrow \mathit{not}\ b, b←c,bb \leftarrow c, b, c←not ac \leftarrow \mathit{not}\ a, c←c,not cc \leftarrow c, \mathit{not}\ c and the query aa. All three tables end up in one component, with the negative waits of aa on bb and of cc on aa and then of cc on cc. Delaying gives the answers a∣{not b}a \mid \{\mathit{not}\ b\}, c∣{not a}c \mid \{\mathit{not}\ a\} and c∣{c,not c}c \mid \{c, \mathit{not}\ c\}. At completion, bb has no answers and is false, so aa becomes true and the answer c∣{not a}c \mid \{\mathit{not}\ a\} is deleted. The answer c∣{c,not c}c \mid \{c, \mathit{not}\ c\} has no false literal, so SIMPLIFY keeps it, but in the well-founded model cc is false: {c}\{c\} is unfounded. Answer completion finds that c∉Sc \notin S and deletes it.

What the tests check

For every atom of every random program, the tests run the evaluator with that atom as the query and compare every tabled atom with the well-founded model. The well-founded model is computed from the definition with unfounded sets (programs with at most 6 atoms) and with the alternating fixpoint written with the plain functions of lp.py (programs with at most 12 atoms). They also check that only atoms reachable from the query are tabled, that a shuffle of the rules and of the body literals does not change the result, and the examples of the page.

Complexity

Let ss be the number of rules plus the number of body literals in the part of the program that the query reaches. There are at most ss nodes, and each step on a node takes time proportional to the size of its delay. Each pass of the main loop delays at least one waiting node or completes at least one table, so there are at most 2s2s passes. This simple version recomputes the components and repeats the SIMPLIFY passes, which gives O(s3)O(s^3) time in the worst case. The space is O(s)O(s): each chain holds one live node, each table its answers, and the call graph one edge per selected literal. Engines such as XSB keep the components incrementally on a completion stack and simplify through links from each atom to the answers that mention it. For Datalog programs with a fixed set of rules, tabled evaluation under the well-founded semantics takes time polynomial in the size of the data, while SLDNF resolution may not terminate at all.

Properties

  • Goal-directed. Only the atoms that the query reaches get tables. The tests check this on random programs.
  • Terminates on finite ground programs. Loops through positive or negative literals end in a table, never in an infinite branch.
  • Sound and complete for the well-founded semantics. Each tabled atom gets its value in the well-founded model, with three values.
  • Answers carry their conditions. The conditional answers form a residual program that explains the undefined atoms.
  • Independent of the rule order. The order of rules and literals changes the path of the evaluation, but not the result.

Variants and improvements

  • OLDT resolution. Tamaki and Sato (1986) introduced tables for definite programs. SLG adds negation, delaying and simplification.
  • The SLG-WAM. XSB compiles SLG resolution into an extension of the Warren abstract machine, with scheduling strategies (local and batched) that change the order of answer return and the time of completion.
  • Answer completion. The operation at line L26 was described by Chen and Warren, and Swift, Pinto and Pereira (2009) gave an incremental way to do it in the SLG-WAM, which had not implemented it before.
  • Call subsumption. Instead of a table per call variant, a call can use the answers of a more general call that is already tabled.
  • Stratified programs. If the program is stratified, the well-founded model is total, so every table ends true or false and no conditional answer is left at the end.
  • Bottom-up alternatives. Magic sets rewrite a program so that bottom-up Datalog evaluation also uses only the relevant facts.

When to use it

Use SLG resolution, through a tabling engine, to answer queries on recursive rules with negation when the program is large and the query needs only a small part of it, or when the program is not stratified and a three-valued answer is acceptable. To get the whole well-founded model of a ground program, the alternating fixpoint is simpler. To get stable models, use an answer set solver; atoms that SLG finds undefined may still be true in every stable model.

Pitfalls

  • Tables are not free. Tabling an atom stores all its answers. For programs with variables, a call with many different arguments creates many tables, and the memory grows with them.
  • Delayed literals are not answers. An answer with a nonempty delay is conditional. Reporting it as true before completion gives wrong results, as in the example, where pp and qq have answers but are undefined.
  • Answer completion. Without line L26, a positive loop through delayed literals can keep a false atom undefined. For a←not ba \leftarrow \mathit{not}\ b, b←c,bb \leftarrow c, b, c←not ac \leftarrow \mathit{not}\ a, c←c,not cc \leftarrow c, \mathit{not}\ c and the query aa, the answer c∣{c,not c}c \mid \{c, \mathit{not}\ c\} survives simplification, but cc is false.
  • Early decisions on negation. A negative literal on an incomplete table may only be resolved when the table is true (fail) or complete (succeed or delay). Treating an incomplete table with no answers as false is a common error, and it gives wrong results on loops.

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.

lp.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the logic program pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Ground normal logic programs, for the logic program pages.

A program is a list of rules (head, pos, neg). The head is an atom, and pos and
neg are tuples of atoms: the rule is head <- pos[0], ..., not neg[0], ....
An atom is any hashable value that can be sorted with the other atoms, for
example a small int or a short string. A rule with pos and neg empty is a fact.
A program with every neg empty is definite.

The functions are the plain definitions, written for clarity and checked by
the tests of each page. The brute force enumerator accepts at most MAX_ATOMS
atoms. The algorithms of the pages live in their own files, not here.
"""

from itertools import combinations

MAX_ATOMS = 12


def atoms(program):
    """The sorted list of the atoms that occur in the program."""
    out = set()
    for head, pos, neg in program:
        out.add(head)
        out.update(pos)
        out.update(neg)
    return sorted(out)


def tp(program, interp):
    """The immediate consequence operator: the heads of the rules whose body is true in the set interp."""
    return frozenset(h for h, pos, neg in program if all(b in interp for b in pos) and not any(c in interp for c in neg))


def least_model(program):
    """The least model of a definite program, as the limit of tp from the empty set."""
    if any(neg for _, _, neg in program):
        raise ValueError("least_model needs a definite program")
    model = frozenset()
    while True:
        nxt = tp(program, model)
        if nxt == model:
            return model
        model = nxt


def reduct(program, m):
    """The Gelfond-Lifschitz reduct of the program by the set m."""
    return [(h, tuple(pos), ()) for h, pos, neg in program if not any(c in m for c in neg)]


def is_stable(program, m):
    """True when m is the least model of the reduct of the program by m."""
    return least_model(reduct(program, m)) == frozenset(m)


def stable_models(program):
    """All stable models, by brute force over every subset of the atoms, sorted by size and then by content."""
    universe = atoms(program)
    if len(universe) > MAX_ATOMS:
        raise ValueError(f"the brute force accepts at most {MAX_ATOMS} atoms")
    found = []
    for k in range(len(universe) + 1):
        for subset in combinations(universe, k):
            if is_stable(program, frozenset(subset)):
                found.append(frozenset(subset))
    return found


def random_program(rng, n_atoms, n_rules, max_pos=2, max_neg=2):
    """A random ground normal program over the atoms 0 .. n_atoms - 1, drawn with the random.Random rng."""
    program = []
    for _ in range(n_rules):
        head = rng.randrange(n_atoms)
        pos = tuple(rng.sample(range(n_atoms), rng.randint(0, min(max_pos, n_atoms))))
        neg = tuple(rng.sample(range(n_atoms), rng.randint(0, min(max_neg, n_atoms))))
        program.append((head, pos, neg))
    return program
slg_resolution.py 266 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slg-resolution/. The authors are listed in prov/N2VDR9.jsonl.
"""A small SLG evaluator for ground normal programs (Chen and Warren 1996).

A program is a list of rules (head, pos, neg), as in lp.py. slg(program, query)
evaluates the atom query top-down with tables and returns a dict from each
tabled atom to "true", "false" or "undefined", its value in the well-founded
model.

The evaluator keeps one table per called atom. A node (h, goals, delay) is a
rule instance for h with the goals still to solve and the set of delayed
literals; a delayed literal is (POS, b) or (NEG, b). It implements the SLG
operations for ground programs: program clause resolution, answer return,
negative return, delaying, simplification, completion of a strongly connected
component of the call graph, and answer completion.

It leaves out: calls with variables (variant checks and substitutions), call
subsumption, the scheduling strategies of real engines, the incremental
completion stack (the components are recomputed from scratch), and all
efficiency work of an engine such as the SLG-WAM.
"""

POS, NEG = "+", "-"


class _Table:
    __slots__ = ("complete", "true", "answers", "consumers", "waiters")

    def __init__(self):
        self.complete = False
        self.true = False  # True once the table has an answer with no delay
        self.answers = set()  # the delay lists of the conditional answers
        self.consumers = []  # nodes waiting for the first answer of a positive call
        self.waiters = []  # nodes waiting on the negation of this atom


class SLG:
    def __init__(self, program):
        self.rules = {}
        for h, pos, neg in program:
            goals = tuple((POS, b) for b in pos) + tuple((NEG, c) for c in neg)
            self.rules.setdefault(h, []).append(goals)
        self.tables = {}
        self.calls = {}  # the call graph: atom -> dict of called atoms, used as an ordered set
        self.work = []
        self.stats = {"delayed": 0, "answer_completion": 0, "nodes": 0}

    # The truth values.

    def _is_false(self, t):
        return t.complete and not t.true and not t.answers

    def value(self, atom):
        t = self.tables[atom]
        if t.true:
            return "true"
        return "false" if not t.answers else "undefined"

    def values(self):
        return {a: self.value(a) for a in self.tables}

    # The operations.

    def _push(self, node):
        self.work.append(node)
        self.stats["nodes"] += 1

    def _call(self, b, caller):
        if caller is not None:
            self.calls[caller][b] = None  # @line L29
        if b not in self.tables:  # @line L30
            self.tables[b] = _Table()
            self.calls[b] = {}
            for goals in self.rules.get(b, ()):
                self._push((b, goals, frozenset()))
        return self.tables[b]

    def _reduce(self, delay):
        """The delay without its true literals, or None if one of its literals is false."""
        out = []
        for sign, b in delay:
            t = self.tables[b]
            if t.true:
                if sign == NEG:
                    return None
            elif self._is_false(t):
                if sign == POS:
                    return None
            else:
                out.append((sign, b))
        return frozenset(out)

    def _make_true(self, h):
        t = self.tables[h]
        t.true = True
        t.complete = True  # a true atom of a ground program is final
        t.answers = set()
        t.waiters = []

    def _wake(self, h):
        t = self.tables[h]
        consumers, t.consumers = t.consumers, []
        for head, rest, delay in consumers:
            self._push((head, rest, delay if t.true else delay | {(POS, h)}))

    def _answer(self, h, delay):
        t = self.tables[h]
        d = self._reduce(delay)  # @line L31
        if d is None or t.true or d in t.answers:
            return
        first = not t.answers
        if not d:
            self._make_true(h)  # @line L32
        else:
            t.answers.add(d)  # @line L33
        if first:
            self._wake(h)  # @line L34

    def _simplify(self):
        changed = True
        while changed:  # @line L35
            changed = False
            for h, t in self.tables.items():
                if t.true or not t.answers:
                    continue
                kept = set()
                for d in t.answers:
                    r = self._reduce(d)
                    if r is None:
                        continue
                    if not r:
                        kept = None
                        break
                    kept.add(r)
                if kept is None:
                    self._make_true(h)
                    changed = True
                elif kept != t.answers:
                    t.answers = kept
                    changed = True

    def _step(self, node):
        h, goals, delay = node  # @line L4
        if self.tables[h].true:
            return
        if not goals:
            self._answer(h, delay)  # @line L5
            return
        (sign, b), rest = goals[0], goals[1:]  # @line L6
        t = self._call(b, h)
        if sign == POS:  # @line L7
            if t.true:
                self._push((h, rest, delay))  # @line L8
            elif t.answers:
                self._push((h, rest, delay | {(POS, b)}))  # @line L9
            elif not t.complete:
                t.consumers.append((h, rest, delay))  # @line L10
        else:  # @line L11
            if t.true:
                return  # @line L12
            if t.complete and not t.answers:
                self._push((h, rest, delay))  # @line L13
            elif t.complete:
                self._push((h, rest, delay | {(NEG, b)}))  # @line L14
            else:
                t.waiters.append((h, rest, delay))  # @line L15

    def _sink_component(self, open_tables):
        """The first component found by Tarjan's algorithm on the incomplete tables, which has no edge to another component."""
        inside = set(open_tables)
        index, low, on_stack, stack = {}, {}, set(), []
        for root in open_tables:
            if root in index:
                continue
            index[root] = low[root] = len(index)
            stack.append(root)
            on_stack.add(root)
            frames = [(root, iter(self.calls[root]))]
            while frames:
                v, it = frames[-1]
                descended = False
                for w in it:
                    if w not in inside:
                        continue
                    if w not in index:
                        index[w] = low[w] = len(index)
                        stack.append(w)
                        on_stack.add(w)
                        frames.append((w, iter(self.calls[w])))
                        descended = True
                        break
                    if w in on_stack:
                        low[v] = min(low[v], index[w])
                if descended:
                    continue
                frames.pop()
                if frames:
                    u = frames[-1][0]
                    low[u] = min(low[u], low[v])
                if low[v] == index[v]:
                    comp = set()
                    while True:
                        w = stack.pop()
                        on_stack.discard(w)
                        comp.add(w)
                        if w == v:
                            return comp
        raise AssertionError("no incomplete table")

    def _complete(self, comp):
        for a in comp:
            self.tables[a].complete = True  # @line L22
        while True:  # @line L23
            self._simplify()  # @line L24
            supported, grew = set(), True
            while grew:  # @line L25
                grew = False
                for a in comp:
                    t = self.tables[a]
                    if a in supported or not t.answers:
                        continue
                    if any(all(b in supported for s, b in d if s == POS and b in comp) for d in t.answers):
                        supported.add(a)
                        grew = True
            dead = [a for a in comp if self.tables[a].answers and a not in supported]
            if not dead:  # @line L27
                break
            self.stats["answer_completion"] += 1
            for a in dead:
                self.tables[a].answers = set()  # @line L26
        for a in comp:
            t = self.tables[a]
            waiters, t.waiters, t.consumers = t.waiters, [], []
            for h, rest, delay in waiters:  # @line L28
                if t.true:
                    continue
                if not t.answers:
                    self._push((h, rest, delay))
                else:
                    self._push((h, rest, delay | {(NEG, a)}))

    def run(self, query):
        self._call(query, None)  # @line L1
        while True:  # @line L2
            while self.work:  # @line L3
                self._step(self.work.pop())
            self._simplify()  # @line L16
            open_tables = [a for a, t in self.tables.items() if not t.complete]
            if not open_tables:  # @line L17
                return self.values()
            comp = self._sink_component(open_tables)  # @line L18
            inner = [(b, node) for b in comp for node in self.tables[b].waiters if node[0] in comp]
            if inner:  # @line L19
                for b in comp:
                    t = self.tables[b]
                    t.waiters = [node for node in t.waiters if node[0] not in comp]
                for b, (h, rest, delay) in inner:
                    self.stats["delayed"] += 1
                    self._push((h, rest, delay | {(NEG, b)}))  # @line L20
            else:  # @line L21
                self._complete(comp)


def slg(program, query):
    """Evaluates the atom query and returns a dict from each tabled atom to "true", "false" or "undefined"."""
    return SLG(program).run(query)
test_slg_resolution.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slg-resolution/. The authors are listed in prov/N2VDR9.jsonl.

import random
import unittest
from itertools import combinations

import lp
from slg_resolution import SLG, slg


def wfm_alternating(program):
    """The well-founded model by the alternating fixpoint, written with the plain definitions of lp.py."""

    def s(j):
        return lp.least_model(lp.reduct(program, j))

    k = frozenset()
    while True:
        u = s(k)
        k_next = s(u)
        if k_next == k:
            return k, frozenset(lp.atoms(program)) - u
        k = k_next


def wfm_unfounded(program):
    """The well-founded model as the least fixpoint of W_P, with the greatest unfounded set found by brute force."""
    universe = lp.atoms(program)
    true, false = frozenset(), frozenset()
    while True:
        new_true = frozenset(h for h, pos, neg in program if all(b in true for b in pos) and all(c in false for c in neg))
        gus = set()
        for k in range(1, len(universe) + 1):
            for u in combinations(universe, k):
                u = set(u)
                if all(h not in u or any(b in false or b in u for b in pos) or any(c in true for c in neg) for h, pos, neg in program):
                    gus |= u
        if (new_true, frozenset(gus)) == (true, false):
            return true, false
        true, false = new_true, frozenset(gus)


def value_in(model, atom):
    true, false = model
    return "true" if atom in true else "false" if atom in false else "undefined"


def reachable(program, query):
    seen, todo = {query}, [query]
    while todo:
        a = todo.pop()
        for h, pos, neg in program:
            if h == a:
                for b in pos + neg:
                    if b not in seen:
                        seen.add(b)
                        todo.append(b)
    return seen


class TestSLG(unittest.TestCase):
    def check_program(self, p, model):
        for q in lp.atoms(p):
            got = slg(p, q)
            self.assertIn(q, got)
            self.assertTrue(set(got) <= reachable(p, q), "only atoms that the query reaches are tabled")
            for a, v in got.items():
                self.assertEqual(v, value_in(model, a), (p, q, a))

    def test_matches_unfounded_set_definition(self):
        rng = random.Random(11)
        for _ in range(150):
            p = lp.random_program(rng, rng.randint(1, 6), rng.randint(0, 10))
            self.check_program(p, wfm_unfounded(p))

    def test_matches_alternating_fixpoint(self):
        rng = random.Random(12)
        for _ in range(500):
            n = rng.randint(1, 12)
            p = lp.random_program(rng, n, rng.randint(0, 2 * n + 2), max_pos=rng.randint(0, 3), max_neg=rng.randint(0, 2))
            self.check_program(p, wfm_alternating(p))

    def test_rule_order_does_not_matter(self):
        rng = random.Random(13)
        for _ in range(200):
            p = lp.random_program(rng, 8, 14)
            model = wfm_alternating(p)
            shuffled = [(h, tuple(rng.sample(pos, len(pos))), tuple(rng.sample(neg, len(neg)))) for h, pos, neg in p]
            rng.shuffle(shuffled)
            self.check_program(shuffled, model)

    def test_delaying_and_answer_completion_are_used(self):
        rng = random.Random(14)
        totals = {"delayed": 0, "answer_completion": 0}
        for _ in range(400):
            p = lp.random_program(rng, 6, 10, max_pos=2, max_neg=1)
            for q in lp.atoms(p):
                e = SLG(p)
                e.run(q)
                for key in totals:
                    totals[key] += e.stats[key]
        self.assertGreater(totals["delayed"], 0)
        self.assertGreater(totals["answer_completion"], 0)

    def test_answer_completion_example(self):
        # a <- not b.  b <- c, b.  c <- not a.  c <- c, not c.
        # After completion, c keeps the answer c | {c, not c}, which only a positive loop supports.
        p = [("a", (), ("b",)), ("b", ("c", "b"), ()), ("c", (), ("a",)), ("c", ("c",), ("c",))]
        e = SLG(p)
        self.assertEqual(e.run("a"), {"a": "true", "b": "false", "c": "false"})
        self.assertEqual(e.stats["answer_completion"], 1)
        self.assertEqual(wfm_alternating(p), (frozenset("a"), frozenset("bc")))

    def test_page_example(self):
        # p <- not q.  q <- not p.  q <- r.  r <- r.
        p = [("p", (), ("q",)), ("q", (), ("p",)), ("q", ("r",), ()), ("r", ("r",), ())]
        e = SLG(p)
        self.assertEqual(e.run("p"), {"p": "undefined", "q": "undefined", "r": "false"})
        self.assertEqual(e.stats["delayed"], 2)
        self.assertEqual(e.tables["p"].answers, {frozenset({("-", "q")})})

    def test_loop_on_positive_recursion(self):
        # SLDNF resolution loops on these programs; SLG terminates.
        self.assertEqual(slg([("p", ("p",), ())], "p"), {"p": "false"})
        p = [("p", ("q",), ()), ("p", (), ("q",)), ("q", ("q",), ())]
        self.assertEqual(slg(p, "p"), {"p": "true", "q": "false"})
        self.assertEqual(slg([("p", (), ("p",))], "p"), {"p": "undefined"})

    def test_win_move_game(self):
        moves = [(1, 2), (2, 3), (3, 4), (5, 6), (6, 5)]
        p = [(x, (), (y,)) for x, y in moves]
        self.assertEqual(slg(p, 1), {1: "true", 2: "false", 3: "true", 4: "false"})
        self.assertEqual(slg(p, 5), {5: "undefined", 6: "undefined"})

    def test_atom_without_rules(self):
        self.assertEqual(slg([], "a"), {"a": "false"})


if __name__ == "__main__":
    unittest.main()

History

Tamaki and Sato (1986) introduced OLDT resolution, tabling for definite programs. Van Gelder, Ross and Schlipf (1991) defined the well-founded semantics, and Przymusinski and others studied global SLS resolution, a top-down procedure for it that is not effective in general. Chen and Warren developed SLG resolution in the early 1990s and published the full account, with delaying, simplification and the proofs, in the Journal of the ACM in 1996. XSB implemented it in the SLG-WAM, and later Prolog systems added tabling with the well-founded semantics. Swift, Pinto and Pereira (2009) added incremental answer completion to XSB.

References

  1. Weidong Chen and David S. Warren, Tabled evaluation with delaying for general logic programs, Journal of the ACM 43(1), 20 to 74 (1996), the SLG transformations (resolution, answer return, negative return, delaying, simplification, completion) and the proofs of soundness, completeness and termination for the well-founded semantics
  2. Hisao Tamaki and Taisuke Sato, OLD resolution with tabulation, Third International Conference on Logic Programming, Lecture Notes in Computer Science 225, Springer, 84 to 98 (1986), tables of calls and answers for definite programs
  3. Allen Van Gelder, Kenneth A. Ross and John S. Schlipf, The well-founded semantics for general logic programs, Journal of the ACM 38(3), 620 to 650 (1991), unfounded sets and the well-founded partial model that SLG computes
  4. Terrance Swift and David S. Warren, XSB, extending Prolog with tabled logic programming, Theory and Practice of Logic Programming 12(1-2), 157 to 187 (2012), the history of tabling in XSB, the SLG-WAM, scheduling and the treatment of the well-founded semantics
  5. Terrance Swift, Alexandre Miguel Pinto and Luís Moniz Pereira, Incremental answer completion in the SLG-WAM, Proceedings of the 25th International Conference on Logic Programming (ICLP 2009), Springer (2009), the answer completion operation and its implementation in the SLG-WAM

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