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
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- 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 over a set of atoms. Its rules are normal rules , choice rules , and constraints . The output is the set of stable models of , 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 maps some atoms to true or false. A body is true under 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.
SMODELS(P, a) ▷ a is a partial assignment; returns the stable models that extend it- 1
try a ← LOOKAHEAD(P, EXPAND(P, a)) on conflict return ∅ - 2
if a assigns every atom then return {the set of true atoms of a} - 3
x, v ← the open atom and value chosen by the heuristic - 4
return SMODELS(P, a ∪ {x ↦ v}) ∪ SMODELS(P, a ∪ {x ↦ ¬v}) EXPAND(P, a)- 5
repeat - 6
a ← ATLEAST(P, a) - 7
U ← the least set closed under: for each normal or choice rule r with no negative atom true in a - 8
and pos(r) ⊆ U, add each head h of r that is not false in a ▷ the upper closure - 9
make every atom outside U false - 10
until a does not change - 11
return a ATLEAST(P, a) ▷ repeat until no rule applies; a clash is a conflict- 12
R1: a normal rule with a true body makes its head true - 13
R2: an atom that is the head of no live rule becomes false - 14
R3: a true atom with exactly one live rule makes every literal of that body true - 15
R4: a constraint, or a normal rule with a false head, must not get a true body: - 16
if all its literals but one are true, make the last one false LOOKAHEAD(P, a)- 17
for each open atom x and each value v do - 18
if EXPAND(P, a ∪ {x ↦ v}) gives a conflict then - 19
a ← EXPAND(P, a ∪ {x ↦ ¬v}) and restart the loop at L17 - 20
return 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
Its completion has two models, and . In the second one, and support only each other. The only stable model is .
| step | rule | assignment |
|---|---|---|
| EXPAND at the root | R4 on the constraint: its one literal must be false | true |
| R1 on | true | |
| ATMOST: the upper closure is , no change | true, open | |
| LOOKAHEAD, try false | R4 on : the head is false, so must be false | true |
| ATMOST: is blocked, and , need each other, so the upper closure is | false, but is true: conflict | |
| LOOKAHEAD fixes true | R2: is no longer live | false |
| L2 | every atom is assigned | return |
The search visits one node and makes no guess. Without LOOKAHEAD, the code branches on , 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 true and 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 that agrees with the current assignment. R1 and R4 hold because is a model of . R2 and R3 hold because each atom of is the head of a rule whose body satisfies. ATMOST holds because 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 of true atoms a model of the reduct , and ATMOST makes a subset of the least model of , so 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 be a finite ground program over a set of atoms. It has normal rules , choice rules and constraints , where a body is . We write and for the positive and negative atoms of . A set satisfies if and .
Stable models of programs with choice rules
The reduct deletes every rule whose body has with , and every constraint. Each normal rule that is left becomes . Each choice rule that is left becomes the rules for . The reduct is a definite program. is a stable model of if is the least model of and 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 be a stable model of .
- If satisfies the body of a normal rule , then .
- Each is the head of a normal rule, or one of the heads of a choice rule, whose body satisfies.
- satisfies no constraint body.
Proof. (1) The rule is kept in as with . is a model of , so . (2) is in the least model of , so some rule of has . That rule comes from a rule of with in its head and . (3) holds by the definition.
The procedures
A partial assignment maps some atoms to true or false. agrees with if implies and implies . A body is true under if all its literals are true, false if one of its literals is false, and open otherwise. A rule is live for if its body is not false.
ATLEAST applies four rules until none of them changes :
- (R1) if the body of a normal rule is true, make 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 : the least set that contains each head with of each normal or choice rule with and no true under . It makes every atom outside false. EXPAND repeats ATLEAST and ATMOST until neither changes . 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 and calls itself with true and with false.
Lemma 2 (each step keeps every stable model). Let be a stable model of that agrees with . Then 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 , so satisfies it, and by Lemma 1(1). (R2) Each rule with in its head has a body that is false under , so does not satisfy it, and by Lemma 1(2). (R3) By Lemma 1(2), satisfies the body of a rule with in the head, and that rule must be live, so it is the one live rule. So satisfies its body. (R4) If satisfied the body, then would satisfy a constraint body, against Lemma 1(3), or would satisfy the body of a normal rule with , against Lemma 1(1). So the body is not true under , and when one literal is open and the others are true, makes that literal false.
ATMOST. We show . is the union of the stages of the immediate consequence operator of . By induction on : an atom of the stage comes from a rule of with and . Since agrees with , no is true under . And , so . So . (For a choice rule the reduct has only for , and the same argument applies.) So each atom that ATMOST makes false is not in .
EXPAND is a sequence of these steps. If one value of an open atom expands to a conflict, then no stable model that agrees with has that value for , by what we just showed, so has the other value. Hence LOOKAHEAD keeps too.
Lemma 3 (a total assignment that expands with no conflict is a stable model). Let be total, with no conflict after EXPAND, and let be its set of true atoms. Then is a stable model of .
Proof. Let be the least model of . First, is a model of . A normal rule of comes from with . If , the body is true under , and (R1) gives . A choice rule gives rules only for heads in . So . Second, ATMOST made every atom outside false and found no conflict, so . Under a total assignment, is built from the rules whose negative atoms are not in , and it adds only heads in . These are exactly the rules of , so by induction on the construction . Together, . Finally, (R4) reports a conflict for a constraint with a true body, so satisfies no constraint body.
Theorem. SEARCH called on the empty assignment returns each stable model of 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 and the search ends. A returned set is a stable model by Lemma 3. Let be a stable model. By Lemma 2, along the path of calls that always takes the branch value that gives, no conflict occurs and agrees with every assignment. The path ends at a total assignment, which is . Two different leaves differ on the atom of their last common branch point, so each stable model is returned once.
Running time
Let be the size of , 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 time per call. Each round of EXPAND other than the last assigns at least one atom, so EXPAND takes time. LOOKAHEAD runs at most expansions for each atom that it fixes, and it fixes at most atoms, so it takes time. The search tree has at most leaves. The worst-case time is . The Python code recomputes each fixpoint with repeated scans, which adds a factor 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, and , 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 be the number of rules plus the number of literals. With counters, ATLEAST and ATMOST take time, so EXPAND takes : each round but the last assigns an atom. LOOKAHEAD runs at most expansions for each of at most atoms that it fixes, which gives per node. The search tree has at most leaves, so the worst-case time is . With a trail of assignments that is undone on backtracking, the extra space is . The Python code copies the assignment at each node and recomputes each fixpoint by repeated scans, which costs an extra factor in time and 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 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 , it would return , 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 expansions per fixed atom, and on easy programs it can cost more than the search it saves.
- Constraints do not derive atoms. The constraint makes true in the assignment, but 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.
# 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
- 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
- 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
- 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
- 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
- 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
- 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.
| 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 NCW1XZ Edit this page History Report an error Markdown