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
- Model
- Word RAM
- Properties
- not concurrentnot externalpersistent
- Evidence
- Proof sketchCode in 1 languages
- 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 is a rooted DAG whose leaves are labelled , , or for , and whose inner nodes are labelled or . Each node denotes a Boolean function in the usual way, and is the set of variables at the leaves below . Following Darwiche and Marquis (2002, Section 2), the circuit is
- decomposable if for each and-node with children , for all ;
- deterministic if for each or-node with children , for all ;
- smooth if for each or-node , for every child .
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 , 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 . 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 , node 1 is , 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 child is , 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 and a literal , removes the clauses that contain and deletes from the others.
COMPILE(Δ) ▷ Δ is a set of clauses; returns a node- 1
if Δ = ∅ then return true - 2
if Δ contains the empty clause then return false - 3
if Δ is in the cache C then return C[Δ] - 4
if Δ has a unit clause {l} then - 5
r ← AND(l, COMPILE(Δ|l)) - 6
else if the clauses of Δ split into groups Δ_1, ..., Δ_k, k ≥ 2, that share no variable then - 7
r ← AND(COMPILE(Δ_1), ..., COMPILE(Δ_k)) - 8
else - 9
x ← a variable with the most occurrences in Δ - 10
r ← OR(AND(x, COMPILE(Δ|x)), AND(¬x, COMPILE(Δ|¬x))) - 11
C[Δ] ← r; return r
The queries walk the circuit once, children first.
CO(N) ▷ N is decomposable- 1
for each node u below N, children first do - 2
if u is a literal or true then c[u] ← 1; if u is false then c[u] ← 0 - 3
if u is an and-node then c[u] ← 1 if c[v] = 1 for every child v, else 0 - 4
if u is an or-node then c[u] ← 1 if c[v] = 1 for some child v, else 0 - 5
return c[N] = 1 CONDITION(N, γ) ▷ γ is a set of literals with no complementary pair- 6
for 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 CE(N, δ) ▷ does N entail the clause δ?- 7
if δ contains a literal and its negation then return true - 8
return not CO(CONDITION(N, {¬l : l ∈ δ})) SMOOTH(N, X) ▷ X ⊇ vars(N)- 9
for each node u below N, children first, rebuild u; if u is an or-node then - 10
replace each child v by AND(v, (y ∨ ¬y) for each y ∈ vars(u) \ vars(v)) - 11
return AND(N', (y ∨ ¬y) for each y ∈ X \ vars(N)) ▷ N' is the rebuilt root CT(N) ▷ N is a smooth d-DNNF with vars(N) = X- 12
for each node u below N, children first: literal 1, true 1, false 0, and-node the product of its children, or-node the sum - 13
return the value at N
Example
Let over .
| call | rule | result |
|---|---|---|
| L6: groups and | AND of the two results | |
| first group | L9: occurs twice | OR of the two branches |
| $\Delta | x_1 = {x_3}$ | L5 |
| $\Delta | \neg x_1 = {x_2}$ | L5 |
| second group | L9: (a tie with , broken by the index) | OR of the two branches |
| and | L5 | and |
The circuit is
with 15 nodes, 14 edges and 2 decisions. SMOOTH adds under and under ; the second or-node is already smooth. CT then gives for each branch of the first or-node, for the first group, for the second, and at the root, which is the number of models of . For CE with , CONDITION with turns both branches of the first or-node into , so the root is and . With , the branch survives, so .
Correctness
The proofs are in the correctness proof. In short:
- COMPILE is equivalent to . Line L5 uses when , line L7 uses that is the conjunction of its groups, and line L10 is the Shannon expansion .
- The output is a decision-DNNF. , so line L5 is decomposable because does not mention the variable of , 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 .
- 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: has two satisfiable children.
- CE. if and only if is unsatisfiable, if and only if 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 over . 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 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 , is its function and is the set of variables at the leaves below . For a set of variables , is the number of assignments to that satisfy . For a clause set , is the set of variables in its clauses, and is defined on the page.
Lemma 0 (constructors). AND returns a node whose function is and whose variables are a subset of ; if the have pairwise disjoint variables and are decomposable, so is the result. OR is the same with ; if the are pairwise contradictory and deterministic, so is the result.
Proof. The constructor either returns (for AND, when a child is ; the conjunction is then false), or removes 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.
The compiler
Lemma 1 (equivalence). COMPILE returns a node with and .
Proof. By induction on , and for equal values on the order of the calls (a cached result was computed earlier for the same , so line L3 is covered by the hypothesis for that earlier call). Line L1: the empty conjunction is . Line L2: a clause set with the empty clause is unsatisfiable. Line L5: if , every model of sets true, and under the clauses with are satisfied and is false in the rest, so . The set does not mention the variable of , so it has fewer variables, and the hypothesis and Lemma 0 give the claim. Line L7: is the conjunction of its groups. Each group is non-empty and the groups have pairwise disjoint, non-empty variable sets, so with each group has fewer variables than . Line L10: the Shannon expansion , where and do not mention .
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 and the node for have disjoint variables, by Lemma 1. At line L7, the node for has variables in , and these sets are pairwise disjoint. At line L10, each and-node joins or with a node whose variables avoid . The or-node has the children and , which no assignment satisfies together. By Lemma 0 the folding of constants keeps both properties.
Lemma 3 (termination). Without the cache, the recursion tree of COMPILE has at most leaves.
Proof. Let be the largest number of leaves for variables. A call that stops at lines L1 to L3 is one leaf, and . Line L5 makes one call with at most variables. Line L7 makes calls on variables with and , and because for . Line L10 makes two calls with at most variables, and . Each call has fewer variables than its caller, so the depth is at most and the recursion stops. The cache returns early at line L3 and only removes subtrees.
The queries
Lemma 4 (CO). If is decomposable, CO returns true if and only if is satisfiable.
Proof. We show if and only if is satisfiable, for each in the order of line L12. Leaves (line L13): a literal and are satisfiable, is not. An or-node (line L15) is satisfiable if and only if some child is. An and-node (line L14) with an unsatisfiable child is unsatisfiable. If every child has a model over , the sets are pairwise disjoint, so the union of the is a well-defined assignment, and it satisfies every child, hence .
Lemma 5 (CONDITION). For a set of literals with no complementary pair, CONDITION returns a node with (the function with the variables of fixed so that is true). If is decomposable or deterministic, so is , and .
Proof. By induction in the order of line L17. A literal becomes , a literal with becomes , and any other literal is kept. Restriction commutes with and , and Lemma 0 gives the function of the rebuilt gate. Variables only disappear, so disjointness is kept. If , then , so determinism is kept.
Lemma 6 (CE). If is decomposable, CE returns true if and only if .
Proof. If contains and , it is valid and line L18 is right. Otherwise is the consistent term . if and only if is unsatisfiable. A model of restricts to a model of , and a model of extends by to a model of , since does not mention . So line L19 is right by Lemmas 4 and 5.
Lemma 7 (SMOOTH). SMOOTH returns a node with , , which is smooth, and which is decomposable (deterministic) when is.
Proof. By induction in the order of line L20, the rebuilt node of has and . For an and-node this follows from the children by Lemma 0. For an or-node , line L21 replaces the rebuilt child by over . Each factor is valid, so the function is , and the variables become exactly , so all children of have the same variables (smooth). The new and-node is decomposable: has the variables , the factors mention distinct variables outside it, and each factor is an or-node of two literals on one variable, which is smooth and deterministic. The functions of the children of are those of , so pairwise contradiction is kept. Line L22 is the same step at the root with in place of .
Lemma 8 (CT). If is a smooth d-DNNF, the value of line L23 is for each node . So CT is the number of models of over .
Proof. By induction in the order of line L23. A literal has one model over its variable; has one model over and none. For an and-node with children and pairwise disjoint , the map is a bijection from the assignments to onto tuples of assignments to the , and satisfies if and only if each satisfies . So . For an or-node , smoothness gives for all , 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 , so . The second sentence follows from Lemma 7, which gives and keeps the function and the two properties.
Cost. Each query visits each node below the root once and does work proportional to its number of children, plus one expected hash lookup in CONDITION and SMOOTH, so CO, CONDITION and CE take expected time for edges. SMOOTH adds at most factors of size for each edge out of an or-node and at the root, so its output has edges with .
Complexity
| operation | time | needs |
|---|---|---|
| CO | decomposability | |
| CONDITION | expected | nothing |
| CE | expected | decomposability |
| SMOOTH | , and the output has edges | decomposability |
| CT | additions and multiplications of numbers of at most bits | smoothness, decomposability, determinism |
| COMPILE | exponential in 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 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 the two children share the model , so after smoothing the sum is , 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 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 the bottom-up sum gives , but the function has 3 models over , because the child does not mention . Smooth first, or multiply each child count by 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 .
- 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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.
| 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 | W4 complete |
|
Tag FSRAPA Edit this page History Report an error Markdown