Algorithmadvanced
Alternating fixpoint computation
Also called Van Gelder alternating fixpoint.
Computes the well-founded model of a ground normal program by applying the reduct least model operator alternately, giving underestimates of the true atoms and overestimates of the non-false ones.
- Time
- O(n · s) worstΘ(s) best
- Space
- Θ(n + s) extra
- Where
- n = the number of atoms; s = the size of the program, the number of rules plus the number of body literals
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Allen Van Gelder, 1989
The alternating fixpoint computes the well-founded model of a finite ground normal program. It uses one operator, , the least model of the Gelfond-Lifschitz reduct . This operator is antimonotone: a larger blocks more negative literals and gives a smaller result. So the sequence alternates between underestimates of the true atoms and overestimates of the atoms that are not false. The underestimates grow and the overestimates shrink until both stop, after at most rounds for atoms. Van Gelder (1993) proved that the limit is the well-founded model. Each application of is a forward chaining pass in linear time, so the whole computation takes polynomial time.
In plain words
Some rules have conditions of the form "if this is not known". The well-founded model sorts each fact into true, false or unknown. The method uses one tool again and again: take a guess of what is true, let every negative condition on a fact in the guess fail, and see what the rules then prove. Start with the guess that nothing is true. Then no negative condition fails, and the rules prove a lot: an overestimate. Use the overestimate as the next guess. Now many negative conditions fail, and the rules prove less: an underestimate, and each fact in it is surely true. Keep going. The underestimates grow, the overestimates shrink, and both soon stop. What the last overestimate leaves out is false, the last underestimate is true, and the facts between them are unknown.
The problem
The input is a finite ground normal program : a set of rules over a set of atoms. The output is the well-founded model, a pair of disjoint sets of atoms: is the set of true atoms, the set of false atoms, and the other atoms are undefined. Van Gelder, Ross and Schlipf (1991) defined it as the least fixpoint of an operator built from unfounded sets; the well-founded semantics page gives the definition.
The algorithm
For , the reduct deletes each rule with some and deletes the negative literals of the other rules. is the least model of this definite program. Gelfond and Lifschitz write it ; a set is a stable model exactly when .
ALTERNATING-FIXPOINT(P) ▷ P is a finite ground normal program over the atoms A- 1
K ← ∅ - 2
U ← S(P, K) ▷ an overestimate of the atoms that are not false - 3
loop - 4
K' ← S(P, U) ▷ an underestimate of the true atoms - 5
if K' = K then return (K, A ∖ U) ▷ true atoms, false atoms - 6
K ← K' - 7
U ← S(P, K) S(P, J) ▷ the least model of the reduct P^J- 8
M ← ∅, Q ← an empty queue - 9
for each rule r = h ← pos, not neg of P do - 10
if neg ∩ J ≠ ∅ then count[r] ← −1 ▷ the reduct deletes r - 11
else count[r] ← |pos|; if count[r] = 0 and h ∉ M then add h to M and to Q - 12
while Q is not empty do - 13
b ← take the first atom of Q - 14
for each rule r with b ∈ pos(r) and count[r] > 0 do - 15
count[r] ← count[r] − 1 - 16
if count[r] = 0 and head(r) ∉ M then add head(r) to M and to Q - 17
return M
Lines L8 to L17 are the counter method of Dowling and Gallier (1984): each kept rule counts its positive body atoms that are not yet derived. The index from each atom to the rules where it occurs positively is built once, before line L1.
Example
The program describes a game: a position is won if some move leads to a position that is not won. The moves are , , , and , and means that position is won. Position 4 has no move, and the rule only puts in the program.
w1 ← not w2. w2 ← not w3. w3 ← not w4. w4 ← w4.
w5 ← not w6. w6 ← not w5.
| round | why | ||
|---|---|---|---|
| 0 | blocks no negative literal, and nothing derives | ||
| 1 | only survives the reduct by ; then blocks the rule for | ||
| 2 | , so the rule for survives | ||
| 3 | equal to : stop at line L5 |
The result is and . The atoms and are undefined: the cycle is a draw. This matches the game: position 4 is lost because it has no move, so 3 is won, 2 is lost and 1 is won. The program has the two stable models and , and both lie between and .
Correctness
The correctness proof has the details. is antimonotone, because a larger makes the reduct smaller. By induction, the increase, the decrease, and . When the loop stops, and . The proof that is the well-founded model has two halves. First, it is closed under the operator of Van Gelder, Ross and Schlipf: a rule whose body is true in it survives the reduct by , so its head is in ; and no atom of can be in an unfounded set, by induction on the stage of its derivation. So the least fixpoint of is below it. Second, for the well-founded model , the atoms outside form an unfounded set, and . With antimonotonicity, an induction on gives and .
Proof: The alternating fixpoint computes the well-founded modelfull
Let be a finite ground normal program and the set of its atoms. For , the reduct deletes each rule with a negative body atom in and deletes the negative literals of the other rules. It is a definite program, and is its least model. We write and for the positive and negative body atoms of a rule . The least model of a definite program is the union of the stages , , so we can argue by induction on the stage at which an atom is derived.
Definitions (Van Gelder, Ross and Schlipf 1991)
A partial interpretation is a pair of subsets of . A positive literal is true in if and false if ; a literal is true if and false if . Pairs are ordered componentwise: if and .
A set is unfounded with respect to if, for each and each rule with head , (i) some body literal of is false in , or (ii) . A union of unfounded sets is unfounded, so there is a greatest unfounded set . Let be the set of heads of the rules whose body literals are all true in , and . If , each literal false in is false in , so each set unfounded with respect to is unfounded with respect to ; and each body true in is true in . So is monotone. The well-founded model is the limit of , . Since is monotone, the increase, and since is finite, the limit is reached after finitely many steps and is a fixpoint of .
The iteration
The algorithm computes , , , and stops at the first with . It returns with and .
Lemma 1 (antimonotone). If , then .
Proof. Each rule that keeps has no negative body atom in , so none in , and keeps it too. So , and the least model of the smaller definite program is smaller.
Lemma 2 (shape of the sequence). For each : , , and .
Proof. . If , then by Lemma 1 , and then . For the third claim, . If , then , and so .
Termination. If , then and the sequence is constant from on. Before that point, grows strictly at each round, so this happens for some . At the end, and , and by Lemma 2.
Theorem (Van Gelder 1993)
The algorithm returns the well-founded model: and .
Step 1: . We show that . Then, by induction on , : it holds for , and by monotonicity.
First, . Take a rule whose body is true in : and . Then keeps as . Its body is in , which is a model of , so the head is in .
Second, . Let be unfounded with respect to . We show by induction on that is disjoint from the stage ; the union of these stages is . The stage is empty. Suppose that enters at stage through a rule with and . Since is unfounded, satisfies (i) or (ii). For (i), a positive body atom would be in , but ; or a negative body atom would be in , but . For (ii), a positive body atom would be in , but by induction is disjoint from . Each case is a contradiction.
Step 2: . We use two facts about the fixpoint of .
(a) is unfounded with respect to , so . Take and a rule with head . If , a negative literal of is false: case (i). Otherwise keeps . Since is a model of and does not contain , some is not in : case (ii).
(b) . By induction on the stage: an atom of the stage comes from a rule with , that is , and with in the stage , so in by induction. The body of is true in , so .
Now we show by induction on that and . . If , then by Lemma 1, so by (a). Then , so by Lemma 1 and (b).
Steps 1 and 2 give .
Consequences
Every stable model lies between and . If is stable, then . By induction : if , then , so . And . So every atom true in the well-founded model is in , and every atom false in it is not in .
A total well-founded model is the unique stable model. If , then , so is stable, and every stable model satisfies .
Running time
Let and let be the size of , the number of rules plus the number of body literals. The implementation computes in time with the counter method of Dowling and Gallier (1984): each rule kept by the reduct has a counter of the positive body atoms not yet derived, and each derived atom decrements the counters of the rules in which it occurs. Each atom enters the queue at most once, and each occurrence of an atom in a rule body is visited at most once. By the termination argument there are at most rounds, each with two calls of and one comparison of sets of size at most . The total time is .
What the tests check
The tests compute the well-founded model a second time from the definition: they iterate from , with the greatest unfounded set found by trying every subset of the atoms. The two results agree on 300 random programs with at most 7 atoms. The tests also check the counter method against the plain least model of lp.py, the monotone shape of the trace from Lemma 2, the bound on the number of rounds, the consequences above against brute force enumeration of the stable models, the totality of the well-founded model on random stratified programs, and the trace of the example on the page.
Complexity
Let be the number of rules plus the number of body literals. One call of takes time: each rule is visited once at lines L9 to L11, and each positive body occurrence at most once at line L14, because each atom enters the queue at most once. The sets grow strictly until the last round, so there are at most rounds and calls of . The total time is , and the space is for the index, the counters and the sets. The bound is reached: on a chain each round adds one atom to , starting from the end of the chain, so there are about rounds of cost each. If the first underestimate is empty, the loop stops after two calls, in time . The problem itself is in polynomial time, and for programs with variables and a fixed program it is P-complete in the size of the data.
Properties
- Deterministic and polynomial. There is no search: the result is one three-valued model, computed in time.
- Bounds on the stable models. Every stable model satisfies , so by induction for every . Atoms true in the well-founded model are in every stable model, and atoms false in it are in none.
- Total on stratified programs. For a stratified program, , and the result is the perfect model, which is also the unique stable model.
- Total means unique. If , then is a stable model, and by the bounds it is the only one.
- Monotone in the double step. is monotone, is its least fixpoint and is its greatest fixpoint.
Variants and improvements
- Kripke-Kleene semantics. Fitting (1985) iterates a three-valued version of the immediate consequence operator, without unfounded sets. It is cheaper but weaker: for it leaves undefined, where the well-founded model makes false.
- Component by component. Split the program along the strongly connected components of its dependency graph and compute the components in topological order, with the atoms of the lower components already decided. On a stratified program each component then needs a single least model computation.
- Faster methods. Lonc and Truszczyński (2001) studied the cost of computing the well-founded model and gave faster algorithms for some classes of programs.
- Goal-directed evaluation. SLG resolution computes the truth value of one query and evaluates only the part of the program that the query reaches.
- Approximation fixpoint theory. Denecker, Marek and Truszczyński generalized the construction to operators on any complete lattice, which gives well-founded semantics for default logic and autoepistemic logic in the same way.
When to use it
Use the alternating fixpoint to compute the whole well-founded model of a ground program bottom-up, for example after grounding. It is also a cheap first step for stable model search: the true atoms must be in every stable model and the false atoms in none, and if the model is total the search is over. For one query on a large program, a goal-directed method such as SLG resolution evaluates less of the program.
Pitfalls
- Odd and even steps. The sets are overestimates and the sets are underestimates. Returning an overestimate as the set of true atoms, or stopping at the first repeat of and pairing it with the wrong , gives a wrong model.
- Atoms with no rules. The false atoms are , where contains every atom of the program, also the atoms that occur only in rule bodies. If holds only the heads, these false atoms are lost.
- Undefined atoms can still follow. For , , , , the atom is in both stable models and , but it is undefined in the well-founded model, because . The well-founded model is a sound approximation of cautious reasoning, not a replacement for it.
- Recomputing from scratch. A naive version reruns a full fixpoint over all rules for each call of , and rescans all rules in each step of that fixpoint. This costs per call instead of .
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
# Part of https://algorithm.tamnd.com/alternating-fixpoint/. The authors are listed in prov/8YTFM5.jsonl.
"""The alternating fixpoint of Van Gelder (1993) for ground normal programs.
A program is a list of rules (head, pos, neg), as in lp.py. S(J) is the least
model of the Gelfond-Lifschitz reduct of the program by J. It is computed in
time linear in the size of the program by counting, for each rule, the
positive body atoms that are not yet derived.
well_founded(program) returns (true, false), two disjoint frozensets of atoms.
The atoms of the program in neither set are undefined. alternating_trace
returns the pairs (K_i, U_i) of the iteration.
"""
from collections import deque
def _atoms(program):
out = set()
for h, pos, neg in program:
out.add(h)
out.update(pos)
out.update(neg)
return out
class _Index:
"""The rules, with the list of the rules in which each atom occurs positively."""
def __init__(self, program):
self.rules = [(h, tuple(set(pos)), tuple(set(neg))) for h, pos, neg in program]
self.occurs = {}
for i, (_, pos, _) in enumerate(self.rules):
for b in pos:
self.occurs.setdefault(b, []).append(i)
def s(self, j):
"""The least model of the reduct by j, by forward chaining with counters."""
model, queue = set(), deque() # @line L8
count = []
for h, pos, neg in self.rules: # @line L9
if any(c in j for c in neg): # @line L10
count.append(-1)
continue
count.append(len(pos)) # @line L11
if not pos and h not in model:
model.add(h)
queue.append(h)
while queue: # @line L12
b = queue.popleft() # @line L13
for i in self.occurs.get(b, ()): # @line L14
if count[i] > 0:
count[i] -= 1 # @line L15
h = self.rules[i][0]
if count[i] == 0 and h not in model: # @line L16
model.add(h)
queue.append(h)
return frozenset(model) # @line L17
def least_model_of_reduct(program, j):
"""S(j): the least model of the reduct of the program by the set j."""
return _Index(program).s(j)
def alternating_trace(program):
"""The list of pairs (K_i, U_i) with K_0 = {}, U_i = S(K_i) and K_{i+1} = S(U_i), up to the fixpoint."""
index = _Index(program)
k = frozenset() # @line L1
u = index.s(k) # @line L2
trace = [(k, u)]
while True: # @line L3
k_next = index.s(u) # @line L4
if k_next == k: # @line L5
return trace
k = k_next # @line L6
u = index.s(k) # @line L7
trace.append((k, u))
def well_founded(program):
"""The well-founded model as (true, false): true = K, false = the atoms not in U = S(K)."""
k, u = alternating_trace(program)[-1]
return k, frozenset(_atoms(program) - u)
lp.py 79 lines
# 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
test_alternating_fixpoint.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alternating-fixpoint/. The authors are listed in prov/8YTFM5.jsonl.
import random
import unittest
from itertools import combinations
import lp
from alternating_fixpoint import alternating_trace, least_model_of_reduct, well_founded
def is_unfounded(program, u, true, false):
"""Van Gelder, Ross and Schlipf: each rule for an atom of u has a body literal false in (true, false) or a positive body atom in u."""
for h, pos, neg in program:
if h not in u:
continue
body_false = any(b in false for b in pos) or any(c in true for c in neg)
if not body_false and not any(b in u for b in pos):
return False
return True
def wfm_by_unfounded_sets(program):
"""The least fixpoint of W_P(T, F) = (T_P(T, F), the greatest unfounded set), 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):
if is_unfounded(program, set(u), true, false):
gus.update(u)
new_false = frozenset(gus)
if (new_true, new_false) == (true, false):
return true, false
true, false = new_true, new_false
def random_stratified(rng, n_atoms, n_rules):
"""Atom a has level a // 3; positive body atoms have a level at most that of the head, negative ones a lower level."""
program = []
for _ in range(n_rules):
h = rng.randrange(n_atoms)
same_or_lower = [a for a in range(n_atoms) if a // 3 <= h // 3]
lower = [a for a in range(n_atoms) if a // 3 < h // 3]
pos = tuple(rng.sample(same_or_lower, rng.randint(0, min(2, len(same_or_lower)))))
neg = tuple(rng.sample(lower, rng.randint(0, min(2, len(lower)))))
program.append((h, pos, neg))
return program
class TestAlternatingFixpoint(unittest.TestCase):
def test_least_model_of_reduct_matches_lp(self):
rng = random.Random(1)
for _ in range(300):
p = lp.random_program(rng, rng.randint(1, 8), rng.randint(0, 12))
j = frozenset(a for a in range(8) if rng.random() < 0.5)
self.assertEqual(least_model_of_reduct(p, j), lp.least_model(lp.reduct(p, j)))
def test_equals_unfounded_set_definition(self):
rng = random.Random(2)
for _ in range(300):
p = lp.random_program(rng, rng.randint(1, 7), rng.randint(0, 11))
self.assertEqual(well_founded(p), wfm_by_unfounded_sets(p), p)
def test_trace_is_monotone_and_short(self):
rng = random.Random(3)
for _ in range(300):
p = lp.random_program(rng, rng.randint(1, 10), rng.randint(0, 16))
trace = alternating_trace(p)
self.assertLessEqual(len(trace), len(lp.atoms(p)) + 1)
for (k0, u0), (k1, u1) in zip(trace, trace[1:]):
self.assertTrue(k0 < k1, "K grows strictly until the fixpoint")
self.assertTrue(u1 <= u0)
for k, u in trace:
self.assertTrue(k <= u)
def test_inside_every_stable_model(self):
rng = random.Random(4)
for _ in range(150):
p = lp.random_program(rng, rng.randint(1, 9), rng.randint(0, 14))
true, false = well_founded(p)
self.assertFalse(true & false)
models = lp.stable_models(p)
for m in models:
self.assertTrue(true <= m and not (false & m))
if len(true) + len(false) == len(lp.atoms(p)):
self.assertEqual(models, [true], "a total well-founded model is the unique stable model")
def test_stratified_programs_are_total(self):
rng = random.Random(5)
for _ in range(200):
p = random_stratified(rng, 9, rng.randint(1, 14))
true, false = well_founded(p)
self.assertEqual(true | false, frozenset(lp.atoms(p)))
self.assertEqual(lp.stable_models(p), [true])
def test_page_example(self):
# a <- not b. b <- not a. c <- not c. d <- not e. e <- e. f <- d, not c. g <- a.
a, b, c, d, e, f, g = "abcdefg"
p = [(a, (), (b,)), (b, (), (a,)), (c, (), (c,)), (d, (), (e,)), (e, (e,), ()), (f, (d,), (c,)), (g, (a,), ())]
trace = alternating_trace(p)
self.assertEqual(trace[0], (frozenset(), frozenset("abcdfg")))
self.assertEqual(trace[1], (frozenset("d"), frozenset("abcdfg")))
self.assertEqual(len(trace), 2)
self.assertEqual(well_founded(p), (frozenset("d"), frozenset("e")))
def test_win_move_game(self):
# win(x) <- move(x, y), not win(y) on the moves 1->2, 2->3, 3->4, 5->6, 6->5.
moves = [(1, 2), (2, 3), (3, 4), (5, 6), (6, 5)]
p = [(x, (), (y,)) for x, y in moves] + [(4, (4,), ())]
f = frozenset
self.assertEqual(alternating_trace(p), [(f(), f({1, 2, 3, 5, 6})), (f({3}), f({1, 3, 5, 6})), (f({1, 3}), f({1, 3, 5, 6}))])
true, false = well_founded(p)
self.assertEqual(true, frozenset({1, 3}))
self.assertEqual(false, frozenset({2, 4}))
def test_atom_in_every_stable_model_but_undefined(self):
# a <- not b. b <- not a. c <- a. c <- b.
p = [("a", (), ("b",)), ("b", (), ("a",)), ("c", ("a",), ()), ("c", ("b",), ())]
self.assertEqual(well_founded(p), (frozenset(), frozenset()))
self.assertEqual(lp.stable_models(p), [frozenset("ac"), frozenset("bc")])
def test_empty_program(self):
self.assertEqual(well_founded([]), (frozenset(), frozenset()))
if __name__ == "__main__":
unittest.main()
History
Van Gelder, Ross and Schlipf introduced the well-founded semantics at PODS 1988, with unfounded sets as the main tool, and published the journal version in 1991. In the same year, Gelfond and Lifschitz (1988) defined stable models with the reduct. Van Gelder (PODS 1989, journal version 1993) connected the two: the operator that maps a set to the least model of its reduct, applied twice, has the well-founded model as its least fixpoint. The construction later became the model for approximation fixpoint theory.
References
- Allen Van Gelder, The alternating fixpoint of logic programs with negation, Journal of Computer and System Sciences 47(1), 185 to 221 (1993), the alternating fixpoint construction and the proof that it gives the well-founded partial model
- 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, the operator W_P and the well-founded partial model
- Michael Gelfond and Vladimir Lifschitz, The stable model semantics for logic programming, in Robert A. Kowalski and Kenneth A. Bowen (eds.), Logic Programming: Proceedings of the Fifth International Conference and Symposium, MIT Press, 1070 to 1080 (1988), the reduct and the operator that maps a set of atoms to the least model of the reduct
- William F. Dowling and Jean H. Gallier, Linear-time algorithms for testing the satisfiability of propositional Horn formulae, Journal of Logic Programming 1(3), 267 to 284 (1984), the counter method that computes the least model of a definite program in linear time
- Zbigniew Lonc and Mirosław Truszczyński, On the problem of computing the well-founded semantics, Theory and Practice of Logic Programming 1(5), 591 to 609 (2001), the cost of the alternating fixpoint and faster methods for classes of programs
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 8YTFM5 Edit this page History Report an error Markdown