Algorithmresearch
Conflict-driven answer set solving
Also called CDNL-ASP, conflict-driven nogood learning for ASP.
Encodes completion and loop constraints as nogoods and runs CDCL-style search with unfounded set checks to find stable models.
- Time
- 2^O((n + s) log(n + s)) worst
- Space
- 2^O((n + s) log(n + s)) extra
- Where
- n = the number of atoms; s = the size of the program, the number of rules plus the number of body literals
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Martin Gebser, Benjamin Kaufmann, André Neumann, Torsten Schaub, 2007
Conflict-driven answer set solving finds the answer sets of a ground normal program with the search engine of CDCL: decisions, propagation, conflict analysis to the first UIP, nogood learning and backjumping. What differs from CDCL is the input and one extra propagator. The constraints are not a CNF formula but nogoods built from the program: one set from the Clark completion, with a variable for each rule body, and one set from the loop formulas, which is exponential in size and so is added only on demand. After unit propagation, an unfounded set check finds atoms that only support each other, and adds the loop nogoods that make them false. Gebser, Kaufmann and Schaub (2012) proved that the answer sets are exactly the solutions of the two sets of nogoods.
In plain words
The solver turns the program into a list of forbidden combinations. "This rule's conditions hold but its conclusion is false" is forbidden. "This fact is true but none of its rules has true conditions" is forbidden too. Then it searches the way a modern SAT solver does: guess, follow the forbidden combinations to forced values, and when a combination is hit, find the reason and remember it so the same mistake is not made again. One thing remains. A group of facts can be true only because each of them proves another in a circle. After each round of forced values, the solver looks for such a group. When it finds one, it writes down a new forbidden combination that says the group cannot be true without help from outside, and goes on.
The problem
The input is a finite ground normal program over a set of atoms, with rules and constraints . The output is an answer set of , or the answer that there is none; repeated calls with blocking nogoods list all of them. Deciding whether an answer set exists is NP-complete in this propositional case, by the NP-completeness theorem. Programs with variables are first ground.
The algorithm
The solver has a Boolean variable for each atom and for each distinct body , with positive atoms and negative atoms . A nogood is a set of literals or that must not all hold. The completion nogoods are:
- for each body : , and for , and for , so that is true exactly when its literals hold;
- for each atom with bodies : for each , and , so that is true exactly when one of its bodies is;
- for each constraint with body : .
For a set of atoms, the external bodies are the bodies of rules with head in whose positive part does not meet . The loop nogood of is : cannot be true when no rule from outside supports .
CDNL-ASP(P)- 1
Γ ← Δ_P; A ← an empty assignment; dl ← 0 - 2
loop - 3
(A, ε) ← PROPAGATE(P, Γ, A) ▷ ε is a violated nogood, or none - 4
if ε ≠ none then - 5
if every literal of ε has level 0 then return "no answer set" - 6
(δ, j) ← ANALYZE(ε, A) - 7
Γ ← Γ ∪ {δ}; undo the literals of level above j; dl ← j - 8
else if A assigns every variable then return {p : Tp ∈ A} - 9
else dl ← dl + 1; add a decision literal on an open variable, at level dl PROPAGATE(P, Γ, A)- 10
loop - 11
while some δ ∈ Γ has all its literals in A but one, σ, which is open: add the complement of σ, with reason δ - 12
if some δ ∈ Γ has all its literals in A then return (A, δ) - 13
if P is tight then return (A, none) - 14
U ← the atoms not false in A that no body which is not false can derive - 15
if U = ∅ then return (A, none) - 16
Γ ← Γ ∪ {λ(p, U) : p ∈ U} ANALYZE(ε, A)- 17
k ← the largest level of a literal of ε - 18
while ε has two or more literals of level k do - 19
σ ← the literal of ε at level k assigned last; δ ← the reason of σ - 20
ε ← (ε ∖ {σ}) ∪ (δ ∖ {complement of σ}) - 21
return (ε, the largest level of the other literals of ε, or 0 if there is none)
Line L14 computes the greatest unfounded set: start from the bodies that are not false and whose positive atoms are already derived, add their heads that are not false, and repeat. The atoms that are not false and never derived form . After unit propagation every body in is false, so each new loop nogood at line L16 is violated or unit, and the next pass of line L11 makes progress. Lines L17 to L21 are the first-UIP scheme of CDCL. The Python code decides the first open variable false at line L9.
Example
Take the program of the smodels example:
The variables are and the bodies , , , , and of the constraint. has 22 nogoods. The program is not tight, because of the cycle .
| level | step | new literals | why |
|---|---|---|---|
| 0 | L11 | , | ; then |
| 0 | L11 | , , | the body and support nogoods of and |
| 0 | L14 | , can be derived from , , then from , then | |
| 1 | L9 | decision | |
| 1 | L11 | , , , | the body nogoods of , , then , then |
| 1 | L14 | , | the only bodies that are not false and could derive or are and , which need and |
| 1 | L16, L12 | conflict on | is at level 0 and at level 1 |
| 0 | L6, L7 | learn , back to level 0 | only one literal of level 1, so it is already the first UIP |
| 0 | L11 | , , , , | the learned nogood is unit |
| 0 | L8 | answer set | every variable is assigned and |
The run makes one decision, meets one conflict and adds two loop nogoods, and . The assignment at level 1 before the conflict, with true, satisfies every nogood of the completion: only the unfounded set check rejects it.
Correctness
The correctness proof has the details. Soundness: the search returns only a total assignment that violates no nogood of and has an empty unfounded set. Then the true atoms form a model of the reduct , because each true body forces its head, and every true atom is derived in the least model of , because the unfounded set is empty. So is an answer set. Completeness: every nogood in the database is in , in the set of all loop nogoods, or is a resolvent of nogoods already in the database. So the database is implied by , and by the theorem of Gebser, Kaufmann and Schaub every answer set violates none of it. A conflict at level 0 therefore proves that there is no answer set. Termination is the CDCL argument, plus the fact that each pass of lines L14 to L16 adds a new loop nogood, of which there are finitely many.
Proof: Conflict-driven nogood learning returns exactly the answer setsfull
Let be a finite ground normal program over a set of atoms, with rules and constraints . For a body we write and . The solver has one variable for each atom and one for each distinct body. A literal is or . An assignment is a consistent set of literals; it is total if it assigns every variable. A nogood is a set of literals; an assignment violates it if it contains all of its literals. A total assignment is a solution of a set of nogoods if it violates none of them. A set induces the total assignment that makes an atom true exactly when it is in and a body true exactly when satisfies it.
The nogoods (Gebser, Kaufmann and Schaub 2012)
For each body : , and the nogoods for and for . For each atom with bodies : for each , and . For each constraint with body : . These nogoods form . Their solutions are exactly the assignments such that is a model of the Clark completion of and of the constraints.
For , the external bodies are the bodies of rules with head in such that . The loop nogood of is , and is the set of all loop nogoods for all nonempty .
Theorem A (Gebser, Kaufmann and Schaub 2012). is an answer set of if and only if is a solution of .
The tests check Theorem A by brute force on random programs. The proof below uses only the "if" direction for one kind of assignment, and proves it directly in Lemma 3.
Unfounded sets
The solver computes, for the current assignment , the set of atoms that can still be derived. is the least set such that if a body is not false in and , then each head of that is not false is in . The set that it returns is the set of atoms that are not false and not in .
Lemma 1. Suppose that unit propagation over a set of nogoods that contains has reached a fixpoint without a violated nogood. Then every body in is false in .
Proof. Let be a body of , and suppose that is not false. If some were false, the nogood would be unit, and unit propagation would have made false. So every atom of is not false. Since , every atom of is in . Then , which is not false, is in by the definition of . This contradicts .
So when , every new loop nogood with is violated, if is true, or unit, if is open. In both cases the next round of unit propagation makes progress. Also, at least one of these nogoods is new. If all of them were present already, then each would be violated or unit at the fixpoint, which a fixpoint without conflict excludes. There are finitely many loop nogoods, so the loop in PROPAGATE ends.
Lemma 2. If is tight (its positive dependency graph has no cycle), the solver adds no loop nogood, and every solution of is of the form for an answer set .
Proof. The code skips the unfounded set check on tight programs. The second claim is Fages' theorem: for a tight program, the models of the completion are the answer sets.
Lemma 3. Let be a total assignment that violates no nogood of and for which . Let be its set of true atoms. Then is an answer set of and satisfies no constraint body.
Proof. Since is total and violates no body nogood, a body is true exactly when satisfies it. Let be the least model of the reduct . A rule of is for a rule with . If , then is true, and the nogood gives . So is a model of and . Under a total assignment, is the least set closed under the rules with true and true. Each of these is a rule of , so . means . So , and . The nogood of each constraint is not violated, so is false.
For a tight program, Lemma 2 covers the same case: a total solution of gives an answer set.
Learned nogoods
A nogood is implied by a set of nogoods if every solution of is a solution of .
Lemma 4. Let , where is the set of blocking nogoods of the run. Each nogood in the solver's database is in or implied by .
Proof. The nogoods of , the loop nogoods and the blocking nogoods are in . A learned nogood is built by ANALYZE. It starts from a violated nogood of the database and repeatedly replaces a literal by the other literals of the nogood that implied in unit propagation. That nogood holds the complement . The new set is the resolvent . Let be a solution of that contains the resolvent. is total, so it contains or . In the first case it contains , and in the second case it contains . Both are implied by by induction, so this is impossible.
Lemma 5 (analysis ends with an asserting nogood). Let the conflict have its largest decision level . ANALYZE ends, and its result has exactly one literal of level and its other literals at levels at most , where is the level returned.
Proof. While the set holds two or more literals of level , the one assigned last is not the decision literal of level , because that literal is the first one at level on the trail. So it has a reason, and the step replaces it by literals assigned earlier. The positions on the trail of the literals at level decrease, so the loop ends. It ends exactly when one literal of level is left. is the largest level among the others, so .
After the backjump to level , the learned nogood has all literals but one true, so unit propagation assigns the complement of its literal of level .
The theorem
Theorem. solve returns an answer set of that is not blocked, if there is one, and None otherwise. answer_sets returns every answer set exactly once.
Proof. Termination. Between two decisions, PROPAGATE ends by Lemma 1 and the finite number of loop nogoods. By Lemma 5 each conflict at level is followed by a backjump and the assignment of an asserted literal at a level below . This is the conflict-driven clause learning scheme, and the standard argument for its termination applies: the vector of the numbers of literals at the levels grows in the lexicographic order after each conflict, and it is bounded.
Soundness. The search returns only when the assignment is total and PROPAGATE found no violated nogood and, for a program that is not tight, . By Lemma 3, or by Lemma 2 for a tight program, the set of true atoms is an answer set. It violates no blocking nogood, so it is not one of the answer sets found before.
Completeness. Let be an answer set that is not blocked. By Theorem A, is a solution of , and it is a solution of . By Lemma 4, it violates no nogood of the database. The search returns None only after a conflict at level . All literals at level follow from the database by unit propagation, so every solution of the database contains them. The conflict nogood would then be violated by , which is impossible. So the search does not return None, and by termination it returns an answer set.
Enumeration. Each call of solve in answer_sets adds a blocking nogood for each answer set found before. By soundness and completeness, each call returns a new answer set until none is left.
Running time
Let be the number of atoms and the size of the program, the number of rules plus the number of body literals. There are at most variables and nogoods in . The unfounded set computation takes time with repeated scans, or with counters. The number of conflicts is not bounded by a polynomial, since the problem is NP-complete. The code finds unit nogoods by scanning all nogoods, which costs per pass for the total size of the database; solvers such as clasp use watched literals instead.
What the tests check
On 300 random programs with at most 6 atoms, and on 150 random programs with constraints, answer_sets gives exactly the answer sets found by brute force with the reduct. For 60 programs the tests build for every nonempty from the definition, independent of the solver code, and check Theorem A: the solutions of are the answer sets. On 300 larger random programs, every answer set that a run does not block violates none of the learned nogoods and none of the loop nogoods of that run, so these nogoods are consistent with Lemma 4. The run learns more than 100 nogoods in total. A last test checks that each loop nogood has one true atom literal and false body literals.
Complexity
Let be the number of rules plus the number of body literals. There are at most variables, and has nogoods of total size . The full set of loop nogoods can have members, which is why it is built on demand. The unfounded set check at line L14 takes time with counters. The number of conflicts is not bounded by a polynomial, as for CDCL, and the NP-completeness of the problem makes a polynomial bound unlikely. The termination argument bounds the number of conflicts by the number of distinct level vectors, which gives the bound on time and on the size of the learned database. The Python code scans every nogood in each pass of unit propagation; solvers such as clasp use watched literals instead.
Properties
- Sound and complete. It returns an answer set if and only if one exists, and enumeration with blocking nogoods lists each answer set once.
- No extra work on tight programs. If the positive dependency graph has no cycle, the completion nogoods are enough, by Fages' theorem, and the unfounded set check is skipped.
- Learned nogoods are consequences. Each learned nogood is a resolvent of completion nogoods, loop nogoods and earlier learned nogoods, so it holds in every answer set.
- Loop nogoods on demand. Only the loop nogoods of unfounded sets that the search actually meets are ever built.
Variants and improvements
- Bodies as variables. Keeping a variable for each body, and not only for each atom, lets the solver branch and learn on bodies. Gebser, Kaufmann and Schaub (2012) discuss this choice.
- Source pointers. The unfounded set check can keep, for each atom, one body that still supports it, and recompute only the atoms that lose their support.
- Optimization and enumeration. clasp extends the search with minimize statements and with enumeration that does not need a blocking nogood per answer set.
- Disjunctive programs. For disjunctive programs, each candidate also needs a minimality check, which a second solver does; that problem is coNP-complete.
- SAT with loop formulas. ASSAT (Lin and Zhao 2004) gives the completion to a SAT solver and adds loop formulas only when a model is not stable; CDNL-ASP adds them inside the search.
When to use it
Use conflict-driven solving for real ASP workloads: planning, scheduling, configuration, and other combinatorial search problems written as answer set programs. It is the method inside clasp and the clingo system. For a small program, or to teach the semantics, the simpler smodels search shows the propagators more clearly.
Pitfalls
- Completion is not enough. Without the unfounded set check the solver returns models of the completion, such as in the example, which are not answer sets.
- External bodies. A body that contains an atom of positively is not external, even if it is true. Treating it as external makes loop nogoods too weak, and the self-supporting loop is accepted.
- Constraints have no head. A constraint gives only the nogood ; it must not add a support nogood for any atom.
- Blocking nogoods are not consequences. When answer sets are enumerated with blocking nogoods, the nogoods learned from them hold only for the rest of the enumeration, not for the program.
- Speed claims. The speed of clasp and similar solvers is a measured property of their implementations and benchmarks, not a consequence of the algorithm; the worst case is exponential.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conflict-driven-answer-set-solving/. The authors are listed in prov/THR1ZW.jsonl.
"""Conflict-driven nogood learning for answer sets (CDNL-ASP), after Gebser, Kaufmann and Schaub (2012).
The input is a ground normal program in the format of lp.py, a list of rules
(head, pos, neg), and optionally a list of constraints (pos, neg). The solver
has one Boolean variable for each atom and one for each distinct rule body.
A literal is +v (v is true) or -v (v is false). A nogood is a frozenset of
literals that must not all be true at the same time.
The static nogoods are those of the completion (Delta_P). Loop nogoods
(Lambda_P) are added on demand: after unit propagation, the solver computes
the greatest unfounded set U of the atoms that are not false, and adds
lambda(p, U) for each p in U. Conflicts are analysed to the first unique
implication point, and the learned nogood is a resolvent of nogoods already
known. Propagation scans all nogoods; a real solver uses watched literals.
"""
def lit_var(lit):
return lit if lit > 0 else -lit
class Solver:
def __init__(self, program, constraints=(), blocked=()):
names = set()
for h, pos, neg in program:
names.add(h)
names.update(pos)
names.update(neg)
for pos, neg in constraints:
names.update(pos)
names.update(neg)
self.atom_names = sorted(names)
self.atom_var = {a: i + 1 for i, a in enumerate(self.atom_names)}
self.n_atoms = len(self.atom_names)
self.body_var = {}
self.body_of = {}
self.heads_of_body = {}
self.bodies_of_atom = {self.atom_var[a]: [] for a in self.atom_names}
def body(pos, neg):
k = (tuple(sorted(self.atom_var[b] for b in set(pos))), tuple(sorted(self.atom_var[c] for c in set(neg))))
if k not in self.body_var:
v = self.n_atoms + len(self.body_var) + 1
self.body_var[k] = v
self.body_of[v] = k
self.heads_of_body[v] = []
return self.body_var[k]
for h, pos, neg in program:
b = body(pos, neg)
hv = self.atom_var[h]
if hv not in self.heads_of_body[b]:
self.heads_of_body[b].append(hv)
self.bodies_of_atom[hv].append(b)
constraint_bodies = [body(pos, neg) for pos, neg in constraints]
self.n_vars = self.n_atoms + len(self.body_var)
# The completion nogoods Delta_P.
self.static = [] # @line L1
for b, (pos, neg) in self.body_of.items():
self.static.append(frozenset([-b] + list(pos) + [-c for c in neg]))
for p in pos:
self.static.append(frozenset([b, -p]))
for c in neg:
self.static.append(frozenset([b, c]))
for a, bodies in self.bodies_of_atom.items():
for b in bodies:
self.static.append(frozenset([-a, b]))
self.static.append(frozenset([a] + [-b for b in bodies]))
for b in constraint_bodies:
self.static.append(frozenset([b]))
# Nogoods that exclude answer sets found before (used to enumerate).
self.blocking = []
self.blocked_models = [frozenset(m) for m in blocked]
for m in blocked:
m = set(m)
self.blocking.append(frozenset(self.atom_var[a] if a in m else -self.atom_var[a] for a in self.atom_names))
self.loop = []
self.loop_set = set()
self.learned = []
self.tight = self._is_tight()
self.value = [None] * (self.n_vars + 1)
self.level = [0] * (self.n_vars + 1)
self.reason = [None] * (self.n_vars + 1)
self.trail = []
self.trail_pos = [0] * (self.n_vars + 1)
self.dl = 0
self.stats = {"decisions": 0, "conflicts": 0, "loop_nogoods": 0}
def _is_tight(self):
"""True when the positive dependency graph has no cycle (Fages: then no loop nogood is needed)."""
succ = {a: set() for a in self.bodies_of_atom}
for b, (pos, _) in self.body_of.items():
for h in self.heads_of_body[b]:
succ[h].update(pos)
state = {}
for start in succ:
if start in state:
continue
stack = [(start, iter(succ[start]))]
state[start] = 1
while stack:
node, it = stack[-1]
nxt = next(it, None)
if nxt is None:
state[node] = 2
stack.pop()
elif state.get(nxt) == 1:
return False
elif nxt not in state:
state[nxt] = 1
stack.append((nxt, iter(succ[nxt])))
return True
# Assignment.
def is_true(self, lit):
v = self.value[lit_var(lit)]
return v is not None and v == (lit > 0)
def assign(self, lit, reason):
v = lit_var(lit)
self.value[v] = lit > 0
self.level[v] = self.dl
self.reason[v] = reason
self.trail_pos[v] = len(self.trail)
self.trail.append(lit)
def backjump(self, j):
while self.trail and self.level[lit_var(self.trail[-1])] > j:
v = lit_var(self.trail.pop())
self.value[v] = None
self.reason[v] = None
self.dl = j
# Propagation.
def nogoods(self):
return self.static + self.blocking + self.loop + self.learned
def unit_propagate(self):
"""Unit propagation over all nogoods. Return a violated nogood or None."""
while True:
changed = False
for ng in self.nogoods():
open_lit = None
n_open = 0
satisfied = False
for lit in ng:
v = self.value[lit_var(lit)]
if v is None:
n_open += 1
open_lit = lit
if n_open > 1:
break
elif v != (lit > 0):
satisfied = True
break
if satisfied or n_open > 1:
continue
if n_open == 0:
return ng # @line L12
self.assign(-open_lit, ng) # @line L11
changed = True
if not changed:
return None
def unfounded_set(self):
"""The greatest unfounded set: the atoms not false that no body which is not false can derive."""
derived = set()
changed = True
while changed:
changed = False
for b, (pos, _) in self.body_of.items():
if self.value[b] is False or not all(p in derived for p in pos):
continue
for h in self.heads_of_body[b]:
if h not in derived and self.value[h] is not False:
derived.add(h)
changed = True
return [a for a in range(1, self.n_atoms + 1) if self.value[a] is not False and a not in derived]
def external_bodies(self, u):
us = set(u)
return sorted({b for a in us for b in self.bodies_of_atom[a] if not us.intersection(self.body_of[b][0])})
def propagate(self):
"""Unit propagation, then unfounded set checks that add loop nogoods. Return a violated nogood or None."""
while True: # @line L10
conflict = self.unit_propagate()
if conflict is not None or self.tight: # @line L13
return conflict
u = self.unfounded_set() # @line L14
if not u: # @line L15
return None
eb = self.external_bodies(u)
for p in u:
ng = frozenset([p] + [-b for b in eb])
if ng not in self.loop_set:
self.loop_set.add(ng)
self.loop.append(ng) # @line L16
self.stats["loop_nogoods"] += 1
# Conflict analysis.
def analyze(self, conflict):
"""Resolve back to the first unique implication point. Return the learned nogood and the backjump level."""
k = max(self.level[lit_var(l)] for l in conflict) # @line L17
delta = set(conflict)
while True:
at_k = [l for l in delta if self.level[lit_var(l)] == k]
if len(at_k) == 1: # @line L18
break
sigma = max(at_k, key=lambda l: self.trail_pos[lit_var(l)]) # @line L19
eps = self.reason[lit_var(sigma)]
delta.discard(sigma)
delta.update(l for l in eps if l != -sigma) # @line L20
j = max((self.level[lit_var(l)] for l in delta if self.level[lit_var(l)] != k), default=0)
return frozenset(delta), j # @line L21
def solve(self):
"""Return one answer set as a frozenset of atoms, or None when there is none."""
while True: # @line L2
conflict = self.propagate() # @line L3
if conflict is not None: # @line L4
self.stats["conflicts"] += 1
k = max(self.level[lit_var(l)] for l in conflict)
if k == 0: # @line L5
return None
if k < self.dl:
self.backjump(k)
learned, j = self.analyze(conflict) # @line L6
self.learned.append(learned) # @line L7
self.backjump(j)
continue
open_vars = [v for v in range(1, self.n_vars + 1) if self.value[v] is None]
if not open_vars: # @line L8
return frozenset(self.atom_names[a - 1] for a in range(1, self.n_atoms + 1) if self.value[a])
self.dl += 1
self.stats["decisions"] += 1
self.assign(-open_vars[0], None) # @line L9
def answer_sets(program, constraints=(), solvers=None):
"""All answer sets, sorted by size and then by content. Each new search blocks the answer sets found before."""
found = []
while True:
s = Solver(program, constraints, blocked=found)
m = s.solve()
if solvers is not None:
solvers.append(s)
if m is None:
break
found.append(m)
return sorted(found, key=lambda m: (len(m), sorted(m)))
def has_answer_set(program, constraints=()):
return Solver(program, constraints).solve() is not None
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_conflict_driven_answer_set_solving.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/conflict-driven-answer-set-solving/. The authors are listed in prov/THR1ZW.jsonl.
import random
import unittest
from itertools import combinations
import lp
from conflict_driven_answer_set_solving import Solver, answer_sets, has_answer_set
def brute_force(program, constraints=()):
"""Stable models by the reduct, minus those that make a constraint body true."""
extra = [a for pos, neg in constraints for a in pos + neg]
universe = sorted(set(lp.atoms(program)) | set(extra))
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
if lp.is_stable(program, m):
found.append(m)
return found
def induced(solver, m):
"""The total assignment of atoms and bodies that the set of atoms m gives, as a set of literals."""
lits = set()
for name, v in solver.atom_var.items():
lits.add(v if name in m else -v)
true_vars = {solver.atom_var[a] for a in m}
for b, (pos, neg) in solver.body_of.items():
holds = all(p in true_vars for p in pos) and not any(c in true_vars for c in neg)
lits.add(b if holds else -b)
return lits
def completion_and_loop_solutions(program, constraints, solver):
"""The sets of atoms whose induced assignment satisfies every completion nogood and every loop nogood.
Every loop nogood lambda(p, U) is built here for every nonempty set U of atoms,
from the definition, without the solver's code.
"""
atoms = sorted(solver.atom_var.values())
eb = {}
for k in range(1, len(atoms) + 1):
for u in combinations(atoms, k):
us = set(u)
eb[u] = [b for b in solver.body_of if any(h in us for h in solver.heads_of_body[b]) and not us.intersection(solver.body_of[b][0])]
sols = []
for m in brute_force_subsets(solver):
lits = induced(solver, m)
if any(ng <= lits for ng in solver.static):
continue
ok = True
for u, bodies in eb.items():
for p in u:
if p in lits and all(-b in lits for b in bodies):
ok = False
if ok:
sols.append(m)
return sols
def brute_force_subsets(solver):
names = solver.atom_names
for k in range(len(names) + 1):
for subset in combinations(names, k):
yield frozenset(subset)
def random_constraints(rng, n_atoms):
out = []
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)))
out.append((pos, neg))
return out
class TestCDNL(unittest.TestCase):
def test_examples(self):
prog = [("p", (), ("q",)), ("q", (), ("p",)), ("r", ("p",), ("s",))]
self.assertEqual(answer_sets(prog), [frozenset({"q"}), frozenset({"p", "r"})])
self.assertEqual(answer_sets([("p", (), ("p",))]), [])
# A positive loop: p <- q. q <- p. p <- not r. r <- not p.
loop = [("p", ("q",), ()), ("q", ("p",), ()), ("p", (), ("r",)), ("r", (), ("p",))]
self.assertEqual(answer_sets(loop), [frozenset({"r"}), frozenset({"p", "q"})])
# The completion of a <- b. b <- a. has the model {a, b}; the loop nogoods reject it.
self.assertEqual(answer_sets([("a", ("b",), ()), ("b", ("a",), ())]), [frozenset()])
def test_random_against_brute_force(self):
rng = random.Random(2012)
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(answer_sets(prog), expected, prog)
self.assertEqual(has_answer_set(prog), bool(expected), prog)
def test_random_with_constraints(self):
rng = random.Random(188)
for _ in range(150):
n = rng.randint(1, 6)
prog = lp.random_program(rng, n, rng.randint(1, 9))
cons = random_constraints(rng, n)
self.assertEqual(answer_sets(prog, cons), brute_force(prog, cons), (prog, cons))
def test_solutions_of_nogoods_are_the_stable_models(self):
# Gebser, Kaufmann and Schaub: X is an answer set iff X is the true atoms of a solution of Delta_P and Lambda_P.
rng = random.Random(55)
for _ in range(60):
n = rng.randint(1, 5)
prog = lp.random_program(rng, n, rng.randint(1, 8))
cons = random_constraints(rng, n)
s = Solver(prog, cons)
sols = completion_and_loop_solutions(prog, cons, s)
self.assertEqual(sorted(sols, key=lambda m: (len(m), sorted(m))), brute_force(prog, cons))
def test_learned_nogoods_are_implied(self):
# Each learned nogood and each loop nogood must be avoided by every solution of the
# completion and loop nogoods that the blocking nogoods of the run do not exclude.
# The first run of each program has no blocking nogood, so there the learned nogoods
# follow from Delta_P and Lambda_P alone.
rng = random.Random(9)
learned = 0
for _ in range(300):
n = rng.randint(3, 6)
prog = lp.random_program(rng, n, rng.randint(6, 14))
cons = random_constraints(rng, n)
solvers = []
answer_sets(prog, cons, solvers)
stable = brute_force(prog, cons)
for s in solvers:
learned += len(s.learned)
for m in stable:
if m in s.blocked_models:
continue
lits = induced(s, m)
for ng in s.learned + s.loop:
self.assertFalse(ng <= lits, (prog, cons, m, ng))
self.assertGreater(learned, 100)
def test_loop_nogoods_have_the_right_form(self):
rng = random.Random(4)
for _ in range(100):
n = rng.randint(2, 6)
prog = lp.random_program(rng, n, rng.randint(3, 10))
s = Solver(prog)
s.solve()
for ng in s.loop:
(p,) = [l for l in ng if l > 0]
self.assertLessEqual(p, s.n_atoms)
self.assertTrue(all(l < 0 and -l > s.n_atoms for l in ng if l != p))
if __name__ == "__main__":
unittest.main()
History
Lin and Zhao (2004) showed that the completion with loop formulas characterizes answer sets and used a SAT solver with loop formulas added on demand. The clasp solver of Gebser, Kaufmann, Neumann and Schaub, first presented in 2007, put the completion and loop conditions inside a conflict-driven search with nogoods, in the style of CDCL. Gebser, Kaufmann and Schaub (2012) gave the full theory: the nogood characterization of answer sets, the algorithm CDNL-ASP and its proofs. The method is the basis of the clingo system.
References
- Martin Gebser, Benjamin Kaufmann and Torsten Schaub, Conflict-driven answer set solving: From theory to practice, Artificial Intelligence 187-188, 52 to 89 (2012), the nogoods of the completion and the loop nogoods, the theorem that answer sets are the solutions of both, the algorithm CDNL-ASP with its propagation, unfounded set check and conflict analysis
- Martin Gebser, Roland Kaminski, Benjamin Kaufmann and Torsten Schaub, Answer Set Solving in Practice, Morgan and Claypool (2012), Chapter 5 on the characterizations by completion and loop nogoods and Chapter 6 on conflict-driven solving
- 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), loop formulas and the theorem that the models of the completion and the loop formulas are the answer sets
- Patrik Simons, Ilkka Niemelä and Timo Soininen, Extending and implementing the stable model semantics, Artificial Intelligence 138(1-2), 181 to 234 (2002), the earlier smodels search without learning, for comparison
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 THR1ZW Edit this page History Report an error Markdown