Algorithm Search⌘K

Data structureadvanced

Deterministic decomposable negation normal form

Also called d-DNNF.

A circuit of and, or and literals whose ands have disjoint variables and whose ors have disjoint models. It gives linear-time consistency, clause entailment and model counting.

Time
O(s) clause_entailment · condition · consistency · count_smoothO(s n) smooth
Space
O(s) circuitO(s n) smoothed_circuit
Where
n = the number of variables; s = the number of edges of the circuit
Properties
not concurrentnot externalpersistent
Origin
Adnan Darwiche, 2001

A d-DNNF is a Boolean circuit in negation normal form, built from literals, constants, and-gates and or-gates, with two properties: the inputs of each and-gate share no variable (decomposability), and the inputs of each or-gate have no common model (determinism). Darwiche (2001) introduced it as a target language for knowledge compilation: a CNF is compiled once, and then consistency, clause entailment and model counting take time linear in the size of the circuit. The model counting page gives the counting problem and its place among counting problems; this page is the data structure, its compiler and its queries, and the knowledge compilation map compares it with the other languages.

In plain words

A formula can be written as a network of "and" and "or" gates over the variables and their negations. In general such a network is hard to ask questions about: even "can this ever be true?" is hard. Add two rules. Under an "and", the parts must talk about different variables, so each part can be solved on its own. Under an "or", the parts must never be true at the same time, so the ways to make them true never overlap. With these rules, you can count the ways to make the whole thing true by one pass from the bottom: multiply under "and", add under "or". The hard work moves to the step that builds the network. A search that tries a variable both ways, and splits the problem into independent parts when it can, builds such a network as a record of its work.

The abstract type

An NNF circuit over the variables XX is a rooted DAG whose leaves are labelled true\mathit{true}, false\mathit{false}, xx or ¬x\neg x for x∈Xx \in X, and whose inner nodes are labelled ∧\wedge or ∨\vee. Each node uu denotes a Boolean function fuf_u in the usual way, and vars(u)\mathrm{vars}(u) is the set of variables at the leaves below uu. Following Darwiche and Marquis (2002, Section 2), the circuit is

  • decomposable if for each and-node uu with children c1,…,ckc_1, \ldots, c_k, vars(ci)∩vars(cj)=∅\mathrm{vars}(c_i) \cap \mathrm{vars}(c_j) = \emptyset for all i≠ji \ne j;
  • deterministic if for each or-node uu with children c1,…,ckc_1, \ldots, c_k, fci∧fcj≡falsef_{c_i} \wedge f_{c_j} \equiv \mathit{false} for all i≠ji \ne j;
  • smooth if for each or-node uu, vars(ci)=vars(u)\mathrm{vars}(c_i) = \mathrm{vars}(u) for every child cic_i.

A DNNF is a decomposable NNF circuit, a d-DNNF is a deterministic DNNF, and an sd-DNNF is a smooth d-DNNF. Decomposability and smoothness are syntactic and can be checked in linear time. Determinism is semantic. A decision node is an or-node of the form (x∧α)∨(¬x∧β)(x \wedge \alpha) \vee (\neg x \wedge \beta), and a circuit whose or-nodes are all decision nodes is a decision-DNNF. It is deterministic by its shape, since the two children disagree on xx. The compiler on this page outputs decision-DNNF, which is a proper subset of d-DNNF; it never builds or-nodes whose children are contradictory for a deeper reason.

The operations are COMPILE (from CNF), CO (consistency), CONDITION, CE (clause entailment), SMOOTH and CT (model count).

Representation

The nodes live in one array. Node 0 is false\mathit{false}, node 1 is true\mathit{true}, and every other node is a literal or a tuple of an operator and the sorted ids of its children. A hash table maps each such key to its id (hash-consing), so a subcircuit built twice is stored once. A child always has a smaller id than its parent, so a loop over the ids below the root in increasing order visits children first; every query is one such loop. The constructors AND and OR fold constants: an and-node with a false\mathit{false} child is false\mathit{false}, true\mathit{true} children are dropped, and a gate with one child is that child. Folding keeps both properties, because it only removes children or replaces a gate by one of its children.

Operations

The compiler is exhaustive DPLL with unit propagation, a split into connected components, and a cache of compiled sub-problems. For a set of clauses Δ\Delta and a literal ll, Δ∣l\Delta|l removes the clauses that contain ll and deletes ¬l\neg l from the others.

  1. COMPILE(Δ) ▷ Δ is a set of clauses; returns a node
  2. 1if Δ = ∅ then return true
  3. 2if Δ contains the empty clause then return false
  4. 3if Δ is in the cache C then return C[Δ]
  5. 4if Δ has a unit clause {l} then
  6. 5r ← AND(l, COMPILE(Δ|l))
  7. 6else if the clauses of Δ split into groups Δ_1, ..., Δ_k, k ≥ 2, that share no variable then
  8. 7r ← AND(COMPILE(Δ_1), ..., COMPILE(Δ_k))
  9. 8else
  10. 9x ← a variable with the most occurrences in Δ
  11. 10r ← OR(AND(x, COMPILE(Δ|x)), AND(¬x, COMPILE(Δ|¬x)))
  12. 11C[Δ] ← r; return r

The queries walk the circuit once, children first.

  1. CO(N) ▷ N is decomposable
  2. 1for each node u below N, children first do
  3. 2if u is a literal or true then c[u] ← 1; if u is false then c[u] ← 0
  4. 3if u is an and-node then c[u] ← 1 if c[v] = 1 for every child v, else 0
  5. 4if u is an or-node then c[u] ← 1 if c[v] = 1 for some child v, else 0
  6. 5return c[N] = 1
  7. CONDITION(N, γ) ▷ γ is a set of literals with no complementary pair
  8. 6for each node u below N, children first: a literal in γ becomes true, a literal whose negation is in γ becomes false, and each gate is rebuilt with AND or OR
  9. CE(N, δ) ▷ does N entail the clause δ?
  10. 7if δ contains a literal and its negation then return true
  11. 8return not CO(CONDITION(N, {¬l : l ∈ δ}))
  12. SMOOTH(N, X) ▷ X ⊇ vars(N)
  13. 9for each node u below N, children first, rebuild u; if u is an or-node then
  14. 10replace each child v by AND(v, (y ∨ ¬y) for each y ∈ vars(u) \ vars(v))
  15. 11return AND(N', (y ∨ ¬y) for each y ∈ X \ vars(N)) ▷ N' is the rebuilt root
  16. CT(N) ▷ N is a smooth d-DNNF with vars(N) = X
  17. 12for each node u below N, children first: literal 1, true 1, false 0, and-node the product of its children, or-node the sum
  18. 13return the value at N

Example

Let Δ=(x1∨x2)∧(¬x1∨x3)∧(x4∨x5)∧(¬x4∨¬x5)\Delta = (x_1 \vee x_2) \wedge (\neg x_1 \vee x_3) \wedge (x_4 \vee x_5) \wedge (\neg x_4 \vee \neg x_5) over x1,…,x5x_1, \ldots, x_5.

call rule result
Δ\Delta L6: groups {x1,x2,x3}\{x_1, x_2, x_3\} and {x4,x5}\{x_4, x_5\} AND of the two results
first group L9: x1x_1 occurs twice OR of the two branches
$\Delta x_1 = {x_3}$ L5
$\Delta \neg x_1 = {x_2}$ L5
second group L9: x4x_4 (a tie with x5x_5, broken by the index) OR of the two branches
{¬x5}\{\neg x_5\} and {x5}\{x_5\} L5 ¬x5\neg x_5 and x5x_5

The circuit is

((x1∧x3)∨(¬x1∧x2))∧((x4∧¬x5)∨(¬x4∧x5)),\big((x_1 \wedge x_3) \vee (\neg x_1 \wedge x_2)\big) \wedge \big((x_4 \wedge \neg x_5) \vee (\neg x_4 \wedge x_5)\big),

with 15 nodes, 14 edges and 2 decisions. SMOOTH adds (x2∨¬x2)(x_2 \vee \neg x_2) under x1∧x3x_1 \wedge x_3 and (x3∨¬x3)(x_3 \vee \neg x_3) under ¬x1∧x2\neg x_1 \wedge x_2; the second or-node is already smooth. CT then gives 1⋅1⋅2=21 \cdot 1 \cdot 2 = 2 for each branch of the first or-node, 2+2=42 + 2 = 4 for the first group, 1+1=21 + 1 = 2 for the second, and 4⋅2=84 \cdot 2 = 8 at the root, which is the number of models of Δ\Delta. For CE with δ=x2∨x3\delta = x_2 \vee x_3, CONDITION with {¬x2,¬x3}\{\neg x_2, \neg x_3\} turns both branches of the first or-node into false\mathit{false}, so the root is false\mathit{false} and Δ⊨x2∨x3\Delta \models x_2 \vee x_3. With δ=x2\delta = x_2, the branch x1∧x3x_1 \wedge x_3 survives, so Δ⊭x2\Delta \not\models x_2.

Correctness

The proofs are in the correctness proof. In short:

  • COMPILE is equivalent to Δ\Delta. Line L5 uses Δ≡l∧Δ∣l\Delta \equiv l \wedge \Delta|l when {l}∈Δ\{l\} \in \Delta, line L7 uses that Δ\Delta is the conjunction of its groups, and line L10 is the Shannon expansion Δ≡(x∧Δ∣x)∨(¬x∧Δ∣¬x)\Delta \equiv (x \wedge \Delta|x) \vee (\neg x \wedge \Delta|\neg x).
  • The output is a decision-DNNF. vars(COMPILE(Δ′))⊆vars(Δ′)\mathrm{vars}(\mathrm{COMPILE}(\Delta')) \subseteq \mathrm{vars}(\Delta'), so line L5 is decomposable because Δ∣l\Delta|l does not mention the variable of ll, line L7 because the groups share no variable, and line L10 for the same reason as L5. The or-node of line L10 is a decision node on xx.
  • CO on a DNNF. An and-node is satisfiable if and only if each child is, because the children have disjoint variables and their models combine. This fails without decomposability: x∧¬xx \wedge \neg x has two satisfiable children.
  • CE. Σ⊨δ\Sigma \models \delta if and only if Σ∧¬δ\Sigma \wedge \neg \delta is unsatisfiable, if and only if Σ∣¬δ\Sigma|\neg\delta is unsatisfiable, and CONDITION keeps decomposability because it only removes variables (Darwiche and Marquis 2002, Lemma A.4).
  • CT on an sd-DNNF. Count the models of fuf_u over vars(u)\mathrm{vars}(u). For an and-node the models are the tuples of models of the children, by decomposability, so the counts multiply. For an or-node the children have the same variables, by smoothness, and no common model, by determinism, so the counts add. SMOOTH keeps the function, decomposability and determinism, because each added factor y∨¬yy \vee \neg y is valid and mentions a variable that the child does not.
Proof: The CNF to decision-DNNF compiler and the linear-time d-DNNF queries are correctfull

We use the pseudocode of the page, lines L1 to L24. For a node uu, fuf_u is its function and vars(u)\mathrm{vars}(u) is the set of variables at the leaves below uu. For a set of variables Y⊇vars(u)Y \supseteq \mathrm{vars}(u), #Y(u)\#_Y(u) is the number of assignments to YY that satisfy fuf_u. For a clause set Δ\Delta, vars(Δ)\mathrm{vars}(\Delta) is the set of variables in its clauses, and Δ∣l\Delta|l is defined on the page.

Lemma 0 (constructors). AND(c1,…,ck)(c_1, \ldots, c_k) returns a node whose function is fc1∧⋯∧fckf_{c_1} \wedge \cdots \wedge f_{c_k} and whose variables are a subset of ⋃ivars(ci)\bigcup_i \mathrm{vars}(c_i); if the cic_i have pairwise disjoint variables and are decomposable, so is the result. OR is the same with ∨\vee; if the cic_i are pairwise contradictory and deterministic, so is the result.

Proof. The constructor either returns false\mathit{false} (for AND, when a child is false\mathit{false}; the conjunction is then false), or removes true\mathit{true} children (which does not change a conjunction), or returns the only remaining child, or makes a gate over the remaining children. Removing children keeps disjointness of variables and pairwise contradiction among the rest. The duals hold for OR. Hash-consing returns a node with the same key, hence the same function. □\square

The compiler

Lemma 1 (equivalence). COMPILE(Δ)(\Delta) returns a node rr with fr≡Δf_r \equiv \Delta and vars(r)⊆vars(Δ)\mathrm{vars}(r) \subseteq \mathrm{vars}(\Delta).

Proof. By induction on ∣vars(Δ)∣|\mathrm{vars}(\Delta)|, and for equal values on the order of the calls (a cached result was computed earlier for the same Δ\Delta, so line L3 is covered by the hypothesis for that earlier call). Line L1: the empty conjunction is true\mathit{true}. Line L2: a clause set with the empty clause is unsatisfiable. Line L5: if {l}∈Δ\{l\} \in \Delta, every model of Δ\Delta sets ll true, and under l=1l = 1 the clauses with ll are satisfied and ¬l\neg l is false in the rest, so Δ≡l∧Δ∣l\Delta \equiv l \wedge \Delta|l. The set Δ∣l\Delta|l does not mention the variable of ll, so it has fewer variables, and the hypothesis and Lemma 0 give the claim. Line L7: Δ\Delta is the conjunction of its groups. Each group is non-empty and the groups have pairwise disjoint, non-empty variable sets, so with k≥2k \ge 2 each group has fewer variables than Δ\Delta. Line L10: the Shannon expansion Δ≡(x∧Δ∣x)∨(¬x∧Δ∣¬x)\Delta \equiv (x \wedge \Delta|x) \vee (\neg x \wedge \Delta|\neg x), where Δ∣x\Delta|x and Δ∣¬x\Delta|\neg x do not mention xx. □\square

Lemma 2 (decision-DNNF). Every node that COMPILE creates is decomposable, and every or-node is a decision node, hence deterministic.

Proof. By the same induction. At line L5, the literal ll and the node for Δ∣l\Delta|l have disjoint variables, by Lemma 1. At line L7, the node for Δi\Delta_i has variables in vars(Δi)\mathrm{vars}(\Delta_i), and these sets are pairwise disjoint. At line L10, each and-node joins xx or ¬x\neg x with a node whose variables avoid xx. The or-node has the children x∧αx \wedge \alpha and ¬x∧β\neg x \wedge \beta, which no assignment satisfies together. By Lemma 0 the folding of constants keeps both properties. □\square

Lemma 3 (termination). Without the cache, the recursion tree of COMPILE(Δ)(\Delta) has at most 2∣vars(Δ)∣2^{|\mathrm{vars}(\Delta)|} leaves.

Proof. Let L(n)L(n) be the largest number of leaves for nn variables. A call that stops at lines L1 to L3 is one leaf, and 1≤2n1 \le 2^n. Line L5 makes one call with at most n−1n - 1 variables. Line L7 makes calls on n1,…,nk≥1n_1, \ldots, n_k \ge 1 variables with ∑ni≤n\sum n_i \le n and k≥2k \ge 2, and ∑2ni≤2∑ni\sum 2^{n_i} \le 2^{\sum n_i} because 2a+2b≤2a+b2^a + 2^b \le 2^{a+b} for a,b≥1a, b \ge 1. Line L10 makes two calls with at most n−1n - 1 variables, and 2⋅2n−1=2n2 \cdot 2^{n-1} = 2^n. Each call has fewer variables than its caller, so the depth is at most nn and the recursion stops. The cache returns early at line L3 and only removes subtrees. □\square

The queries

Lemma 4 (CO). If NN is decomposable, CO(N)(N) returns true if and only if fNf_N is satisfiable.

Proof. We show c[u]=1c[u] = 1 if and only if fuf_u is satisfiable, for each uu in the order of line L12. Leaves (line L13): a literal and true\mathit{true} are satisfiable, false\mathit{false} is not. An or-node (line L15) is satisfiable if and only if some child is. An and-node uu (line L14) with an unsatisfiable child is unsatisfiable. If every child cic_i has a model μi\mu_i over vars(ci)\mathrm{vars}(c_i), the sets vars(ci)\mathrm{vars}(c_i) are pairwise disjoint, so the union of the μi\mu_i is a well-defined assignment, and it satisfies every child, hence fuf_u. □\square

Lemma 5 (CONDITION). For a set γ\gamma of literals with no complementary pair, CONDITION(N,γ)(N, \gamma) returns a node N′N' with fN′=fN∣γf_{N'} = f_N|\gamma (the function with the variables of γ\gamma fixed so that γ\gamma is true). If NN is decomposable or deterministic, so is N′N', and vars(N′)⊆vars(N)∖vars(γ)\mathrm{vars}(N') \subseteq \mathrm{vars}(N) \setminus \mathrm{vars}(\gamma).

Proof. By induction in the order of line L17. A literal l∈γl \in \gamma becomes true=l∣γ\mathit{true} = l|\gamma, a literal with ¬l∈γ\neg l \in \gamma becomes false\mathit{false}, and any other literal is kept. Restriction commutes with ∧\wedge and ∨\vee, and Lemma 0 gives the function of the rebuilt gate. Variables only disappear, so disjointness is kept. If fci∧fcj≡falsef_{c_i} \wedge f_{c_j} \equiv \mathit{false}, then (fci∣γ)∧(fcj∣γ)=(fci∧fcj)∣γ≡false(f_{c_i}|\gamma) \wedge (f_{c_j}|\gamma) = (f_{c_i} \wedge f_{c_j})|\gamma \equiv \mathit{false}, so determinism is kept. □\square

Lemma 6 (CE). If NN is decomposable, CE(N,δ)(N, \delta) returns true if and only if fN⊨δf_N \models \delta.

Proof. If δ\delta contains ll and ¬l\neg l, it is valid and line L18 is right. Otherwise ¬δ\neg\delta is the consistent term γ={¬l:l∈δ}\gamma = \{\neg l : l \in \delta\}. fN⊨δf_N \models \delta if and only if fN∧γf_N \wedge \gamma is unsatisfiable. A model of fN∧γf_N \wedge \gamma restricts to a model of fN∣γf_N|\gamma, and a model of fN∣γf_N|\gamma extends by γ\gamma to a model of fN∧γf_N \wedge \gamma, since fN∣γf_N|\gamma does not mention vars(γ)\mathrm{vars}(\gamma). So line L19 is right by Lemmas 4 and 5. □\square

Lemma 7 (SMOOTH). SMOOTH(N,X)(N, X) returns a node N′′N'' with fN′′≡fNf_{N''} \equiv f_N, vars(N′′)=X\mathrm{vars}(N'') = X, which is smooth, and which is decomposable (deterministic) when NN is.

Proof. By induction in the order of line L20, the rebuilt node u′u' of uu has fu′≡fuf_{u'} \equiv f_u and vars(u′)=vars(u)\mathrm{vars}(u') = \mathrm{vars}(u). For an and-node this follows from the children by Lemma 0. For an or-node uu, line L21 replaces the rebuilt child v′v' by v′∧⋀y(y∨¬y)v' \wedge \bigwedge_{y} (y \vee \neg y) over y∈vars(u)∖vars(v)y \in \mathrm{vars}(u) \setminus \mathrm{vars}(v). Each factor is valid, so the function is fvf_v, and the variables become exactly vars(u)\mathrm{vars}(u), so all children of u′u' have the same variables (smooth). The new and-node is decomposable: v′v' has the variables vars(v)\mathrm{vars}(v), the factors mention distinct variables outside it, and each factor y∨¬yy \vee \neg y is an or-node of two literals on one variable, which is smooth and deterministic. The functions of the children of u′u' are those of uu, so pairwise contradiction is kept. Line L22 is the same step at the root with XX in place of vars(u)\mathrm{vars}(u). □\square

Lemma 8 (CT). If NN is a smooth d-DNNF, the value t[u]t[u] of line L23 is #vars(u)(u)\#_{\mathrm{vars}(u)}(u) for each node uu. So CT(SMOOTH(N,X))(\mathrm{SMOOTH}(N, X)) is the number of models of fNf_N over XX.

Proof. By induction in the order of line L23. A literal has one model over its variable; true\mathit{true} has one model over ∅\emptyset and false\mathit{false} none. For an and-node uu with children c1,…,ckc_1, \ldots, c_k and pairwise disjoint Vi=vars(ci)V_i = \mathrm{vars}(c_i), the map μ↦(μ∣V1,…,μ∣Vk)\mu \mapsto (\mu|_{V_1}, \ldots, \mu|_{V_k}) is a bijection from the assignments to vars(u)=⋃Vi\mathrm{vars}(u) = \bigcup V_i onto tuples of assignments to the ViV_i, and μ\mu satisfies fuf_u if and only if each μ∣Vi\mu|_{V_i} satisfies fcif_{c_i}. So #(u)=∏i#(ci)\#(u) = \prod_i \#(c_i). For an or-node uu, smoothness gives vars(ci)=vars(u)\mathrm{vars}(c_i) = \mathrm{vars}(u) for all ii, so all counts are over the same set. The model sets of the children are pairwise disjoint by determinism, and their union is the model set of fuf_u, so #(u)=∑i#(ci)\#(u) = \sum_i \#(c_i). The second sentence follows from Lemma 7, which gives vars(SMOOTH(N,X))=X\mathrm{vars}(\mathrm{SMOOTH}(N, X)) = X and keeps the function and the two properties. □\square

Cost. Each query visits each node below the root once and does work proportional to its number of children, plus one expected O(1)O(1) hash lookup in CONDITION and SMOOTH, so CO, CONDITION and CE take O(s)O(s) expected time for ss edges. SMOOTH adds at most ∣X∣|X| factors of size O(1)O(1) for each edge out of an or-node and at the root, so its output has O(sn)O(s n) edges with n=∣X∣n = |X|. □\square

Complexity

operation time needs
CO O(s)O(s) decomposability
CONDITION O(s)O(s) expected nothing
CE O(s)O(s) expected decomposability
SMOOTH O(sn)O(s n), and the output has O(sn)O(s n) edges decomposability
CT O(s)O(s) additions and multiplications of numbers of at most nn bits smoothness, decomposability, determinism
COMPILE exponential in nn in the worst case nothing

Darwiche and Marquis (2002, Table 5) also list validity, implicant checking and model enumeration as polynomial for d-DNNF. They leave equivalence of two d-DNNFs open, with a probabilistic polynomial test, and they show that sentential entailment is not polynomial unless P = NP. Their Table 7 shows that d-DNNF supports conditioning, but not forgetting, conjunction or disjunction of two circuits in polynomial time unless P = NP; whether negation is polynomial is open.

The compiler cannot be polynomial on all inputs unless P = NP: its output answers CO in linear time, and CO of the output decides SAT of the input. Without the cache, the recursion has at most 2n2^n leaves, since a decision on one variable doubles the branches and a split into groups divides the variables; the cache can only shorten this. Much better bounds hold for structured inputs: Darwiche (2001, JACM) shows that a CNF of bounded treewidth has a DNNF of linear size.

Variants

  • DNNF drops determinism. It still supports CO, CE and model enumeration, but not counting: in the DNNF x∨yx \vee y the two children share the model x=y=1x = y = 1, so after smoothing the sum is 2+2=42 + 2 = 4, but the function has 3 models.
  • Decision-DNNF is the output of this compiler and of other search-based compilers (Huang and Darwiche 2007).
  • FBDD and OBDD. Read as an NNF circuit, a free BDD is a decision-DNNF in which every and-node is the x∧αx \wedge \alpha part of a decision node. Huang and Darwiche (2007) show that the trace of exhaustive DPLL without the component split of line L7 is an FBDD, and an OBDD when the variable order is fixed.
  • Sentential decision diagram. A d-DNNF with structured decomposability and a canonical form for a fixed vtree. Its apply operation conjoins or disjoins two SDDs for the same vtree in polynomial time when the result need not be compressed.
  • Weighted counting. Give each literal a weight and use the same pass with the weight in place of 1 at the leaves. With weights taken from the parameters of a Bayesian network, this pass computes probabilities.

When to use it

Use a d-DNNF when one knowledge base receives many counting or probability queries, possibly under different evidence, so that the cost of compiling is paid once. Each query is then one linear pass, and evidence is a CONDITION. Do not use it when the knowledge base changes often by conjunction with new clauses: d-DNNF does not support conjunction of two circuits in polynomial time, and an OBDD or an SDD fits that use better.

Pitfalls

  • Counting without smoothing. On x1∨(¬x1∧x2)x_1 \vee (\neg x_1 \wedge x_2) the bottom-up sum gives 1+1=21 + 1 = 2, but the function has 3 models over {x1,x2}\{x_1, x_2\}, because the child x1x_1 does not mention x2x_2. Smooth first, or multiply each child count by 22 to the power of the number of missing variables. The root also needs smoothing to all the variables of the problem: a variable that the CNF mentions but the circuit does not doubles the count.
  • Checking determinism. For a general NNF circuit, deciding whether two children of an or-node are contradictory is coNP-hard, since it includes unsatisfiability of an NNF formula. A compiler must make determinism hold by construction, for example with decision nodes. A d-DNNF that comes from elsewhere cannot be checked cheaply.
  • Consistency needs decomposability. CONDITION keeps decomposability, but a conjunction of two d-DNNFs under one and-node is not decomposable in general. CO on it can then answer "satisfiable" for x∧¬xx \wedge \neg x.
  • Cache keys. The cache of line L3 must use the residual clause set itself (or a canonical encoding of it), not only the set of free variables, or two different sub-problems share one result.

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.

d_dnnf.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/d-dnnf/. The authors are listed in prov/FSRAPA.jsonl.
"""A compiler from CNF to d-DNNF, and the linear-time queries of d-DNNF.

A CNF is a list of clauses. A clause is a tuple of nonzero integers in the
DIMACS style: the literal 3 is x3 and the literal -3 is the negation of x3.
The variables are 1 to n.

A circuit lives in a Circuit object. Node 0 is FALSE and node 1 is TRUE.
Every other node is one of

    ("lit", l)                  a literal
    ("and", (c1, c2, ...))      a conjunction of the child nodes
    ("or", (c1, c2, ...))       a disjunction of the child nodes

Nodes are hash-consed: the same triple always gets the same id. A child
always has a smaller id than its parent, so a loop over the ids in
increasing order visits the children before the parents. Each query below is
one such loop, so its time is linear in the number of nodes plus edges.

The compiler is exhaustive DPLL with unit propagation, a split into
independent components and a cache of compiled components (the method of
Huang and Darwiche, "The language of search", JAIR 29, 2007). Its output is
a decision-DNNF: every or-node is a decision node (x and A) or (not x and B).
Decision-DNNF is a subset of d-DNNF, and this module does not produce the
other members of d-DNNF.
"""

from __future__ import annotations

FALSE, TRUE = 0, 1


class Circuit:
    """A store of hash-consed NNF nodes."""

    def __init__(self) -> None:
        self.nodes: list[tuple] = [("false",), ("true",)]
        self.unique: dict[tuple, int] = {}

    def _make(self, key: tuple) -> int:
        u = self.unique.get(key)
        if u is None:
            u = len(self.nodes)
            self.nodes.append(key)
            self.unique[key] = u
        return u

    def lit(self, l: int) -> int:
        return self._make(("lit", l))

    def conj(self, children) -> int:
        """The and of the children, with FALSE and TRUE folded."""
        kept = set()
        for c in children:
            if c == FALSE:
                return FALSE
            if c != TRUE:
                kept.add(c)
        if not kept:
            return TRUE
        if len(kept) == 1:
            return kept.pop()
        return self._make(("and", tuple(sorted(kept))))

    def disj(self, children) -> int:
        """The or of the children, with FALSE and TRUE folded."""
        kept = set()
        for c in children:
            if c == TRUE:
                return TRUE
            if c != FALSE:
                kept.add(c)
        if not kept:
            return FALSE
        if len(kept) == 1:
            return kept.pop()
        return self._make(("or", tuple(sorted(kept))))

    # ---------------------------------------------------------------- queries

    def size(self, root: int) -> int:
        """The number of edges below the root."""
        return sum(len(self.nodes[u][1]) for u in self.reachable(root) if self.nodes[u][0] in ("and", "or"))

    def reachable(self, root: int) -> list[int]:
        """The ids of the nodes below the root (root included), in increasing order."""
        seen = {root}
        stack = [root]
        while stack:
            u = stack.pop()
            key = self.nodes[u]
            if key[0] in ("and", "or"):
                for c in key[1]:
                    if c not in seen:
                        seen.add(c)
                        stack.append(c)
        return sorted(seen)

    def variables(self, root: int) -> dict[int, frozenset[int]]:
        """vars(u) for each node u below the root."""
        out: dict[int, frozenset[int]] = {}
        for u in self.reachable(root):
            key = self.nodes[u]
            if key[0] == "lit":
                out[u] = frozenset([abs(key[1])])
            elif key[0] in ("and", "or"):
                out[u] = frozenset().union(*(out[c] for c in key[1]))
            else:
                out[u] = frozenset()
        return out

    def evaluate(self, root: int, assignment: dict[int, bool]) -> bool:
        """The value of the circuit under a full assignment of its variables."""
        val: dict[int, bool] = {}
        for u in self.reachable(root):
            key = self.nodes[u]
            if key[0] == "lit":
                l = key[1]
                val[u] = assignment[abs(l)] == (l > 0)
            elif key[0] == "and":
                val[u] = all(val[c] for c in key[1])
            elif key[0] == "or":
                val[u] = any(val[c] for c in key[1])
            else:
                val[u] = u == TRUE
        return val[root]

    def consistent(self, root: int) -> bool:
        """CO: is the circuit satisfiable? Correct when the circuit is decomposable."""
        val: dict[int, bool] = {}
        for u in self.reachable(root):  # @line L12
            key = self.nodes[u]
            if key[0] == "lit":  # @line L13
                val[u] = True
            elif key[0] == "and":  # @line L14
                val[u] = all(val[c] for c in key[1])
            elif key[0] == "or":  # @line L15
                val[u] = any(val[c] for c in key[1])
            else:
                val[u] = u == TRUE
        return val[root]  # @line L16

    def condition(self, root: int, term: set[int]) -> int:
        """The circuit with each literal of the term set to TRUE and its negation to FALSE."""
        new: dict[int, int] = {}
        for u in self.reachable(root):  # @line L17
            key = self.nodes[u]
            if key[0] == "lit":
                l = key[1]
                new[u] = TRUE if l in term else FALSE if -l in term else u
            elif key[0] == "and":
                new[u] = self.conj(new[c] for c in key[1])
            elif key[0] == "or":
                new[u] = self.disj(new[c] for c in key[1])
            else:
                new[u] = u
        return new[root]

    def entails_clause(self, root: int, clause) -> bool:
        """CE: does the circuit entail the clause? Uses conditioning on the negated clause, then CO."""
        lits = set(clause)
        if any(-l in lits for l in lits):  # @line L18
            return True
        return not self.consistent(self.condition(root, {-l for l in lits}))  # @line L19

    def smooth(self, root: int, all_vars) -> int:
        """An equivalent smooth circuit whose root mentions every variable of all_vars."""
        vs = self.variables(root)
        new: dict[int, int] = {}

        def pad(u: int, have: frozenset[int], want: frozenset[int]) -> int:
            missing = sorted(want - have)
            return self.conj([u] + [self.disj([self.lit(v), self.lit(-v)]) for v in missing])

        for u in self.reachable(root):  # @line L20
            key = self.nodes[u]
            if key[0] == "and":
                new[u] = self.conj(new[c] for c in key[1])
            elif key[0] == "or":
                new[u] = self.disj(pad(new[c], vs[c], vs[u]) for c in key[1])  # @line L21
            else:
                new[u] = u
        return pad(new[root], vs[root], frozenset(all_vars))  # @line L22

    def is_smooth(self, root: int) -> bool:
        vs = self.variables(root)
        return all(
            len({vs[c] for c in self.nodes[u][1]}) == 1 for u in vs if self.nodes[u][0] == "or"
        )

    def count_smooth(self, root: int) -> int:
        """CT on a smooth d-DNNF: literals count 1, an and multiplies, an or adds."""
        cnt: dict[int, int] = {}
        for u in self.reachable(root):  # @line L23
            key = self.nodes[u]
            if key[0] == "lit":
                cnt[u] = 1
            elif key[0] == "and":
                p = 1
                for c in key[1]:
                    p *= cnt[c]
                cnt[u] = p
            elif key[0] == "or":
                cnt[u] = sum(cnt[c] for c in key[1])
            else:
                cnt[u] = 1 if u == TRUE else 0
        return cnt[root]  # @line L24

    def model_count(self, root: int, n: int) -> int:
        """The number of models over the variables 1 to n."""
        return self.count_smooth(self.smooth(root, range(1, n + 1)))


# -------------------------------------------------------------------- compiler


def _simplify(clauses: frozenset, lit: int):
    """The clauses after setting lit to true, or None on an empty clause."""
    out = set()
    for c in clauses:
        if lit in c:
            continue
        if -lit in c:
            c = c - {-lit}
            if not c:
                return None
        out.add(c)
    return frozenset(out)


def _components(clauses: frozenset) -> list[frozenset]:
    """The clauses grouped into sets that share no variable."""
    parent: dict[int, int] = {}

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    for c in clauses:
        vs = [abs(l) for l in c]
        for v in vs:
            parent.setdefault(v, v)
        for v in vs[1:]:
            a, b = find(vs[0]), find(v)
            if a != b:
                parent[a] = b
    groups: dict[int, set] = {}
    for c in clauses:
        groups.setdefault(find(abs(next(iter(c)))), set()).add(c)
    return [frozenset(g) for g in groups.values()]


class Compiler:
    """Exhaustive DPLL with components and a cache; the trace is a decision-DNNF."""

    def __init__(self, circuit: Circuit | None = None) -> None:
        self.circuit = circuit or Circuit()
        self.cache: dict[frozenset, int] = {}
        self.decisions = 0

    def compile(self, cnf) -> int:
        clauses = frozenset(frozenset(c) for c in cnf)
        if any(any(-l in c for l in c) for c in clauses):
            clauses = frozenset(c for c in clauses if not any(-l in c for l in c))
        return self._compile(clauses)

    def _compile(self, clauses: frozenset) -> int:
        cc = self.circuit
        if not clauses:  # @line L1
            return TRUE
        if clauses in self.cache:  # @line L3
            return self.cache[clauses]
        # Unit propagation: the units become and-children of the result.
        units: list[int] = []
        rest = clauses
        while True:
            unit = next((c for c in rest if len(c) == 1), None)  # @line L4
            if unit is None:
                break
            l = next(iter(unit))
            units.append(l)
            rest = _simplify(rest, l)
            if rest is None:  # @line L2
                self.cache[clauses] = FALSE
                return FALSE
        if units:
            result = cc.conj([cc.lit(l) for l in units] + [self._compile(rest)])  # @line L5
        else:
            parts = _components(rest)
            if len(parts) > 1:  # @line L6
                result = cc.conj(self._compile(p) for p in parts)  # @line L7
            else:  # @line L8
                result = self._decide(rest)
        self.cache[clauses] = result  # @line L11
        return result

    def _decide(self, clauses: frozenset) -> int:
        cc = self.circuit
        freq: dict[int, int] = {}
        for c in clauses:
            for l in c:
                freq[abs(l)] = freq.get(abs(l), 0) + 1
        x = min(freq, key=lambda v: (-freq[v], v))  # @line L9
        self.decisions += 1
        branches = []
        for l in (x, -x):
            sub = _simplify(clauses, l)
            body = FALSE if sub is None else self._compile(sub)
            branches.append(cc.conj([cc.lit(l), body]))
        return cc.disj(branches)  # @line L10


def compile_cnf(cnf) -> tuple[Circuit, int]:
    """Compile a CNF; return the circuit store and the root id."""
    comp = Compiler()
    root = comp.compile(cnf)
    return comp.circuit, root
test_d_dnnf.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/d-dnnf/. The authors are listed in prov/FSRAPA.jsonl.
"""Tests of the d-DNNF compiler and queries against brute force over all assignments."""

import itertools
import random

from d_dnnf import FALSE, TRUE, Circuit, compile_cnf


def assignments(variables):
    variables = sorted(variables)
    for bits in itertools.product([False, True], repeat=len(variables)):
        yield dict(zip(variables, bits))


def cnf_holds(cnf, a) -> bool:
    return all(any(a[abs(l)] == (l > 0) for l in c) for c in cnf)


def brute_count(cnf, n: int) -> int:
    return sum(cnf_holds(cnf, a) for a in assignments(range(1, n + 1)))


def random_cnf(rng: random.Random, n: int, m: int, width: int = 3):
    cnf = []
    for _ in range(m):
        k = rng.randint(1, min(width, n))
        vs = rng.sample(range(1, n + 1), k)
        cnf.append(tuple(v if rng.random() < 0.5 else -v for v in vs))
    return cnf


def cases(seed: int, count: int, max_n: int):
    rng = random.Random(seed)
    for _ in range(count):
        n = rng.randint(1, max_n)
        m = rng.randint(0, 3 * n)
        yield n, random_cnf(rng, n, m)


def complete(a, n):
    """The assignment a extended with False on the variables 1 to n that it misses."""
    return {v: a.get(v, False) for v in range(1, n + 1)}


def test_equivalent_to_cnf():
    for n, cnf in cases(1, 300, 7):
        c, root = compile_cnf(cnf)
        for a in assignments(range(1, n + 1)):
            assert c.evaluate(root, a) == cnf_holds(cnf, a)


def test_model_count_matches_brute_force():
    for n, cnf in cases(2, 400, 10):
        c, root = compile_cnf(cnf)
        assert c.model_count(root, n) == brute_count(cnf, n)


def test_every_and_node_is_decomposable():
    for n, cnf in cases(3, 300, 12):
        c, root = compile_cnf(cnf)
        vs = c.variables(root)
        for u in vs:
            key = c.nodes[u]
            if key[0] == "and":
                for a, b in itertools.combinations(key[1], 2):
                    assert not (vs[a] & vs[b])


def test_every_or_node_is_deterministic():
    """Brute force: no assignment of vars(u) satisfies two children of an or-node u."""
    for n, cnf in cases(4, 200, 7):
        c, root = compile_cnf(cnf)
        vs = c.variables(root)
        for u in vs:
            key = c.nodes[u]
            if key[0] != "or":
                continue
            for a in assignments(vs[u]):
                assert sum(c.evaluate(ch, a) for ch in key[1]) <= 1


def test_every_or_node_is_a_decision_node():
    for n, cnf in cases(5, 200, 10):
        c, root = compile_cnf(cnf)
        for u in c.reachable(root):
            key = c.nodes[u]
            if key[0] != "or":
                continue
            assert len(key[1]) == 2
            heads = []
            for ch in key[1]:
                k = c.nodes[ch]
                lits = [k[1]] if k[0] == "lit" else [c.nodes[g][1] for g in k[1] if c.nodes[g][0] == "lit"]
                heads.append(set(lits))
            assert any(-l in heads[1] for l in heads[0])


def test_smoothing_keeps_models_and_properties():
    for n, cnf in cases(6, 200, 7):
        c, root = compile_cnf(cnf)
        s = c.smooth(root, range(1, n + 1))
        assert c.is_smooth(s)
        vs = c.variables(s)
        if s not in (FALSE, TRUE):
            assert vs[s] == frozenset(range(1, n + 1))
        for a in assignments(range(1, n + 1)):
            assert c.evaluate(s, a) == c.evaluate(root, a)
        for u in vs:
            key = c.nodes[u]
            if key[0] == "and":
                for x, y in itertools.combinations(key[1], 2):
                    assert not (vs[x] & vs[y])
            if key[0] == "or":
                for a in assignments(vs[u]):
                    assert sum(c.evaluate(ch, a) for ch in key[1]) <= 1


def test_consistency_matches_brute_force():
    for n, cnf in cases(7, 400, 9):
        c, root = compile_cnf(cnf)
        assert c.consistent(root) == (brute_count(cnf, n) > 0)


def test_clause_entailment_matches_brute_force():
    rng = random.Random(8)
    for n, cnf in cases(9, 200, 8):
        c, root = compile_cnf(cnf)
        for _ in range(10):
            clause = random_cnf(rng, n, 1)[0]
            expect = all(any(a[abs(l)] == (l > 0) for l in clause) for a in assignments(range(1, n + 1)) if cnf_holds(cnf, a))
            assert c.entails_clause(root, clause) == expect


def test_conditioning_is_restriction():
    rng = random.Random(10)
    for n, cnf in cases(11, 150, 7):
        c, root = compile_cnf(cnf)
        k = rng.randint(1, n)
        term = {v if rng.random() < 0.5 else -v for v in rng.sample(range(1, n + 1), k)}
        cond = c.condition(root, term)
        for a in assignments(range(1, n + 1)):
            b = dict(a)
            for l in term:
                b[abs(l)] = l > 0
            assert c.evaluate(cond, complete(a, n)) == c.evaluate(root, b)


def test_worked_example():
    cnf = [(1, 2), (-1, 3), (4, 5), (-4, -5)]
    c, root = compile_cnf(cnf)
    assert c.model_count(root, 5) == brute_count(cnf, 5) == 8
    assert c.entails_clause(root, (2, 3))
    assert not c.entails_clause(root, (2,))


def test_constants():
    c = Circuit()
    assert c.model_count(TRUE, 3) == 8
    assert c.model_count(FALSE, 3) == 0
    c, root = compile_cnf([(1,), (-1,)])
    assert root == FALSE
    c, root = compile_cnf([])
    assert root == TRUE

History

Darwiche published the full account of DNNF, with a compiler and the treewidth bound, in the Journal of the ACM in 2001. In a 2001 paper on tractable model counting he added determinism, showed that counting is linear on smooth d-DNNF, and applied it to truth maintenance and belief revision. The compiler c2d (Darwiche 2002) builds d-DNNF from CNF. Darwiche and Marquis (2002) placed d-DNNF in the knowledge compilation map, with the succinctness relations and the polynomial queries and transformations. Huang and Darwiche (2007) showed that the trace of exhaustive DPLL with component decomposition is a decision-DNNF.

References

  1. Adnan Darwiche and Pierre Marquis, A knowledge compilation map, Journal of Artificial Intelligence Research 17, 2002, Section 2 (decomposability, determinism, smoothness and the language d-DNNF), Table 5 on page 239 (queries), Table 7 on page 242 (transformations), Appendix A, Lemma A.1 (smoothing in polynomial time) and Lemma A.4 (consistency and conditioning give clause entailment)
  2. Adnan Darwiche, On the tractable counting of theory models and its application to truth maintenance and belief revision, Journal of Applied Non-Classical Logics 11(1-2), 2001, pages 11 to 34, deterministic DNNF and model counting in time linear in the size of the circuit (general locator)
  3. Adnan Darwiche, Decomposable negation normal form, Journal of the ACM 48(4), 2001, pages 608 to 647 (DNNF, its linear-time consistency test, and a compiler from CNF to DNNF)
  4. Jinbo Huang and Adnan Darwiche, The language of search, Journal of Artificial Intelligence Research 29, 2007, pages 191 to 219 (the trace of exhaustive DPLL with decomposition is a decision-DNNF, a subset of d-DNNF)
  5. Adnan Darwiche, A compiler for deterministic, decomposable negation normal form, Proceedings of the Eighteenth National Conference on Artificial Intelligence (AAAI), 2002, the c2d compiler from CNF to d-DNNF (general locator)

Where this leads

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.clause_entailment
  • a full proof of time.condition
  • a full proof of time.consistency
  • a full proof of time.count_smooth
  • a full proof of time.smooth
  • a full proof of space.circuit
  • a full proof of space.smoothed_circuit
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)
WritingW4 complete
  • a review of the text: no review record reviews/FSRAPA/text.yaml