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
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- 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 , a set of rules , and a query atom . The output is the value of in the well-founded model of : 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 stands for a rule of with the goals still to solve and the set of delayed literals. A table holds the answers of its atom: an answer with 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 is true when is true and false when is false; is the opposite. The call graph has an edge when a node of selects a literal on .
SLG(P, q) ▷ P: a finite ground normal program, q: the query atom- 1
CALL(q) from no caller - 2
loop - 3
while the work list W is not empty do - 4
take a node (h ← G | D) from W, and skip it if h is true - 5
if G is empty then ANSWER(h, D), and continue with the next node - 6
L ← the first literal of G, R ← the rest of G, b ← the atom of L; CALL(b) from h - 7
if L = b then - 8
if b is true then push (h ← R | D) - 9
else if b has answers then push (h ← R | D ∪ {b}) ▷ delay b - 10
else if b is not complete then add (h ← R | D) to the consumers of b ▷ else b is false: drop the node - 11
else ▷ L = not b - 12
if b is true then drop the node - 13
else if b is complete and has no answers then push (h ← R | D) - 14
else if b is complete then push (h ← R | D ∪ {not b}) ▷ b is undefined - 15
else add (h ← R | D) to the negative waiters of b - 16
SIMPLIFY - 17
if every table is complete then return the status of each table - 18
C ← a strongly connected component of the call graph on the incomplete tables, with no edge to another one - 19
if a node of a table of C waits on not b for a table b of C then - 20
move each such node (h ← R | D) to W as (h ← R | D ∪ {not b}) ▷ delaying - 21
else - 22
mark the tables of C complete ▷ completion - 23
repeat - 24
SIMPLIFY - 25
S ← 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 - 26
delete the answers of the atoms of C that are not in S ▷ answer completion - 27
until line L26 deletes nothing - 28
move each negative waiter on a table of C to W, handled as at lines L12 to L14 CALL(b) from h- 29
if there is a caller h then add the edge h → b to the call graph - 30
if b has no table then create an incomplete table for b, and push (b ← body | ∅) for each rule of b ANSWER(h, D)- 31
remove the true literals from D; return if D has a false literal, if h is true, or if h has the answer D - 32
if D is empty then make h true: delete its answers, mark it complete, drop its negative waiters - 33
else add the answer (h | D) - 34
if this is the first answer of h then move its consumers to W, handled as at lines L8 and L9 SIMPLIFY- 35
until 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 can only wait on tables of . If one of these waits is negative, nothing else can move, and line L20 delays the literal. If none is, no table of can get a new answer, and line L22 completes : 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 . Its well-founded model makes false and leaves and 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() | create the table ; push |
| 2 | CALL(): create the table ; push and . The table is incomplete, so the node waits on | |
| 3 | CALL(): create the table ; push . The table has no answers, so the node becomes a consumer of | |
| 4 | has no answers: the node becomes a consumer of | |
| 5 | is incomplete: the node waits on | |
| 6 | is empty | the call graph is , , , ; the component has no edge out and no negative wait, so it is completed. It has no answers: is false, and its consumers are dropped |
| 7 | is empty | the component has the waits of on and of on ; delaying pushes and |
| 8 | the answer | |
| 9 | the answer | |
| 10 | is empty | complete : no literal can be simplified, , and nothing is deleted |
The result is and undefined, false. The conditional answers and are the residual program: they record why and are undefined. SLDNF resolution loops on this query, because the subsidiary tree for calls 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 nodes. Soundness: every node comes from a rule of 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 and one query atom . The line numbers refer to the pseudocode on the page.
Notation
Let be the well-founded model of : the least fixpoint of the operator of Van Gelder, Ross and Schlipf, where is the set of heads of the rules whose body is true in and is the greatest unfounded set. A set is unfounded with respect to if each rule with its head in has (i) a body literal that is false in , or (ii) a positive body atom in . The operator is monotone, so for every with .
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 belongs to a rule of ; 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 .
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, . 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 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 and every table that becomes false is in . The induction uses one invariant:
(N) For each node and each answer , there is a rule of with head whose body consists of the literals of , the literals of , 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: true; line L13: false, so true; SIMPLIFY and line L31: true literals), or moves a literal from to (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 , so the head is in .
False. Tables become false only while a component is completed, at line L22 (the tables of with no answers) and at line L26 (the deleted atoms). Let be the set of atoms of that have no answers after one of these events, together with the atoms deleted at that event. We show that is unfounded with respect to , so . Take and a rule of . The chain of ended in one of these ways.
- It was dropped because a literal was false: with true (line L12, or line L31 or SIMPLIFY), or with false. By induction, this literal of is false in : case (i).
- It waits as a consumer of , which has had no answer since then. If was complete earlier, it is false, and case (i) holds. Otherwise is incomplete when is chosen; since is a sink of the call graph on the incomplete tables, , and has no answers, so : case (ii).
- It waits negatively. This is not possible: is completed only when no node of a table of waits on a table of , and a wait on a table outside ended when that table was completed.
- It gave an answer that is still present when the atom is deleted at line L26. Then , so the delay of the answer has a positive literal with . The table is not true, because SIMPLIFY at line L24 removed the true literals, so has no answers or is itself deleted: , and is in the body of 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 .
The head of is not true, since . So every rule of satisfies (i) or (ii).
Completeness
Let be the final statuses. At the end every table is complete. Let , where is the set of true tables together with the atoms of that have no table, and the set of false tables together with the atoms of that have no table. By soundness, . We show that ; then , so the two are equal, and each undefined table is neither in nor in .
Final answers. After is completed, each delay of an answer of mentions only tables of 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 do not change either. By the last SIMPLIFY, the literals of the final delays are all on undefined tables.
. Let be a rule of whose body is true in . If has no table, the body is true in , since , so . Otherwise follow the chain of . Each literal it reaches is called, so it is on a table, and it is true in . A positive literal on a true table either continues the chain at once (line L8 or L9) or waits until the first answer of , which comes because ends true (line L34). A negative literal with 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 in which every literal ends true, unless 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 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 became true before it, so there are none left after line L24, and the atom is in ; by induction on the order, every later one is in too. The answer has only such atoms as positive delayed atoms of , so . In the end all literals of are removed, and is true.
. Let be unfounded with respect to . Since , is also unfounded with respect to , so . The atoms of without a table are then in , and no atom of is a true table. Suppose that some atoms of are undefined tables, and let be the first completed component that contains one of them. Take such an atom and a final answer , from a rule . By (N), the body of is plus literals true in . The literals of are on undefined tables, so no literal of is false in , and the positive literals outside are in , which is disjoint from . As is unfounded, contains a positive literal . The table is undefined, and it is in or in a component completed before ; by the choice of , . So every final answer of every atom of has a positive delayed atom in . The last iteration of lines L23 to L27 for deleted nothing, so contained every atom of with an answer, including the atoms of . But the least fixpoint never adds a first atom of , because each of its answers needs another atom of to be in already. This is a contradiction, so every atom of 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 , , , and the query . All three tables end up in one component, with the negative waits of on and of on and then of on . Delaying gives the answers , and . At completion, has no answers and is false, so becomes true and the answer is deleted. The answer has no false literal, so SIMPLIFY keeps it, but in the well-founded model is false: is unfounded. Answer completion finds that 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 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 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 passes. This simple version recomputes the components and repeats the SIMPLIFY passes, which gives time in the worst case. The space is : 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 and have answers but are undefined.
- Answer completion. Without line L26, a positive loop through delayed literals can keep a false atom undefined. For , , , and the query , the answer survives simplification, but 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.
# 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag N2VDR9 Edit this page History Report an error Markdown