Algorithm Search⌘K

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
Properties
deterministic
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 PP over a set AA of nn atoms, with rules h←b1,…,bm,not c1,…,not ckh \leftarrow b_1, \ldots, b_m, \mathit{not}\ c_1, \ldots, \mathit{not}\ c_k and constraints ←b1,…,not ck\leftarrow b_1, \ldots, \mathit{not}\ c_k. The output is an answer set of PP, 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 pp and for each distinct body β\beta, with positive atoms β+\beta^+ and negative atoms β−\beta^-. A nogood is a set of literals Tv\mathbf{T}v or Fv\mathbf{F}v that must not all hold. The completion nogoods ΔP\Delta_P are:

  • for each body β\beta: {Fβ}∪{Ta:a∈β+}∪{Fa:a∈β−}\{\mathbf{F}\beta\} \cup \{\mathbf{T}a : a \in \beta^+\} \cup \{\mathbf{F}a : a \in \beta^-\}, and {Tβ,Fa}\{\mathbf{T}\beta, \mathbf{F}a\} for a∈β+a \in \beta^+, and {Tβ,Ta}\{\mathbf{T}\beta, \mathbf{T}a\} for a∈β−a \in \beta^-, so that β\beta is true exactly when its literals hold;
  • for each atom pp with bodies β1,…,βk\beta_1, \ldots, \beta_k: {Fp,Tβi}\{\mathbf{F}p, \mathbf{T}\beta_i\} for each ii, and {Tp,Fβ1,…,Fβk}\{\mathbf{T}p, \mathbf{F}\beta_1, \ldots, \mathbf{F}\beta_k\}, so that pp is true exactly when one of its bodies is;
  • for each constraint with body β\beta: {Tβ}\{\mathbf{T}\beta\}.

For a set UU of atoms, the external bodies EB(U)EB(U) are the bodies of rules with head in UU whose positive part does not meet UU. The loop nogood of p∈Up \in U is λ(p,U)={Tp}∪{Fβ:β∈EB(U)}\lambda(p, U) = \{\mathbf{T}p\} \cup \{\mathbf{F}\beta : \beta \in EB(U)\}: pp cannot be true when no rule from outside UU supports UU.

  1. CDNL-ASP(P)
  2. 1Γ ← Δ_P; A ← an empty assignment; dl ← 0
  3. 2loop
  4. 3(A, ε) ← PROPAGATE(P, Γ, A) ▷ ε is a violated nogood, or none
  5. 4if ε ≠ none then
  6. 5if every literal of ε has level 0 then return "no answer set"
  7. 6(δ, j) ← ANALYZE(ε, A)
  8. 7Γ ← Γ ∪ {δ}; undo the literals of level above j; dl ← j
  9. 8else if A assigns every variable then return {p : Tp ∈ A}
  10. 9else dl ← dl + 1; add a decision literal on an open variable, at level dl
  11. PROPAGATE(P, Γ, A)
  12. 10loop
  13. 11while some δ ∈ Γ has all its literals in A but one, σ, which is open: add the complement of σ, with reason δ
  14. 12if some δ ∈ Γ has all its literals in A then return (A, δ)
  15. 13if P is tight then return (A, none)
  16. 14U ← the atoms not false in A that no body which is not false can derive
  17. 15if U = ∅ then return (A, none)
  18. 16Γ ← Γ ∪ {λ(p, U) : p ∈ U}
  19. ANALYZE(ε, A)
  20. 17k ← the largest level of a literal of ε
  21. 18while ε has two or more literals of level k do
  22. 19σ ← the literal of ε at level k assigned last; δ ← the reason of σ
  23. 20ε ← (ε ∖ {σ}) ∪ (δ ∖ {complement of σ})
  24. 21return (ε, 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 UU. After unit propagation every body in EB(U)EB(U) 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:

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.

The variables are p,q,r,sp, q, r, s and the bodies β1={not q}\beta_1 = \{\mathit{not}\ q\}, β2={not p}\beta_2 = \{\mathit{not}\ p\}, β3={p}\beta_3 = \{p\}, β4={s}\beta_4 = \{s\}, β5={r}\beta_5 = \{r\} and β6={not r}\beta_6 = \{\mathit{not}\ r\} of the constraint. ΔP\Delta_P has 22 nogoods. The program is not tight, because of the cycle r→s→rr \to s \to r.

level step new literals why
0 L11 Fβ6\mathbf{F}\beta_6, Tr\mathbf{T}r {Tβ6}\{\mathbf{T}\beta_6\}; then {Fβ6,Fr}\{\mathbf{F}\beta_6, \mathbf{F}r\}
0 L11 Tβ5\mathbf{T}\beta_5, Ts\mathbf{T}s, Tβ4\mathbf{T}\beta_4 the body and support nogoods of rr and ss
0 L14 U=∅U = \emptyset pp, qq can be derived from β1\beta_1, β2\beta_2, then rr from β3\beta_3, then ss
1 L9 Fp\mathbf{F}p decision
1 L11 Fβ3\mathbf{F}\beta_3, Tβ2\mathbf{T}\beta_2, Tq\mathbf{T}q, Fβ1\mathbf{F}\beta_1 the body nogoods of β3\beta_3, β2\beta_2, then qq, then β1\beta_1
1 L14 U={r,s}U = \{r, s\}, EB(U)={β3}EB(U) = \{\beta_3\} the only bodies that are not false and could derive rr or ss are β4\beta_4 and β5\beta_5, which need ss and rr
1 L16, L12 conflict on λ(r,U)={Tr,Fβ3}\lambda(r, U) = \{\mathbf{T}r, \mathbf{F}\beta_3\} Tr\mathbf{T}r is at level 0 and Fβ3\mathbf{F}\beta_3 at level 1
0 L6, L7 learn {Tr,Fβ3}\{\mathbf{T}r, \mathbf{F}\beta_3\}, back to level 0 only one literal of level 1, so it is already the first UIP
0 L11 Tβ3\mathbf{T}\beta_3, Tp\mathbf{T}p, Fβ2\mathbf{F}\beta_2, Fq\mathbf{F}q, Tβ1\mathbf{T}\beta_1 the learned nogood is unit
0 L8 answer set {p,r,s}\{p, r, s\} every variable is assigned and U=∅U = \emptyset

The run makes one decision, meets one conflict and adds two loop nogoods, λ(r,U)\lambda(r, U) and λ(s,U)\lambda(s, U). The assignment at level 1 before the conflict, with q,r,sq, r, s 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 ΔP\Delta_P and has an empty unfounded set. Then the true atoms XX form a model of the reduct PXP^X, because each true body forces its head, and every true atom is derived in the least model of PXP^X, because the unfounded set is empty. So XX is an answer set. Completeness: every nogood in the database is in ΔP\Delta_P, in the set ΛP\Lambda_P of all loop nogoods, or is a resolvent of nogoods already in the database. So the database is implied by ΔP∪ΛP\Delta_P \cup \Lambda_P, 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 PP be a finite ground normal program over a set AA of atoms, with rules h←Bh \leftarrow B and constraints ←B\leftarrow B. For a body B=b1,…,bm,not c1,…,not ckB = b_1, \ldots, b_m, \mathit{not}\ c_1, \ldots, \mathit{not}\ c_k we write B+={b1,…,bm}B^+ = \{b_1, \ldots, b_m\} and B−={c1,…,ck}B^- = \{c_1, \ldots, c_k\}. The solver has one variable for each atom and one for each distinct body. A literal is Tv\mathbf{T}v or Fv\mathbf{F}v. 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 X⊆AX \subseteq A induces the total assignment AXA_X that makes an atom true exactly when it is in XX and a body true exactly when XX satisfies it.

The nogoods (Gebser, Kaufmann and Schaub 2012)

For each body β\beta: δ(β)={Fβ}∪{Ta:a∈β+}∪{Fa:a∈β−}\delta(\beta) = \{\mathbf{F}\beta\} \cup \{\mathbf{T}a : a \in \beta^+\} \cup \{\mathbf{F}a : a \in \beta^-\}, and the nogoods {Tβ,Fa}\{\mathbf{T}\beta, \mathbf{F}a\} for a∈β+a \in \beta^+ and {Tβ,Ta}\{\mathbf{T}\beta, \mathbf{T}a\} for a∈β−a \in \beta^-. For each atom pp with bodies β1,…,βk\beta_1, \ldots, \beta_k: {Fp,Tβi}\{\mathbf{F}p, \mathbf{T}\beta_i\} for each ii, and δ(p)={Tp,Fβ1,…,Fβk}\delta(p) = \{\mathbf{T}p, \mathbf{F}\beta_1, \ldots, \mathbf{F}\beta_k\}. For each constraint with body β\beta: {Tβ}\{\mathbf{T}\beta\}. These nogoods form ΔP\Delta_P. Their solutions are exactly the assignments AXA_X such that XX is a model of the Clark completion of PP and of the constraints.

For U⊆AU \subseteq A, the external bodies EB(U)EB(U) are the bodies β\beta of rules with head in UU such that β+∩U=∅\beta^+ \cap U = \emptyset. The loop nogood of p∈Up \in U is λ(p,U)={Tp}∪{Fβ:β∈EB(U)}\lambda(p, U) = \{\mathbf{T}p\} \cup \{\mathbf{F}\beta : \beta \in EB(U)\}, and ΛP\Lambda_P is the set of all loop nogoods for all nonempty U⊆AU \subseteq A.

Theorem A (Gebser, Kaufmann and Schaub 2012). X⊆AX \subseteq A is an answer set of PP if and only if AXA_X is a solution of ΔP∪ΛP\Delta_P \cup \Lambda_P.

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 A\mathcal{A}, the set DD of atoms that can still be derived. DD is the least set such that if a body β\beta is not false in A\mathcal{A} and β+⊆D\beta^+ \subseteq D, then each head pp of β\beta that is not false is in DD. The set UU that it returns is the set of atoms that are not false and not in DD.

Lemma 1. Suppose that unit propagation over a set of nogoods that contains ΔP\Delta_P has reached a fixpoint without a violated nogood. Then every body in EB(U)EB(U) is false in A\mathcal{A}.

Proof. Let β∈EB(U)\beta \in EB(U) be a body of p∈Up \in U, and suppose that β\beta is not false. If some a∈β+a \in \beta^+ were false, the nogood {Tβ,Fa}\{\mathbf{T}\beta, \mathbf{F}a\} would be unit, and unit propagation would have made β\beta false. So every atom of β+\beta^+ is not false. Since β+∩U=∅\beta^+ \cap U = \emptyset, every atom of β+\beta^+ is in DD. Then pp, which is not false, is in DD by the definition of DD. This contradicts p∈Up \in U. □\square

So when U≠∅U \neq \emptyset, every new loop nogood λ(p,U)\lambda(p, U) with p∈Up \in U is violated, if pp is true, or unit, if pp 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 PP is tight (its positive dependency graph has no cycle), the solver adds no loop nogood, and every solution of ΔP\Delta_P is of the form AXA_X for an answer set XX.

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. □\square

Lemma 3. Let A\mathcal{A} be a total assignment that violates no nogood of ΔP\Delta_P and for which U=∅U = \emptyset. Let XX be its set of true atoms. Then XX is an answer set of PP and satisfies no constraint body.

Proof. Since A\mathcal{A} is total and violates no body nogood, a body is true exactly when XX satisfies it. Let LL be the least model of the reduct PXP^X. A rule of PXP^X is h←β+h \leftarrow \beta^+ for a rule h←βh \leftarrow \beta with β−∩X=∅\beta^- \cap X = \emptyset. If β+⊆X\beta^+ \subseteq X, then β\beta is true, and the nogood {Fh,Tβ}\{\mathbf{F}h, \mathbf{T}\beta\} gives h∈Xh \in X. So XX is a model of PXP^X and L⊆XL \subseteq X. Under a total assignment, DD is the least set closed under the rules h←β+h \leftarrow \beta^+ with β\beta true and hh true. Each of these is a rule of PXP^X, so D⊆LD \subseteq L. U=∅U = \emptyset means X⊆DX \subseteq D. So X⊆D⊆L⊆XX \subseteq D \subseteq L \subseteq X, and X=LX = L. The nogood {Tβ}\{\mathbf{T}\beta\} of each constraint is not violated, so β\beta is false. □\square

For a tight program, Lemma 2 covers the same case: a total solution of ΔP\Delta_P gives an answer set.

Learned nogoods

A nogood δ\delta is implied by a set Γ\Gamma of nogoods if every solution of Γ\Gamma is a solution of Γ∪{δ}\Gamma \cup \{\delta\}.

Lemma 4. Let Γ=ΔP∪ΛP∪Θ\Gamma = \Delta_P \cup \Lambda_P \cup \Theta, where Θ\Theta is the set of blocking nogoods of the run. Each nogood in the solver's database is in Γ\Gamma or implied by Γ\Gamma.

Proof. The nogoods of ΔP\Delta_P, the loop nogoods and the blocking nogoods are in Γ\Gamma. A learned nogood is built by ANALYZE. It starts from a violated nogood of the database and repeatedly replaces a literal σ\sigma by the other literals of the nogood ε\varepsilon that implied σ\sigma in unit propagation. That nogood holds the complement σˉ\bar\sigma. The new set is the resolvent (δ∖{σ})∪(ε∖{σˉ})(\delta \setminus \{\sigma\}) \cup (\varepsilon \setminus \{\bar\sigma\}). Let B\mathcal{B} be a solution of Γ\Gamma that contains the resolvent. B\mathcal{B} is total, so it contains σ\sigma or σˉ\bar\sigma. In the first case it contains δ\delta, and in the second case it contains ε\varepsilon. Both are implied by Γ\Gamma by induction, so this is impossible. □\square

Lemma 5 (analysis ends with an asserting nogood). Let the conflict have its largest decision level k≥1k \geq 1. ANALYZE ends, and its result has exactly one literal of level kk and its other literals at levels at most j<kj < k, where jj is the level returned.

Proof. While the set holds two or more literals of level kk, the one assigned last is not the decision literal of level kk, because that literal is the first one at level kk 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 kk decrease, so the loop ends. It ends exactly when one literal of level kk is left. jj is the largest level among the others, so j<kj < k. □\square

After the backjump to level jj, the learned nogood has all literals but one true, so unit propagation assigns the complement of its literal of level kk.

The theorem

Theorem. solve returns an answer set of PP 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 k≥1k \geq 1 is followed by a backjump and the assignment of an asserted literal at a level below kk. 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 0,1,…0, 1, \ldots 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, U=∅U = \emptyset. 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 XX be an answer set that is not blocked. By Theorem A, AXA_X is a solution of ΔP∪ΛP\Delta_P \cup \Lambda_P, and it is a solution of Θ\Theta. By Lemma 4, it violates no nogood of the database. The search returns None only after a conflict at level 00. All literals at level 00 follow from the database by unit propagation, so every solution of the database contains them. The conflict nogood would then be violated by AXA_X, 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. □\square

Running time

Let nn be the number of atoms and ss the size of the program, the number of rules plus the number of body literals. There are at most n+sn + s variables and O(s)O(s) nogoods in ΔP\Delta_P. The unfounded set computation takes O(n⋅s)O(n \cdot s) time with repeated scans, or O(s)O(s) 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 O(g)O(g) per pass for gg 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 ΛP\Lambda_P for every nonempty UU from the definition, independent of the solver code, and check Theorem A: the solutions of ΔP∪ΛP\Delta_P \cup \Lambda_P 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 ss be the number of rules plus the number of body literals. There are at most n+sn + s variables, and ΔP\Delta_P has O(s)O(s) nogoods of total size O(s)O(s). The full set ΛP\Lambda_P of loop nogoods can have n⋅2nn \cdot 2^n members, which is why it is built on demand. The unfounded set check at line L14 takes O(s)O(s) 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 2O((n+s)log⁡(n+s))2^{O((n + s) \log(n + s))} 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 {q,r,s}\{q, r, s\} in the example, which are not answer sets.
  • External bodies. A body that contains an atom of UU 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 {Tβ}\{\mathbf{T}\beta\}; 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.

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

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

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