Algorithm Search⌘K

Algorithmadvanced

Smodels algorithm

Also called Simons-Niemela-Soininen search.

Searches for stable models by branching on atoms and propagating with well-founded and lookahead reasoning, in the style of DPLL.

Time
O(2^n · n^3 · s) worst
Space
O(n + s) extra
Where
n = the number of atoms; s = the size of the program, the number of rules plus the number of literals
Properties
deterministic
Origin
Patrik Simons, Ilkka Niemelä, Timo Soininen, 2002

The smodels algorithm finds the stable models of a ground logic program by search. It works like DPLL: it keeps a partial assignment of truth values to atoms, extends it by propagation, and branches on an open atom when propagation stops. The propagation has two parts. The first follows the rules forward and backward, much like unit propagation. The second computes an upper bound on the atoms that can still be derived, as in the well-founded semantics, and makes every other atom false. This second part is what separates stable models from the models of the Clark completion.

In plain words

You want to pick a set of facts that the rules justify, with no fact that only supports itself in a circle. Smodels guesses one fact at a time, true or false. After each guess it works out what must follow. A rule whose conditions all hold forces its conclusion. A fact with no rule left that could prove it must be false. A true fact with only one rule left that could prove it forces the conditions of that rule. Then it asks which facts could still be proved at all from the rules that are not blocked yet, and every other fact becomes false. If the guess leads to a contradiction, it tries the other value. Before it guesses, it also tests each open fact both ways, and a value that fails at once is never guessed.

The problem

The input is a finite ground program PP over a set AA of nn atoms. Its rules are normal rules h←b1,…,bm,not c1,…,not ckh \leftarrow b_1, \ldots, b_m, \mathit{not}\ c_1, \ldots, \mathit{not}\ c_k, choice rules {h1,…,hj}←b1,…,not ck\{h_1, \ldots, h_j\} \leftarrow b_1, \ldots, \mathit{not}\ c_k, and constraints ←b1,…,not ck\leftarrow b_1, \ldots, \mathit{not}\ c_k. The output is the set of stable models of PP, or one of them, or the answer that there is none. The existence question is NP-complete for normal programs, by the NP-completeness theorem, so the search is exponential in the worst case. This is the propositional case: programs with variables are first ground.

The algorithm

A partial assignment aa maps some atoms to true or false. A body is true under aa if every literal in it is true, false if some literal in it is false, and open otherwise. A rule is live if its body is not false.

  1. SMODELS(P, a) ▷ a is a partial assignment; returns the stable models that extend it
  2. 1try a ← LOOKAHEAD(P, EXPAND(P, a)) on conflict return ∅
  3. 2if a assigns every atom then return {the set of true atoms of a}
  4. 3x, v ← the open atom and value chosen by the heuristic
  5. 4return SMODELS(P, a ∪ {x ↦ v}) ∪ SMODELS(P, a ∪ {x ↦ ¬v})
  6. EXPAND(P, a)
  7. 5repeat
  8. 6a ← ATLEAST(P, a)
  9. 7U ← the least set closed under: for each normal or choice rule r with no negative atom true in a
  10. 8and pos(r) ⊆ U, add each head h of r that is not false in a ▷ the upper closure
  11. 9make every atom outside U false
  12. 10until a does not change
  13. 11return a
  14. ATLEAST(P, a) ▷ repeat until no rule applies; a clash is a conflict
  15. 12R1: a normal rule with a true body makes its head true
  16. 13R2: an atom that is the head of no live rule becomes false
  17. 14R3: a true atom with exactly one live rule makes every literal of that body true
  18. 15R4: a constraint, or a normal rule with a false head, must not get a true body:
  19. 16if all its literals but one are true, make the last one false
  20. LOOKAHEAD(P, a)
  21. 17for each open atom x and each value v do
  22. 18if EXPAND(P, a ∪ {x ↦ v}) gives a conflict then
  23. 19a ← EXPAND(P, a ∪ {x ↦ ¬v}) and restart the loop at L17
  24. 20return a

Lines L7 to L9 are the ATMOST step. In the real system, ATLEAST and ATMOST keep a counter per rule and a queue, so each runs in time linear in the size of the program. The heuristic at line L3 uses the sizes that LOOKAHEAD computes: the Python code branches on the atom whose two expansions assign the most atoms in the worse case, and tries first the value with the larger expansion.

Example

Take the program

p←not q.q←not p.r←p.r←s.s←r.←not r.p \leftarrow \mathit{not}\ q. \quad q \leftarrow \mathit{not}\ p. \quad r \leftarrow p. \quad r \leftarrow s. \quad s \leftarrow r. \quad \leftarrow \mathit{not}\ r.

Its completion has two models, {p,r,s}\{p, r, s\} and {q,r,s}\{q, r, s\}. In the second one, rr and ss support only each other. The only stable model is {p,r,s}\{p, r, s\}.

step rule assignment
EXPAND at the root R4 on the constraint: its one literal not r\mathit{not}\ r must be false rr true
R1 on s←rs \leftarrow r ss true
ATMOST: the upper closure is {p,q,r,s}\{p, q, r, s\}, no change {r,s}\{r, s\} true, p,qp, q open
LOOKAHEAD, try pp false R4 on p←not qp \leftarrow \mathit{not}\ q: the head is false, so not q\mathit{not}\ q must be false qq true
ATMOST: r←pr \leftarrow p is blocked, and rr, ss need each other, so the upper closure is {q}\{q\} rr false, but rr is true: conflict
LOOKAHEAD fixes pp true R2: q←not pq \leftarrow \mathit{not}\ p is no longer live qq false
L2 every atom is assigned return {p,r,s}\{p, r, s\}

The search visits one node and makes no guess. Without LOOKAHEAD, the code branches on pp, finds the model on the true branch and a conflict on the false branch: three nodes and one conflict. The rules R1 to R4 alone cannot see the conflict, because q,r,sq, r, s true and pp false is a model of the completion. Only the upper closure finds it.

Correctness

The correctness proof has the details. Every step keeps every stable model MM that agrees with the current assignment. R1 and R4 hold because MM is a model of PP. R2 and R3 hold because each atom of MM is the head of a rule whose body MM satisfies. ATMOST holds because MM is the least model of its reduct, and each stage of that least model lies inside the upper closure. LOOKAHEAD only fixes a value whose opposite leads to a conflict. Conversely, at a total assignment with no conflict, R1 makes the set MM of true atoms a model of the reduct PMP^M, and ATMOST makes MM a subset of the least model of PMP^M, so MM is stable. Branching on both values of an atom covers every stable model exactly once.

Proof: The smodels search returns exactly the stable modelsfull

Let PP be a finite ground program over a set AA of nn atoms. It has normal rules h←Bh \leftarrow B, choice rules {h1,…,hk}←B\{h_1, \ldots, h_k\} \leftarrow B and constraints ←B\leftarrow B, where a body BB is b1,…,bm,not c1,…,not cjb_1, \ldots, b_m, \mathit{not}\ c_1, \ldots, \mathit{not}\ c_j. We write pos(B)\mathrm{pos}(B) and neg(B)\mathrm{neg}(B) for the positive and negative atoms of BB. A set M⊆AM \subseteq A satisfies BB if pos(B)⊆M\mathrm{pos}(B) \subseteq M and neg(B)∩M=∅\mathrm{neg}(B) \cap M = \emptyset.

Stable models of programs with choice rules

The reduct PMP^M deletes every rule whose body has not c\mathit{not}\ c with c∈Mc \in M, and every constraint. Each normal rule h←Bh \leftarrow B that is left becomes h←pos(B)h \leftarrow \mathrm{pos}(B). Each choice rule {H}←B\{H\} \leftarrow B that is left becomes the rules h←pos(B)h \leftarrow \mathrm{pos}(B) for h∈H∩Mh \in H \cap M. The reduct is a definite program. MM is a stable model of PP if MM is the least model of PMP^M and MM satisfies no constraint body. For a program with only normal rules this is the definition of Gelfond and Lifschitz (1988). For choice rules it is the definition of Simons, Niemelä and Soininen (2002) restricted to choice rules, in the reduct form used by Gebser, Kaminski, Kaufmann and Schaub (2012).

Lemma 1 (properties of a stable model). Let MM be a stable model of PP.

  1. If MM satisfies the body of a normal rule h←Bh \leftarrow B, then h∈Mh \in M.
  2. Each a∈Ma \in M is the head of a normal rule, or one of the heads of a choice rule, whose body MM satisfies.
  3. MM satisfies no constraint body.

Proof. (1) The rule is kept in PMP^M as h←pos(B)h \leftarrow \mathrm{pos}(B) with pos(B)⊆M\mathrm{pos}(B) \subseteq M. MM is a model of PMP^M, so h∈Mh \in M. (2) aa is in the least model of PMP^M, so some rule a←pos(B)a \leftarrow \mathrm{pos}(B) of PMP^M has pos(B)⊆M\mathrm{pos}(B) \subseteq M. That rule comes from a rule of PP with aa in its head and neg(B)∩M=∅\mathrm{neg}(B) \cap M = \emptyset. (3) holds by the definition. □\square

The procedures

A partial assignment aa maps some atoms to true or false. MM agrees with aa if a(x)=truea(x) = \mathrm{true} implies x∈Mx \in M and a(x)=falsea(x) = \mathrm{false} implies x∉Mx \notin M. A body is true under aa if all its literals are true, false if one of its literals is false, and open otherwise. A rule is live for aa if its body is not false.

ATLEAST applies four rules until none of them changes aa:

  • (R1) if the body of a normal rule h←Bh \leftarrow B is true, make hh true;
  • (R2) if an atom has no live rule with that atom in the head, make it false;
  • (R3) if an atom is true and has exactly one live rule with that atom in the head, make every literal of that body true;
  • (R4) for a constraint, or a normal rule whose head is false: if the body is true, report a conflict; if exactly one literal of the body is open and the others are true, make that literal false.

ATMOST computes the upper closure U(a)U(a): the least set that contains each head hh with a(h)≠falsea(h) \neq \mathrm{false} of each normal or choice rule rr with pos(r)⊆U(a)\mathrm{pos}(r) \subseteq U(a) and no c∈neg(r)c \in \mathrm{neg}(r) true under aa. It makes every atom outside U(a)U(a) false. EXPAND repeats ATLEAST and ATMOST until neither changes aa. Any step that would give an atom both values raises a conflict. LOOKAHEAD tries both values of each open atom; when EXPAND of one value gives a conflict, it fixes the other value and expands again. SEARCH calls EXPAND and LOOKAHEAD. On a conflict it returns nothing. On a total assignment it returns the set of true atoms. Otherwise it picks an open atom xx and calls itself with xx true and with xx false.

Lemma 2 (each step keeps every stable model). Let MM be a stable model of PP that agrees with aa. Then MM agrees with the result of each rule (R1) to (R4), with the result of ATMOST, and with the result of LOOKAHEAD, and none of these steps reports a conflict.

Proof. (R1) The body is true under aa, so MM satisfies it, and h∈Mh \in M by Lemma 1(1). (R2) Each rule with xx in its head has a body that is false under aa, so MM does not satisfy it, and x∉Mx \notin M by Lemma 1(2). (R3) By Lemma 1(2), MM satisfies the body of a rule with xx in the head, and that rule must be live, so it is the one live rule. So MM satisfies its body. (R4) If MM satisfied the body, then MM would satisfy a constraint body, against Lemma 1(3), or MM would satisfy the body of a normal rule with h∉Mh \notin M, against Lemma 1(1). So the body is not true under aa, and when one literal is open and the others are true, MM makes that literal false.

ATMOST. We show M⊆U(a)M \subseteq U(a). MM is the union of the stages T↑kT \uparrow k of the immediate consequence operator of PMP^M. By induction on kk: an atom hh of the stage k+1k + 1 comes from a rule rr of PP with pos(r)⊆T↑k⊆U(a)\mathrm{pos}(r) \subseteq T \uparrow k \subseteq U(a) and neg(r)∩M=∅\mathrm{neg}(r) \cap M = \emptyset. Since MM agrees with aa, no c∈neg(r)c \in \mathrm{neg}(r) is true under aa. And h∈Mh \in M, so a(h)≠falsea(h) \neq \mathrm{false}. So h∈U(a)h \in U(a). (For a choice rule the reduct has h←pos(r)h \leftarrow \mathrm{pos}(r) only for h∈Mh \in M, and the same argument applies.) So each atom that ATMOST makes false is not in MM.

EXPAND is a sequence of these steps. If one value of an open atom xx expands to a conflict, then no stable model that agrees with aa has that value for xx, by what we just showed, so MM has the other value. Hence LOOKAHEAD keeps MM too. □\square

Lemma 3 (a total assignment that expands with no conflict is a stable model). Let aa be total, with no conflict after EXPAND, and let MM be its set of true atoms. Then MM is a stable model of PP.

Proof. Let LL be the least model of PMP^M. First, MM is a model of PMP^M. A normal rule of PMP^M comes from h←Bh \leftarrow B with neg(B)∩M=∅\mathrm{neg}(B) \cap M = \emptyset. If pos(B)⊆M\mathrm{pos}(B) \subseteq M, the body is true under aa, and (R1) gives h∈Mh \in M. A choice rule gives rules only for heads in MM. So L⊆ML \subseteq M. Second, ATMOST made every atom outside U(a)U(a) false and found no conflict, so M⊆U(a)M \subseteq U(a). Under a total assignment, U(a)U(a) is built from the rules whose negative atoms are not in MM, and it adds only heads in MM. These are exactly the rules of PMP^M, so by induction on the construction U(a)⊆LU(a) \subseteq L. Together, M=LM = L. Finally, (R4) reports a conflict for a constraint with a true body, so MM satisfies no constraint body. □\square

Theorem. SEARCH called on the empty assignment returns each stable model of PP exactly once, and nothing else.

Proof. Each call either returns, or assigns one more atom in each of its two child calls. So the recursion depth is at most nn and the search ends. A returned set is a stable model by Lemma 3. Let MM be a stable model. By Lemma 2, along the path of calls that always takes the branch value that MM gives, no conflict occurs and MM agrees with every assignment. The path ends at a total assignment, which is MM. Two different leaves differ on the atom of their last common branch point, so each stable model is returned once. □\square

Running time

Let ss be the size of PP, the number of rules plus the number of literals in them. With counters per rule and a queue, as in the counter method of Dowling and Gallier (1984), ATLEAST and ATMOST each take O(s)O(s) time per call. Each round of EXPAND other than the last assigns at least one atom, so EXPAND takes O(n⋅s)O(n \cdot s) time. LOOKAHEAD runs at most 2n2n expansions for each atom that it fixes, and it fixes at most nn atoms, so it takes O(n3⋅s)O(n^3 \cdot s) time. The search tree has at most 2n2^n leaves. The worst-case time is O(2n⋅n3⋅s)O(2^n \cdot n^3 \cdot s). The Python code recomputes each fixpoint with repeated scans, which adds a factor nn to each bound. An exponential worst case is expected: deciding whether a normal program has a stable model is NP-complete.

What the tests check

The tests compare the output of stable_models with a brute force search over all subsets of the atoms that tests the reduct definition above directly. They do this on 300 random normal programs with at most 6 atoms, with and without LOOKAHEAD, and on 250 random programs with choice rules and constraints. They also check that the normal translation of choice rules, h←B,not h′h \leftarrow B, \mathit{not}\ h' and h′←not hh' \leftarrow \mathit{not}\ h, gives the same models after the projection to the original atoms, with one translated model for each direct model. Small cases check that ATMOST makes the atoms of a positive loop false with no search, and that a constraint with a true body is a conflict.

Complexity

Let ss be the number of rules plus the number of literals. With counters, ATLEAST and ATMOST take O(s)O(s) time, so EXPAND takes O(n⋅s)O(n \cdot s): each round but the last assigns an atom. LOOKAHEAD runs at most 2n2n expansions for each of at most nn atoms that it fixes, which gives O(n3⋅s)O(n^3 \cdot s) per node. The search tree has at most 2n2^n leaves, so the worst-case time is O(2n⋅n3⋅s)O(2^n \cdot n^3 \cdot s). With a trail of assignments that is undone on backtracking, the extra space is O(n+s)O(n + s). The Python code copies the assignment at each node and recomputes each fixpoint by repeated scans, which costs an extra factor nn in time and O(n2)O(n^2) space for the copies. No algorithm is expected to avoid the exponential factor, since the problem is NP-complete.

Properties

  • Complete and sound. It returns every stable model and nothing else, and it can stop after the first one.
  • Stronger than completion. The upper closure removes every atom outside the least model of the reduct. On a tight program this adds nothing; on a program with positive loops it is necessary.
  • Contains the well-founded model. At the root, before any guess, EXPAND makes every atom that is true in the well-founded model true and every atom that is false in it false, since ATMOST removes unfounded atoms and R1 derives the rest.
  • No learning. The search backtracks chronologically and forgets why a branch failed.

Variants and improvements

  • Weight constraint rules. Simons, Niemelä and Soininen (2002) extend the same four rules and the upper closure to cardinality and weight constraints, so that a rule such as 1{a,b,c} 21 \{a, b, c\}\ 2 is handled directly and not through a translation.
  • Conflict-driven learning. Conflict-driven answer set solving keeps the same two propagators, written as nogoods of the completion and loop nogoods, and adds clause learning and backjumping.
  • SAT-based solvers. Lin and Zhao (2004) give the completion to a SAT solver and add loop formulas for each model that is not stable.
  • Disjunctive programs. For disjunctive programs the same kind of search needs an extra minimality check at each candidate, which is a coNP problem.

When to use it

Use smodels-style search to understand or to teach stable model solvers, or when a small, simple solver for ground programs is enough. The algorithm shows clearly which propagation does what. For hard instances, conflict-driven solvers are usually much faster, because they learn from failed branches.

Pitfalls

  • Forgetting ATMOST. Without the upper closure, the search accepts supported models of positive loops. For p←qp \leftarrow q, q←pq \leftarrow p it would return {p,q}\{p, q\}, which is not stable.
  • Choice heads in R1. A choice rule with a true body does not force its heads; R1 applies only to normal rules. A choice rule is live for R2 and R3, and it adds its heads to the upper closure.
  • Atoms that occur only in bodies. They have no rule, so R2 must make them false at the start. If the set of atoms is taken from the heads only, they stay open forever.
  • Cost of lookahead. LOOKAHEAD runs up to 2n2n expansions per fixed atom, and on easy programs it can cost more than the search it saves.
  • Constraints do not derive atoms. The constraint ←not r\leftarrow \mathit{not}\ r makes rr true in the assignment, but rr must still be derived by a rule in the end, or ATMOST reports a conflict.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

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

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

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

from itertools import combinations

MAX_ATOMS = 12


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


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


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


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


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


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


def random_program(rng, n_atoms, n_rules, max_pos=2, max_neg=2):
    """A random ground normal program over the atoms 0 .. n_atoms - 1, drawn with the random.Random rng."""
    program = []
    for _ in range(n_rules):
        head = rng.randrange(n_atoms)
        pos = tuple(rng.sample(range(n_atoms), rng.randint(0, min(max_pos, n_atoms))))
        neg = tuple(rng.sample(range(n_atoms), rng.randint(0, min(max_neg, n_atoms))))
        program.append((head, pos, neg))
    return program
smodels_algorithm.py 222 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smodels-algorithm/. The authors are listed in prov/NCW1XZ.jsonl.
"""The smodels search of Simons, Niemela and Soininen (2002) for ground programs.

A program has three kinds of rules:
- normal rules (head, pos, neg), as in lp.py: head <- pos, not neg;
- choice rules (heads, pos, neg): {heads} <- pos, not neg, where heads is a tuple of atoms;
- constraints (pos, neg): <- pos, not neg.

A partial assignment is a dict from atoms to True or False. EXPAND closes it
under ATLEAST (the propagation rules of Simons) and ATMOST (the atoms outside
the upper closure are false, as in the well-founded semantics). LOOKAHEAD
tries each open atom both ways and fixes it when one way gives a conflict.
SEARCH branches on one atom and explores both values, so it returns all
stable models. This is the textbook form of the method, with each fixpoint
computed by repeated scans over the rules; the real smodels uses counters
and queues for the same fixpoints.
"""

NORMAL, CHOICE, CONSTRAINT = "normal", "choice", "constraint"


class Conflict(Exception):
    """An atom would get both values."""


class Program:
    """A ground program with normal rules, choice rules and constraints."""

    def __init__(self, normal=(), choice=(), constraints=()):
        self.rules = []
        for head, pos, neg in normal:
            self.rules.append((NORMAL, (head,), tuple(pos), tuple(neg)))
        for heads, pos, neg in choice:
            self.rules.append((CHOICE, tuple(heads), tuple(pos), tuple(neg)))
        for pos, neg in constraints:
            self.rules.append((CONSTRAINT, (), tuple(pos), tuple(neg)))
        found = set()
        for _, heads, pos, neg in self.rules:
            found.update(heads)
            found.update(pos)
            found.update(neg)
        self.atoms = sorted(found)
        self.support = {a: [] for a in self.atoms}
        for i, (kind, heads, _, _) in enumerate(self.rules):
            if kind != CONSTRAINT:
                for h in heads:
                    self.support[h].append(i)


def body_value(rule, a):
    """True, False or None (open) for the body of the rule under the partial assignment a."""
    _, _, pos, neg = rule
    open_seen = False
    for b in pos:
        v = a.get(b)
        if v is False:
            return False
        if v is None:
            open_seen = True
    for c in neg:
        v = a.get(c)
        if v is True:
            return False
        if v is None:
            open_seen = True
    return None if open_seen else True


def set_value(a, atom, value):
    """Assign atom := value. Return True when a changed; raise Conflict on the opposite value."""
    old = a.get(atom)
    if old is None:
        a[atom] = value
        return True
    if old != value:
        raise Conflict(atom)
    return False


def atleast(prog, a):
    """Close a under the four propagation rules. Raise Conflict when they clash."""
    changed = True
    while changed:
        changed = False
        for rule in prog.rules:
            kind, heads, pos, neg = rule
            value = body_value(rule, a)
            # Rule 1: a normal rule with a true body makes its head true.
            if kind == NORMAL and value is True:
                changed |= set_value(a, heads[0], True)  # @line L12
            # Rule 4: the body of a constraint, or of a normal rule with a false head, must not become true.
            if kind == CONSTRAINT or (kind == NORMAL and a.get(heads[0]) is False):  # @line L15
                if value is True:
                    raise Conflict(rule)
                if value is None:
                    open_lits = [(b, True) for b in pos if a.get(b) is None]
                    open_lits += [(c, False) for c in neg if a.get(c) is None]
                    if len(open_lits) == 1:
                        atom, makes_true = open_lits[0]
                        changed |= set_value(a, atom, not makes_true)  # @line L16
        for atom in prog.atoms:
            live = [i for i in prog.support[atom] if body_value(prog.rules[i], a) is not False]
            # Rule 2: an atom with no rule whose body can still be true is false.
            if not live:
                changed |= set_value(a, atom, False)  # @line L13
            # Rule 3: a true atom with one possible rule needs the body of that rule.
            elif len(live) == 1 and a.get(atom) is True:  # @line L14
                _, _, pos, neg = prog.rules[live[0]]
                for b in pos:
                    changed |= set_value(a, b, True)
                for c in neg:
                    changed |= set_value(a, c, False)
    return a


def upper_closure(prog, a):
    """The atoms that some stable model extending a may contain: a least fixpoint over the rules not blocked by a."""
    upper = set()
    changed = True
    while changed:
        changed = False
        for kind, heads, pos, neg in prog.rules:
            if kind == CONSTRAINT or any(a.get(c) is True for c in neg):
                continue
            if all(b in upper for b in pos):
                for h in heads:
                    if h not in upper and a.get(h) is not False:  # @line L8
                        upper.add(h)
                        changed = True
    return upper


def atmost(prog, a):
    """Make every atom outside the upper closure false. Return True when a changed."""
    upper = upper_closure(prog, a)  # @line L7
    changed = False
    for atom in prog.atoms:
        if atom not in upper:
            changed |= set_value(a, atom, False)  # @line L9
    return changed


def expand(prog, a):
    """Alternate ATLEAST and ATMOST until neither changes a. Raise Conflict on a clash."""
    while True:  # @line L5
        atleast(prog, a)  # @line L6
        if not atmost(prog, a):  # @line L10
            return a  # @line L11


def lookahead(prog, a):
    """Fix each open atom whose one value expands to a conflict. Return the expansion sizes of the open atoms."""
    while True:
        scores = {}
        progress = False
        for atom in prog.atoms:  # @line L17
            if atom in a:
                continue
            sizes = []
            for value in (True, False):
                trial = dict(a)
                trial[atom] = value
                try:
                    expand(prog, trial)  # @line L18
                except Conflict:
                    a[atom] = not value  # @line L19
                    expand(prog, a)
                    progress = True
                    break
                sizes.append(len(trial))
            if progress:
                break
            scores[atom] = (min(sizes), max(sizes), sizes[0] >= sizes[1])
        if not progress:
            return scores  # @line L20


def search(prog, a, out, stats, use_lookahead=True, first_only=False):
    """Depth-first search for all stable models that extend a. Append them to out."""
    stats["nodes"] += 1
    try:
        expand(prog, a)  # @line L1
        scores = lookahead(prog, a) if use_lookahead else None
    except Conflict:
        stats["conflicts"] += 1
        return
    if len(a) == len(prog.atoms):  # @line L2
        out.append(frozenset(x for x, v in a.items() if v))
        return
    open_atoms = [x for x in prog.atoms if x not in a]
    if scores:
        atom = max(open_atoms, key=lambda x: scores[x][:2])  # @line L3
        first = scores[atom][2]
    else:
        atom, first = open_atoms[0], True
    for value in (first, not first):  # @line L4
        if first_only and out:
            return
        branch = dict(a)
        branch[atom] = value
        search(prog, branch, out, stats, use_lookahead, first_only)


def stable_models(normal=(), choice=(), constraints=(), use_lookahead=True, stats=None):
    """All stable models of the program, sorted by size and then by content."""
    prog = Program(normal, choice, constraints)
    if stats is None:
        stats = {}
    stats.setdefault("nodes", 0)
    stats.setdefault("conflicts", 0)
    out = []
    search(prog, {}, out, stats, use_lookahead)
    return sorted(out, key=lambda m: (len(m), sorted(m)))


def has_stable_model(normal=(), choice=(), constraints=()):
    """True when the program has a stable model. The search stops at the first one."""
    prog = Program(normal, choice, constraints)
    out = []
    search(prog, {}, out, {"nodes": 0, "conflicts": 0}, True, first_only=True)
    return bool(out)
test_smodels_algorithm.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smodels-algorithm/. The authors are listed in prov/NCW1XZ.jsonl.

import random
import unittest
from itertools import combinations

import lp
from smodels_algorithm import Conflict, Program, expand, has_stable_model, stable_models


def key(models):
    return sorted(models, key=lambda m: (len(m), sorted(m)))


def brute_force(normal, choice=(), constraints=()):
    """Stable models by the reduct, over every subset of the atoms.

    A choice rule {H} <- pos, not neg survives the reduct by M when neg and M are
    disjoint, and then gives h <- pos for each h in H that is in M. M must also
    make no constraint body true.
    """
    universe = set()
    for h, pos, neg in normal:
        universe.update((h,) + tuple(pos) + tuple(neg))
    for hs, pos, neg in choice:
        universe.update(tuple(hs) + tuple(pos) + tuple(neg))
    for pos, neg in constraints:
        universe.update(tuple(pos) + tuple(neg))
    universe = sorted(universe)
    found = []
    for k in range(len(universe) + 1):
        for subset in combinations(universe, k):
            m = frozenset(subset)
            if any(all(b in m for b in pos) and not any(c in m for c in neg) for pos, neg in constraints):
                continue
            red = lp.reduct(normal, m)
            for hs, pos, neg in choice:
                if not any(c in m for c in neg):
                    red += [(h, tuple(pos), ()) for h in hs if h in m]
            if lp.least_model(red) == m:
                found.append(m)
    return key(found)


def translate_choice(normal, choice, offset=100):
    """The normal translation: h <- pos, not neg, not h'; h' <- not h, with h' = h + offset."""
    out = list(normal)
    for hs, pos, neg in choice:
        for h in hs:
            out.append((h, tuple(pos), tuple(neg) + (h + offset,)))
            out.append((h + offset, (), (h,)))
    return out


def random_choice_program(rng, n_atoms):
    normal = lp.random_program(rng, n_atoms, rng.randint(1, 6))
    choice = []
    for _ in range(rng.randint(1, 2)):
        hs = tuple(rng.sample(range(n_atoms), rng.randint(1, min(2, n_atoms))))
        pos = tuple(rng.sample(range(n_atoms), rng.randint(0, 1)))
        neg = tuple(rng.sample(range(n_atoms), rng.randint(0, 1)))
        choice.append((hs, pos, neg))
    constraints = []
    for _ in range(rng.randint(0, 2)):
        pos = tuple(rng.sample(range(n_atoms), rng.randint(1, min(2, n_atoms))))
        neg = tuple(rng.sample(range(n_atoms), rng.randint(0, 1)))
        constraints.append((pos, neg))
    return normal, choice, constraints


class TestSmodels(unittest.TestCase):
    def test_examples(self):
        # p <- not q. q <- not p. r <- p, not s.
        prog = [("p", (), ("q",)), ("q", (), ("p",)), ("r", ("p",), ("s",))]
        self.assertEqual(stable_models(prog), [frozenset({"q"}), frozenset({"p", "r"})])
        self.assertEqual(stable_models([("p", (), ("p",))]), [])
        self.assertEqual(stable_models([("p", ("p",), ())]), [frozenset()])
        # {a, b}. <- a, b. gives the three subsets of size at most 1.
        models = stable_models(choice=[(("a", "b"), (), ())], constraints=[(("a", "b"), ())])
        self.assertEqual(models, [frozenset(), frozenset({"a"}), frozenset({"b"})])

    def test_atmost_rejects_self_support(self):
        # p <- q. q <- p. The upper closure is empty, so EXPAND makes both false with no search.
        prog = Program([("p", ("q",), ()), ("q", ("p",), ())])
        a = expand(prog, {})
        self.assertEqual(a, {"p": False, "q": False})

    def test_conflict_from_constraint(self):
        prog = Program([("p", (), ())], constraints=[(("p",), ())])
        with self.assertRaises(Conflict):
            expand(prog, {})

    def test_random_normal_against_brute_force(self):
        rng = random.Random(20021)
        for _ in range(300):
            n = rng.randint(1, 6)
            prog = lp.random_program(rng, n, rng.randint(1, 9))
            expected = lp.stable_models(prog)
            self.assertEqual(stable_models(prog), expected, prog)
            self.assertEqual(stable_models(prog, use_lookahead=False), expected, prog)
            self.assertEqual(has_stable_model(prog), bool(expected), prog)

    def test_random_choice_against_brute_force(self):
        rng = random.Random(1382)
        for _ in range(250):
            n = rng.randint(1, 6)
            normal, choice, constraints = random_choice_program(rng, n)
            expected = brute_force(normal, choice, constraints)
            self.assertEqual(stable_models(normal, choice, constraints), expected, (normal, choice, constraints))
            self.assertEqual(stable_models(normal, choice, constraints, use_lookahead=False), expected)

    def test_choice_translation_has_same_models(self):
        rng = random.Random(77)
        for _ in range(80):
            n = rng.randint(1, 4)
            normal, choice, constraints = random_choice_program(rng, n)
            direct = stable_models(normal, choice, constraints)
            translated = stable_models(translate_choice(normal, choice), constraints=constraints)
            projected = key({frozenset(x for x in m if x < 100) for m in translated})
            self.assertEqual(direct, projected)
            # Each direct model comes from exactly one translated model.
            self.assertEqual(len(direct), len(translated))


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

History

Niemelä and Simons wrote the smodels system in the middle of the 1990s. Niemelä (1999) argued that logic programs with stable models are a constraint programming language and used smodels as the main example. Simons, Niemelä and Soininen (2002) published the full algorithm with weight constraint rules and its proofs. The approach set the pattern for the first generation of answer set solvers, and its propagators survive in the conflict-driven solvers that replaced it.

References

  1. Patrik Simons, Ilkka Niemelä and Timo Soininen, Extending and implementing the stable model semantics, Artificial Intelligence 138(1-2), 181 to 234 (2002), the procedures smodels, expand, atleast, atmost and lookahead, and the semantics of choice, cardinality and weight rules
  2. Ilkka Niemelä, Logic programs with stable model semantics as a constraint programming paradigm, Annals of Mathematics and Artificial Intelligence 25(3-4), 241 to 273 (1999), stable model search as constraint programming and the use of the smodels system
  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 definition of stable models by the reduct
  4. 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, which the upper closure of atmost removes
  5. 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 behind the linear-time fixpoints
  6. Fangzhen Lin and Yuting Zhao, ASSAT: computing answer sets of a logic program by SAT solvers, Artificial Intelligence 157(1-2), 115 to 137 (2004), the completion given to a SAT solver, with loop formulas added for models that are not stable

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example