Algorithm Search⌘K

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
Properties
deterministic
Origin
Allen Van Gelder, 1989

The alternating fixpoint computes the well-founded model of a finite ground normal program. It uses one operator, S(J)S(J), the least model of the Gelfond-Lifschitz reduct PJP^J. This operator is antimonotone: a larger JJ blocks more negative literals and gives a smaller result. So the sequence ∅,S(∅),S(S(∅)),…\emptyset, S(\emptyset), S(S(\emptyset)), \ldots 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 n+1n + 1 rounds for nn atoms. Van Gelder (1993) proved that the limit is the well-founded model. Each application of SS 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 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 over a set AA of nn atoms. The output is the well-founded model, a pair (T,F)(T, F) of disjoint sets of atoms: TT is the set of true atoms, FF 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 J⊆AJ \subseteq A, the reduct PJP^J deletes each rule with some ci∈Jc_i \in J and deletes the negative literals of the other rules. S(J)S(J) is the least model of this definite program. Gelfond and Lifschitz write it ΓP(J)\Gamma_P(J); a set MM is a stable model exactly when S(M)=MS(M) = M.

  1. ALTERNATING-FIXPOINT(P) ▷ P is a finite ground normal program over the atoms A
  2. 1K ← ∅
  3. 2U ← S(P, K) ▷ an overestimate of the atoms that are not false
  4. 3loop
  5. 4K' ← S(P, U) ▷ an underestimate of the true atoms
  6. 5if K' = K then return (K, A ∖ U) ▷ true atoms, false atoms
  7. 6K ← K'
  8. 7U ← S(P, K)
  9. S(P, J) ▷ the least model of the reduct P^J
  10. 8M ← ∅, Q ← an empty queue
  11. 9for each rule r = h ← pos, not neg of P do
  12. 10if neg ∩ J ≠ ∅ then count[r] ← −1 ▷ the reduct deletes r
  13. 11else count[r] ← |pos|; if count[r] = 0 and h ∉ M then add h to M and to Q
  14. 12while Q is not empty do
  15. 13b ← take the first atom of Q
  16. 14for each rule r with b ∈ pos(r) and count[r] > 0 do
  17. 15count[r] ← count[r] − 1
  18. 16if count[r] = 0 and head(r) ∉ M then add head(r) to M and to Q
  19. 17return 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 1→21 \to 2, 2→32 \to 3, 3→43 \to 4, 5→65 \to 6 and 6→56 \to 5, and wiw_i means that position ii is won. Position 4 has no move, and the rule w4←w4w_4 \leftarrow w_4 only puts w4w_4 in the program.

w1 ← not w2.   w2 ← not w3.   w3 ← not w4.   w4 ← w4.
w5 ← not w6.   w6 ← not w5.
round KiK_i Ui=S(Ki)U_i = S(K_i) why
0 ∅\emptyset {w1,w2,w3,w5,w6}\{w_1, w_2, w_3, w_5, w_6\} K0K_0 blocks no negative literal, and nothing derives w4w_4
1 S(U0)={w3}S(U_0) = \{w_3\} {w1,w3,w5,w6}\{w_1, w_3, w_5, w_6\} only w3←not w4w_3 \leftarrow \mathit{not}\ w_4 survives the reduct by U0U_0; then w3∈K1w_3 \in K_1 blocks the rule for w2w_2
2 S(U1)={w1,w3}S(U_1) = \{w_1, w_3\} {w1,w3,w5,w6}\{w_1, w_3, w_5, w_6\} w2∉U1w_2 \notin U_1, so the rule for w1w_1 survives
3 S(U2)={w1,w3}S(U_2) = \{w_1, w_3\} equal to K2K_2: stop at line L5

The result is T={w1,w3}T = \{w_1, w_3\} and F=A∖U2={w2,w4}F = A \setminus U_2 = \{w_2, w_4\}. The atoms w5w_5 and w6w_6 are undefined: the cycle 5→6→55 \to 6 \to 5 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 {w1,w3,w5}\{w_1, w_3, w_5\} and {w1,w3,w6}\{w_1, w_3, w_6\}, and both lie between KK and UU.

Correctness

The correctness proof has the details. SS is antimonotone, because a larger JJ makes the reduct smaller. By induction, the KiK_i increase, the UiU_i decrease, and Ki⊆UiK_i \subseteq U_i. When the loop stops, S(U)=KS(U) = K and S(K)=US(K) = U. The proof that (K,A∖U)(K, A \setminus U) is the well-founded model has two halves. First, it is closed under the operator WPW_P of Van Gelder, Ross and Schlipf: a rule whose body is true in it survives the reduct by UU, so its head is in S(U)=KS(U) = K; and no atom of S(K)=US(K) = U can be in an unfounded set, by induction on the stage of its derivation. So the least fixpoint of WPW_P is below it. Second, for the well-founded model (T∗,F∗)(T^*, F^*), the atoms outside S(T∗)S(T^*) form an unfounded set, and S(A∖F∗)⊆T∗S(A \setminus F^*) \subseteq T^*. With antimonotonicity, an induction on ii gives Ki⊆T∗K_i \subseteq T^* and A∖Ui⊆F∗A \setminus U_i \subseteq F^*.

Proof: The alternating fixpoint computes the well-founded modelfull

Let PP be a finite ground normal program and AA the set of its atoms. For J⊆AJ \subseteq A, the reduct PJP^J deletes each rule with a negative body atom in JJ and deletes the negative literals of the other rules. It is a definite program, and S(J)S(J) is its least model. We write pos(r)\mathrm{pos}(r) and neg(r)\mathrm{neg}(r) for the positive and negative body atoms of a rule rr. The least model of a definite program DD is the union of the stages TD↑0=∅T_D \uparrow 0 = \emptyset, TD↑(k+1)=TD(TD↑k)T_D \uparrow (k+1) = T_D(T_D \uparrow k), 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 I=(T,F)I = (T, F) of subsets of AA. A positive literal bb is true in II if b∈Tb \in T and false if b∈Fb \in F; a literal not c\mathit{not}\ c is true if c∈Fc \in F and false if c∈Tc \in T. Pairs are ordered componentwise: (T,F)≤(T′,F′)(T, F) \le (T', F') if T⊆T′T \subseteq T' and F⊆F′F \subseteq F'.

A set X⊆AX \subseteq A is unfounded with respect to II if, for each a∈Xa \in X and each rule rr with head aa, (i) some body literal of rr is false in II, or (ii) pos(r)∩X≠∅\mathrm{pos}(r) \cap X \neq \emptyset. A union of unfounded sets is unfounded, so there is a greatest unfounded set GUS(I)\mathrm{GUS}(I). Let TP(I)T_P(I) be the set of heads of the rules whose body literals are all true in II, and WP(I)=(TP(I),GUS(I))W_P(I) = (T_P(I), \mathrm{GUS}(I)). If I≤I′I \le I', each literal false in II is false in I′I', so each set unfounded with respect to II is unfounded with respect to I′I'; and each body true in II is true in I′I'. So WPW_P is monotone. The well-founded model is the limit (T∗,F∗)(T^*, F^*) of I0=(∅,∅)I_0 = (\emptyset, \emptyset), Ik+1=WP(Ik)I_{k+1} = W_P(I_k). Since WPW_P is monotone, the IkI_k increase, and since AA is finite, the limit is reached after finitely many steps and is a fixpoint of WPW_P.

The iteration

The algorithm computes K0=∅K_0 = \emptyset, Ui=S(Ki)U_i = S(K_i), Ki+1=S(Ui)K_{i+1} = S(U_i), and stops at the first ii with Ki+1=KiK_{i+1} = K_i. It returns (K,A∖U)(K, A \setminus U) with K=KiK = K_i and U=UiU = U_i.

Lemma 1 (antimonotone). If J⊆J′J \subseteq J', then S(J′)⊆S(J)S(J') \subseteq S(J).

Proof. Each rule that PJ′P^{J'} keeps has no negative body atom in J′J', so none in JJ, and PJP^J keeps it too. So PJ′⊆PJP^{J'} \subseteq P^J, and the least model of the smaller definite program is smaller. □\square

Lemma 2 (shape of the sequence). For each ii: Ki⊆Ki+1K_i \subseteq K_{i+1}, Ui+1⊆UiU_{i+1} \subseteq U_i, and Ki⊆UiK_i \subseteq U_i.

Proof. K0=∅⊆K1K_0 = \emptyset \subseteq K_1. If Ki⊆Ki+1K_i \subseteq K_{i+1}, then by Lemma 1 Ui+1=S(Ki+1)⊆S(Ki)=UiU_{i+1} = S(K_{i+1}) \subseteq S(K_i) = U_i, and then Ki+2=S(Ui+1)⊇S(Ui)=Ki+1K_{i+2} = S(U_{i+1}) \supseteq S(U_i) = K_{i+1}. For the third claim, K0=∅⊆U0K_0 = \emptyset \subseteq U_0. If Ki⊆UiK_i \subseteq U_i, then Ki+1=S(Ui)⊆S(Ki)=UiK_{i+1} = S(U_i) \subseteq S(K_i) = U_i, and so Ui+1=S(Ki+1)⊇S(Ui)=Ki+1U_{i+1} = S(K_{i+1}) \supseteq S(U_i) = K_{i+1}. □\square

Termination. If Ki+1=KiK_{i+1} = K_i, then Ui+1=UiU_{i+1} = U_i and the sequence is constant from ii on. Before that point, KK grows strictly at each round, so this happens for some i≤∣A∣i \le |A|. At the end, S(K)=US(K) = U and S(U)=KS(U) = K, and K⊆UK \subseteq U by Lemma 2.

Theorem (Van Gelder 1993)

The algorithm returns the well-founded model: T∗=KT^* = K and F∗=A∖UF^* = A \setminus U.

Step 1: (T∗,F∗)≤(K,A∖U)(T^*, F^*) \le (K, A \setminus U). We show that WP(K,A∖U)≤(K,A∖U)W_P(K, A \setminus U) \le (K, A \setminus U). Then, by induction on kk, Ik≤(K,A∖U)I_k \le (K, A \setminus U): it holds for I0I_0, and Ik+1=WP(Ik)≤WP(K,A∖U)≤(K,A∖U)I_{k+1} = W_P(I_k) \le W_P(K, A \setminus U) \le (K, A \setminus U) by monotonicity.

First, TP(K,A∖U)⊆KT_P(K, A \setminus U) \subseteq K. Take a rule rr whose body is true in (K,A∖U)(K, A \setminus U): pos(r)⊆K\mathrm{pos}(r) \subseteq K and neg(r)∩U=∅\mathrm{neg}(r) \cap U = \emptyset. Then PUP^U keeps rr as h←pos(r)h \leftarrow \mathrm{pos}(r). Its body is in K=S(U)K = S(U), which is a model of PUP^U, so the head hh is in KK.

Second, GUS(K,A∖U)⊆A∖U\mathrm{GUS}(K, A \setminus U) \subseteq A \setminus U. Let XX be unfounded with respect to (K,A∖U)(K, A \setminus U). We show by induction on kk that XX is disjoint from the stage TPK↑kT_{P^K} \uparrow k; the union of these stages is S(K)=US(K) = U. The stage 00 is empty. Suppose that a∈Xa \in X enters at stage k+1k + 1 through a rule rr with neg(r)∩K=∅\mathrm{neg}(r) \cap K = \emptyset and pos(r)⊆TPK↑k\mathrm{pos}(r) \subseteq T_{P^K} \uparrow k. Since XX is unfounded, rr satisfies (i) or (ii). For (i), a positive body atom would be in A∖UA \setminus U, but pos(r)⊆TPK↑k⊆U\mathrm{pos}(r) \subseteq T_{P^K} \uparrow k \subseteq U; or a negative body atom would be in KK, but neg(r)∩K=∅\mathrm{neg}(r) \cap K = \emptyset. For (ii), a positive body atom would be in XX, but by induction TPK↑kT_{P^K} \uparrow k is disjoint from XX. Each case is a contradiction.

Step 2: (K,A∖U)≤(T∗,F∗)(K, A \setminus U) \le (T^*, F^*). We use two facts about the fixpoint (T∗,F∗)(T^*, F^*) of WPW_P.

(a) A∖S(T∗)A \setminus S(T^*) is unfounded with respect to (T∗,F∗)(T^*, F^*), so A∖S(T∗)⊆F∗A \setminus S(T^*) \subseteq F^*. Take a∉S(T∗)a \notin S(T^*) and a rule rr with head aa. If neg(r)∩T∗≠∅\mathrm{neg}(r) \cap T^* \neq \emptyset, a negative literal of rr is false: case (i). Otherwise PT∗P^{T^*} keeps rr. Since S(T∗)S(T^*) is a model of PT∗P^{T^*} and does not contain aa, some b∈pos(r)b \in \mathrm{pos}(r) is not in S(T∗)S(T^*): case (ii).

(b) S(A∖F∗)⊆T∗S(A \setminus F^*) \subseteq T^*. By induction on the stage: an atom hh of the stage k+1k + 1 comes from a rule rr with neg(r)∩(A∖F∗)=∅\mathrm{neg}(r) \cap (A \setminus F^*) = \emptyset, that is neg(r)⊆F∗\mathrm{neg}(r) \subseteq F^*, and with pos(r)\mathrm{pos}(r) in the stage kk, so in T∗T^* by induction. The body of rr is true in (T∗,F∗)(T^*, F^*), so h∈TP(T∗,F∗)=T∗h \in T_P(T^*, F^*) = T^*.

Now we show by induction on ii that Ki⊆T∗K_i \subseteq T^* and A∖Ui⊆F∗A \setminus U_i \subseteq F^*. K0=∅⊆T∗K_0 = \emptyset \subseteq T^*. If Ki⊆T∗K_i \subseteq T^*, then Ui=S(Ki)⊇S(T∗)U_i = S(K_i) \supseteq S(T^*) by Lemma 1, so A∖Ui⊆A∖S(T∗)⊆F∗A \setminus U_i \subseteq A \setminus S(T^*) \subseteq F^* by (a). Then Ui⊇A∖F∗U_i \supseteq A \setminus F^*, so Ki+1=S(Ui)⊆S(A∖F∗)⊆T∗K_{i+1} = S(U_i) \subseteq S(A \setminus F^*) \subseteq T^* by Lemma 1 and (b).

Steps 1 and 2 give (T∗,F∗)=(K,A∖U)(T^*, F^*) = (K, A \setminus U). □\square

Consequences

Every stable model lies between KK and UU. If MM is stable, then S(M)=MS(M) = M. By induction Ki⊆MK_i \subseteq M: if Ki⊆MK_i \subseteq M, then Ui=S(Ki)⊇S(M)=MU_i = S(K_i) \supseteq S(M) = M, so Ki+1=S(Ui)⊆S(M)=MK_{i+1} = S(U_i) \subseteq S(M) = M. And M=S(M)⊆S(K)=UM = S(M) \subseteq S(K) = U. So every atom true in the well-founded model is in MM, and every atom false in it is not in MM.

A total well-founded model is the unique stable model. If K=UK = U, then S(K)=U=KS(K) = U = K, so KK is stable, and every stable model MM satisfies K⊆M⊆U=KK \subseteq M \subseteq U = K.

Running time

Let n=∣A∣n = |A| and let ss be the size of PP, the number of rules plus the number of body literals. The implementation computes S(J)S(J) in O(s)O(s) 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 n+1n + 1 rounds, each with two calls of SS and one comparison of sets of size at most nn. The total time is O(n⋅s)O(n \cdot s).

What the tests check

The tests compute the well-founded model a second time from the definition: they iterate WPW_P from (∅,∅)(\emptyset, \emptyset), 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 ss be the number of rules plus the number of body literals. One call of SS takes Θ(s)\Theta(s) 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 KiK_i grow strictly until the last round, so there are at most n+1n + 1 rounds and O(n)O(n) calls of SS. The total time is O(n⋅s)O(n \cdot s), and the space is Θ(n+s)\Theta(n + s) for the index, the counters and the sets. The bound is reached: on a chain w1←not w2,…,wn−1←not wnw_1 \leftarrow \mathit{not}\ w_2, \ldots, w_{n-1} \leftarrow \mathit{not}\ w_n each round adds one atom to KK, starting from the end of the chain, so there are about n/2n/2 rounds of cost Θ(n)\Theta(n) each. If the first underestimate S(S(∅))S(S(\emptyset)) is empty, the loop stops after two calls, in time Θ(s)\Theta(s). 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 O(n⋅s)O(n \cdot s) time.
  • Bounds on the stable models. Every stable model MM satisfies S(M)=MS(M) = M, so by induction Ki⊆M⊆UiK_i \subseteq M \subseteq U_i for every ii. 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, K=UK = U, and the result is the perfect model, which is also the unique stable model.
  • Total means unique. If K=UK = U, then KK is a stable model, and by the bounds it is the only one.
  • Monotone in the double step. S∘SS \circ S is monotone, KK is its least fixpoint and U=S(K)U = S(K) 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 p←pp \leftarrow p it leaves pp undefined, where the well-founded model makes pp 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 S(Ki)S(K_i) are overestimates and the sets S(Ui)S(U_i) are underestimates. Returning an overestimate as the set of true atoms, or stopping at the first repeat of UU and pairing it with the wrong KK, gives a wrong model.
  • Atoms with no rules. The false atoms are A∖UA \setminus U, where AA contains every atom of the program, also the atoms that occur only in rule bodies. If AA holds only the heads, these false atoms are lost.
  • Undefined atoms can still follow. For a←not ba \leftarrow \mathit{not}\ b, b←not ab \leftarrow \mathit{not}\ a, c←ac \leftarrow a, c←bc \leftarrow b, the atom cc is in both stable models {a,c}\{a, c\} and {b,c}\{b, c\}, but it is undefined in the well-founded model, because K=∅K = \emptyset. 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 SS, and rescans all rules in each step of that fixpoint. This costs O(n⋅s)O(n \cdot s) per call instead of O(s)O(s).

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.

alternating_fixpoint.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • 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