Algorithm Search⌘K

Data structureresearch

Sentential decision diagram

Also called SDD.

A canonical circuit for a fixed variable tree that splits a function into prime and sub pairs. It generalizes OBDDs, and its apply is polynomial when the result is not compressed.

Time
O(s t) apply_uncompressedO(s) evaluate · model_count · negate
Space
O(s) sdd
Where
n = the number of variables; s = the size of the first SDD (its number of elements); t = the size of the second SDD
Properties
not concurrentnot externalpersistent
Origin
Adnan Darwiche, 2011

A sentential decision diagram (SDD) is a Boolean circuit that splits a function on a set of variables at a time, where an OBDD splits on one variable at a time. A binary tree over the variables, the vtree, fixes which sets are used. Darwiche (2011) introduced SDDs as a target language for knowledge compilation that keeps the two strengths of OBDDs, a canonical form and an apply operation that combines two diagrams, while it reaches more functions in small size. Every SDD is a d-DNNF; the d-DNNF page covers the general circuit class and its linear-time queries, and this page covers the vtree, the canonical form and apply, which a general d-DNNF does not have.

In plain words

Split the variables into a left group and a right group. Any function can be written as a list of cases: for each case, a condition on the left variables and a function of the right variables that holds in that case. The conditions never overlap and together cover everything, so exactly one case applies. Do the same split again inside each condition and each right-hand function, using a fixed tree that says how to split each group. If you also merge cases with the same right-hand function, and store each piece once, every function gets exactly one diagram for a given tree. So two diagrams mean the same thing exactly when they are the same object. To combine two diagrams with "and" or "or", pair up their cases and combine the parts.

The abstract type

A vtree over the variables XX is a full binary tree whose leaves are in one-to-one correspondence with XX. For an inner node vv, vlv^l and vrv^r are its left and right children, and vars(v)\mathrm{vars}(v) is the set of variables at the leaves below vv.

For a function ff and a split of its variables into XX and YY, an XX-partition of ff (Darwiche 2011, Definition 1) is a set {(p1,s1),…,(pk,sk)}\{(p_1, s_1), \ldots, (p_k, s_k)\} of elements with primes pip_i over XX and subs sis_i over YY such that

f=(p1∧s1)∨⋯∨(pk∧sk),f = (p_1 \wedge s_1) \vee \cdots \vee (p_k \wedge s_k),

each prime is satisfiable, the primes are pairwise inconsistent, and p1∨⋯∨pk≡truep_1 \vee \cdots \vee p_k \equiv \mathit{true}. The partition is compressed if the subs are distinct. Each function has exactly one compressed XX-partition (Theorem 3): the subs are the distinct functions f∣xf|x over the assignments xx to XX, and the prime of a sub ss is the set of xx with f∣x=sf|x = s.

An SDD that respects the vtree node vv (Definitions 4 and 5) is true\mathit{true}, false\mathit{false}, a literal of the variable at a leaf vv, or a decomposition at an inner node vv: a set of elements (pi,si)(p_i, s_i) where the pip_i are SDDs that respect nodes in the subtree of vlv^l, the sis_i are SDDs that respect nodes in the subtree of vrv^r, and the functions of the pip_i form a vars(vl)\mathrm{vars}(v^l)-partition. An SDD is compressed if every decomposition has distinct subs, and trimmed if no decomposition has the form {(true,α)}\{(\mathit{true}, \alpha)\} or {(α,true),(¬α,false)}\{(\alpha, \mathit{true}), (\neg\alpha, \mathit{false})\} (Definitions 6 and 8). For a fixed vtree, two equivalent compressed and trimmed SDDs are equal (Theorem 10).

Read as a circuit, a decomposition is an or-node over and-nodes pi∧sip_i \wedge s_i. The and-nodes are decomposable, because pip_i and sis_i use the disjoint sets vars(vl)\mathrm{vars}(v^l) and vars(vr)\mathrm{vars}(v^r), and the or-node is deterministic, because the primes are pairwise inconsistent. So an SDD is a d-DNNF in which the vtree fixes how each and-node splits the variables.

The operations are APPLY with ∧\wedge or ∨\vee, NEGATE, COUNT (the model count) and the equivalence test, which is a comparison of two node ids.

Representation

A manager holds one vtree and every node built for it. Node 0 is false\mathit{false} and node 1 is true\mathit{true}. A literal node stores the literal, and a decomposition node stores its vtree node vv and the sorted tuple of its elements as pairs of node ids. Each node also records the vtree node it respects, written vt(u)\mathrm{vt}(u). A unique table maps each key to one id (hash-consing), so by canonicity two ids are equal if and only if their functions are equal. Each vtree node stores its parent, its depth and the interval of its leaves in left-to-right order. The interval gives the test "is aa in the subtree of vv" in constant time, and the depth gives the lowest common ancestor by walking up. APPLY keeps a cache keyed by the operator and the two ids, and NEGATE keeps a cache by id. The size of an SDD is the total number of elements in its decompositions.

Operations

APPLY combines two SDDs for the same vtree. It brings both to the lowest common ancestor vv of the vtree nodes they respect and multiplies their partitions.

  1. APPLY(α, β, ∘) ▷ ∘ is ∧ or ∨; returns a compressed, trimmed SDD
  2. 1if α or β is a constant, or α = β, then return the result by the rules of ∘
  3. 2if (∘, α, β) is in the cache then return it
  4. 3if α and β are the two literals of one variable then r ← false if ∘ = ∧, else true
  5. 4else v ← the lowest common ancestor of vt(α) and vt(β)
  6. 5E ← ∅
  7. 6for each (p, s) in ELEMENTS(α, v) do
  8. 7for each (q, t) in ELEMENTS(β, v) do
  9. 8pq ← APPLY(p, q, ∧)
  10. 9if pq ≠ false then add (pq, APPLY(s, t, ∘)) to E
  11. 10r ← UNIQUE(v, E)
  12. 11store r in the cache; return r

ELEMENTS writes a node as a partition at an ancestor, and UNIQUE makes the result compressed and trimmed and looks it up.

  1. ELEMENTS(u, v) ▷ vt(u) is in the subtree of v
  2. 1if vt(u) = v then return the elements of u
  3. 2if vt(u) is in the subtree of v^l then return {(u, true), (NEGATE(u), false)}
  4. 3return {(true, u)}
  5. UNIQUE(v, E) ▷ E is a partition at v
  6. 4merge the elements with equal subs: (p, s) and (p', s) become (APPLY(p, p', ∨), s)
  7. 5if one element (true, s) is left then return s
  8. 6if the elements are (a, true) and (b, false) then return a
  9. 7return the node for (v, E) from the unique table, made if it is new
  10. NEGATE(u) ▷ constants swap
  11. 8if u is a literal then return the opposite literal
  12. 9return UNIQUE(vt(u), {(p, NEGATE(s)) : (p, s) ∈ u})
  13. COUNT(u, w) ▷ models of u over vars(w); vt(u) is in the subtree of w
  14. 10if u = false then return 0; if u = true then return 2^|vars(w)|
  15. 11c ← 1 if u is a literal, else the sum over (p, s) ∈ u of COUNT(p, v^l) · COUNT(s, v^r), with v = vt(u)
  16. 12return c · 2^(|vars(w)| - |vars(vt(u))|)

To build the SDD of a formula, start from literals and apply the connectives bottom up. The model count over all variables is COUNT(u,root)(u, \text{root}), with a memo on uu for line L22. Two SDDs for the same vtree are equivalent if and only if they are the same node.

Example

Take f=(x1∧x2)∨(x3∧x4)f = (x_1 \wedge x_2) \vee (x_3 \wedge x_4) and the balanced vtree ((x1,x2),(x3,x4))((x_1, x_2), (x_3, x_4)). At the root the left variables are {x1,x2}\{x_1, x_2\}. The assignments to them give two distinct subfunctions, true\mathit{true} when x1∧x2x_1 \wedge x_2 and x3∧x4x_3 \wedge x_4 otherwise, so the root decomposition is

{(x1∧x2, true), (¬(x1∧x2), x3∧x4)}.\{(x_1 \wedge x_2,\ \mathit{true}),\ (\neg(x_1 \wedge x_2),\ x_3 \wedge x_4)\}.

The primes and the sub are decompositions at the two inner children:

function vtree node elements
x1∧x2x_1 \wedge x_2 (x1,x2)(x_1, x_2) (x1,x2),(¬x1,false)(x_1, x_2), (\neg x_1, \mathit{false})
¬(x1∧x2)\neg(x_1 \wedge x_2) (x1,x2)(x_1, x_2) (x1,¬x2),(¬x1,true)(x_1, \neg x_2), (\neg x_1, \mathit{true})
x3∧x4x_3 \wedge x_4 (x3,x4)(x_3, x_4) (x3,x4),(¬x3,false)(x_3, x_4), (\neg x_3, \mathit{false})

The size is 2+2+2+2=82 + 2 + 2 + 2 = 8. COUNT at the root gives 1⋅4+3⋅1=71 \cdot 4 + 3 \cdot 1 = 7: the prime x1∧x2x_1 \wedge x_2 has 1 model over {x1,x2}\{x_1, x_2\} and the sub true\mathit{true} has 4 over {x3,x4}\{x_3, x_4\}, and the prime ¬(x1∧x2)\neg(x_1 \wedge x_2) has 3 models and the sub x3∧x4x_3 \wedge x_4 has 1. On the right-linear vtree (x1,(x2,(x3,x4)))(x_1, (x_2, (x_3, x_4))) the same function has three decompositions of two elements each, size 6. They are the OBDD nodes for x1x_1, x2x_2 and x3x_3, and the OBDD node for x4x_4 is the literal x4x_4. With the order x1,x3,x2,x4x_1, x_3, x_2, x_4 on a right-linear vtree the size is 8.

The vtree decides the size. For fk=(x1∧y1)∨⋯∨(xk∧yk)f_k = (x_1 \wedge y_1) \vee \cdots \vee (x_k \wedge y_k), the implementation on this page gives these sizes:

kk right-linear, x1,y1,x2,y2,…x_1, y_1, x_2, y_2, \ldots right-linear, x1,…,xk,y1,…,ykx_1, \ldots, x_k, y_1, \ldots, y_k balanced, x1,y1,x2,y2,…x_1, y_1, x_2, y_2, \ldots
1 2 2 2
2 6 8 8
3 10 22 17
4 14 52 22
5 18 114 36

The first column grows linearly and the second exponentially, as for OBDDs with the same orders.

Correctness

The proofs are in the correctness proof. In short:

  • APPLY computes α∘β\alpha \circ \beta. After ELEMENTS, both inputs are partitions at the same node vv. The nonempty products p∧qp \wedge q are pairwise inconsistent and cover all assignments to vars(vl)\mathrm{vars}(v^l), and on an assignment in p∧qp \wedge q the function α∘β\alpha \circ \beta equals s∘ts \circ t. So EE is a partition of α∘β\alpha \circ \beta.
  • UNIQUE keeps the function. Merging two elements with the same sub gives one element whose prime is the union, which keeps the partition. A partition with one element has the prime true\mathit{true}, and a partition with the subs true\mathit{true} and false\mathit{false} is equal to the prime of true\mathit{true}.
  • The result is compressed and trimmed, by lines L15 to L17 and induction on the calls.
  • Canonicity. A compressed and trimmed decomposition depends on a variable on each side of its vtree node, so the node it respects is the lowest common ancestor of the variables the function depends on. Its elements are the unique compressed partition of Theorem 3. By induction the primes and subs are unique, and the unique table returns one id.
  • COUNT. The primes of a decomposition have disjoint model sets, and each model of pi∧sip_i \wedge s_i over vars(v)\mathrm{vars}(v) is a model of pip_i over vars(vl)\mathrm{vars}(v^l) joined with a model of sis_i over vars(vr)\mathrm{vars}(v^r), so the counts multiply and add. Variables of ww outside vars(vt(u))\mathrm{vars}(\mathrm{vt}(u)) are free, which gives the factor of line L23.
Proof: APPLY, NEGATE and COUNT on compressed and trimmed SDDs are correct, and the SDDs are canonicalfull

We use the pseudocode of the page, lines L1 to L23, and a fixed vtree. For an SDD node uu, fuf_u is its function. For a vtree node vv, sub(v)\mathrm{sub}(v) is the set of vtree nodes in the subtree of vv. We say uu is normal if it is a constant, or a literal, or a decomposition at some vv that is compressed and trimmed and whose primes and subs are normal. Every node in the manager is made by literal or by line L18, so it suffices to show that the operations return normal nodes with the right functions.

Lemma 0 (dependence). Let uu be a normal decomposition at vv. Then fuf_u depends on some variable of vars(vl)\mathrm{vars}(v^l) and on some variable of vars(vr)\mathrm{vars}(v^r), and on no variable outside vars(v)\mathrm{vars}(v).

Proof. The last part holds because the primes and subs use only variables below vv. Let X=vars(vl)X = \mathrm{vars}(v^l). For an assignment xx to XX, exactly one prime pip_i holds, and fu∣x=sif_u|x = s_i. If fuf_u did not depend on XX, all fu∣xf_u|x would be equal, so all subs would be equal, and by compression there would be one element (true,s1)(\mathit{true}, s_1), which trimming excludes. If fuf_u did not depend on vars(vr)\mathrm{vars}(v^r), each fu∣xf_u|x would be a constant, so each sub would be true\mathit{true} or false\mathit{false}. By compression and since a partition has at least one element, the elements would be {(p,true)}\{(p, \mathit{true})\}, {(p,false)}\{(p, \mathit{false})\} (both with p=truep = \mathit{true}) or {(p,true),(¬p,false)}\{(p, \mathit{true}), (\neg p, \mathit{false})\}, and trimming excludes all three. □\square

Theorem 1 (canonicity; Darwiche 2011, Theorem 10). If uu and u′u' are normal and fu=fu′f_u = f_{u'}, then u=u′u = u'.

Proof. By induction on the size of the vtree subtree involved. Let f=fu=fu′f = f_u = f_{u'} and let DD be the set of variables that ff depends on. If D=∅D = \emptyset, ff is a constant, and neither a literal nor (by Lemma 0) a decomposition has a constant function, so u=u′u = u' is that constant. If D={x}D = \{x\}, ff is xx or ¬x\neg x, a decomposition depends on at least two variables by Lemma 0, so uu and u′u' are the same literal. Otherwise uu and u′u' are decompositions at vv and v′v'. By Lemma 0, D⊆vars(v)D \subseteq \mathrm{vars}(v) and DD meets both vars(vl)\mathrm{vars}(v^l) and vars(vr)\mathrm{vars}(v^r), so vv is the lowest common ancestor of the leaves of DD. The same holds for v′v', so v=v′v = v'. Let X=vars(vl)X = \mathrm{vars}(v^l). In a compressed partition, the sub of the element whose prime holds at xx is f∣xf|x, so the subs are exactly the distinct functions f∣xf|x and the prime of a sub ss is the set of xx with f∣x=sf|x = s. So uu and u′u' have the same set of (prime function, sub function) pairs. The primes and subs are normal and respect smaller subtrees, so by induction equal functions give equal ids. The keys of uu and u′u' are equal, and the unique table gives one id for one key. □\square

Lemma 2 (ELEMENTS). If uu is normal, not a constant, and vt(u)∈sub(v)\mathrm{vt}(u) \in \mathrm{sub}(v) for an inner node vv, then ELEMENTS(u,v)(u, v) is a vars(vl)\mathrm{vars}(v^l)-partition of fuf_u whose primes are normal and respect nodes in sub(vl)\mathrm{sub}(v^l) or are true\mathit{true}, and whose subs are normal and respect nodes in sub(vr)\mathrm{sub}(v^r) or are constants.

Proof. Line L12 returns the elements of uu, which have these properties by definition. At line L13, fuf_u uses only variables of vlv^l, so fu=(fu∧true)∨(¬fu∧false)f_u = (f_u \wedge \mathit{true}) \vee (\neg f_u \wedge \mathit{false}), and fuf_u and ¬fu\neg f_u are both satisfiable because fuf_u is not constant. NEGATE(u)(u) is normal and respects vt(u)\mathrm{vt}(u) by Lemma 4 below. At line L14, fuf_u uses only variables of vrv^r, and {(true,u)}\{(\mathit{true}, u)\} is a partition. □\square

Lemma 3 (UNIQUE). If EE is a vars(vl)\mathrm{vars}(v^l)-partition of a function gg with normal primes in sub(vl)\mathrm{sub}(v^l) and normal subs in sub(vr)\mathrm{sub}(v^r), then UNIQUE(v,E)(v, E) returns a normal node rr with fr=gf_r = g and vt(r)∈sub(v)\mathrm{vt}(r) \in \mathrm{sub}(v).

Proof. Line L15 replaces two elements (p,s)(p, s) and (p′,s)(p', s) by (p∨p′,s)(p \vee p', s). Since (p∧s)∨(p′∧s)=(p∨p′)∧s(p \wedge s) \vee (p' \wedge s) = (p \vee p') \wedge s, the function is kept. The new prime is satisfiable and inconsistent with the other primes, and the primes still cover all assignments, so EE stays a partition. After the merges the subs are distinct. The primes p∨p′p \vee p' come from APPLY, which is normal and stays in sub(vl)\mathrm{sub}(v^l) by Theorem 5 applied to smaller calls. At line L16, one element left means its prime is true\mathit{true} and g=sg = s, a normal node in sub(vr)\mathrm{sub}(v^r). At line L17, the primes aa and bb partition, so b=¬ab = \neg a and g=(a∧true)∨(¬a∧false)=ag = (a \wedge \mathit{true}) \vee (\neg a \wedge \mathit{false}) = a, a normal node in sub(vl)\mathrm{sub}(v^l). Otherwise the node of line L18 is compressed and not of either trimmed form, so it is normal, and its function is gg. □\square

Lemma 4 (NEGATE). If uu is normal, NEGATE(u)(u) is normal, has the function ¬fu\neg f_u, and respects vt(u)\mathrm{vt}(u) when uu is not constant.

Proof. By induction on uu. Constants swap and line L19 is clear. At line L20, ¬fu=⋁i(pi∧¬si)\neg f_u = \bigvee_i (p_i \wedge \neg s_i), because exactly one prime holds at each assignment. The primes are unchanged, so {(pi,NEGATE(si))}\{(p_i, \mathrm{NEGATE}(s_i))\} is a partition. The negated subs are distinct because negation is a bijection, so line L15 merges nothing. The set of subs equals {true,false}\{\mathit{true}, \mathit{false}\} only if the original set did, and a single element would need a single original element, which trimming excludes. So line L18 returns a decomposition at vt(u)\mathrm{vt}(u). □\square

Theorem 5 (APPLY). If α\alpha and β\beta are normal, APPLY(α,β,∘)(\alpha, \beta, \circ) returns a normal node rr with fr=fα∘fβf_r = f_\alpha \circ f_\beta, and rr is a constant or vt(r)\mathrm{vt}(r) is in the subtree of the lowest common ancestor of vt(α)\mathrm{vt}(\alpha) and vt(β)\mathrm{vt}(\beta).

Proof. By induction on the calls, which terminate because each recursive call at lines L8, L9 and L15 is on nodes that respect proper subtrees of vv or on constants. Line L1: false∧g=false\mathit{false} \wedge g = \mathit{false}, true∧g=g\mathit{true} \wedge g = g, g∧g=gg \wedge g = g, and the duals for ∨\vee; the returned node is one of the inputs or a constant. Line L2 returns a result computed earlier for the same input. Line L3: if vt(α)=vt(β)\mathrm{vt}(\alpha) = \mathrm{vt}(\beta) is a leaf and α≠β\alpha \ne \beta, the two nodes are xx and ¬x\neg x, and x∧¬x=falsex \wedge \neg x = \mathit{false}, x∨¬x=truex \vee \neg x = \mathit{true}. Otherwise vv at line L4 is an inner node, because two nodes that respect one leaf are literals of one variable. By Lemma 2, ELEMENTS gives partitions {(pi,si)}\{(p_i, s_i)\} of fαf_\alpha and {(qj,tj)}\{(q_j, t_j)\} of fβf_\beta over X=vars(vl)X = \mathrm{vars}(v^l). For an assignment xx to XX, exactly one pip_i and one qjq_j hold, so exactly one product pi∧qjp_i \wedge q_j holds, and there (fα∘fβ)∣x=si∘tj(f_\alpha \circ f_\beta)|x = s_i \circ t_j. Hence the products that are not false\mathit{false} (line L9) are satisfiable, pairwise inconsistent, cover all of XX, and

fα∘fβ=⋁i,j(pi∧qj)∧(si∘tj).f_\alpha \circ f_\beta = \bigvee_{i,j} (p_i \wedge q_j) \wedge (s_i \circ t_j).

By induction, pi∧qjp_i \wedge q_j is normal in sub(vl)\mathrm{sub}(v^l) or a constant, and si∘tjs_i \circ t_j is normal in sub(vr)\mathrm{sub}(v^r) or a constant; a prime of true\mathit{true} arises only when both pip_i and qjq_j are true\mathit{true}, which is a partition of one element. So EE satisfies the condition of Lemma 3, and line L10 gives the claim. □\square

Lemma 6 (COUNT). For a normal node uu and a vtree node ww with uu constant or vt(u)∈sub(w)\mathrm{vt}(u) \in \mathrm{sub}(w), COUNT(u,w)(u, w) is the number of assignments to vars(w)\mathrm{vars}(w) that satisfy fuf_u.

Proof. Line L21 is clear. Let cc be the value of line L22; we show it is the number of models of fuf_u over vars(vt(u))\mathrm{vars}(\mathrm{vt}(u)). A literal has one model over its variable. For a decomposition at vv with elements (pi,si)(p_i, s_i), an assignment to vars(v)\mathrm{vars}(v) is a pair (x,y)(x, y) of assignments to vars(vl)\mathrm{vars}(v^l) and vars(vr)\mathrm{vars}(v^r). It satisfies fuf_u if and only if it satisfies pi∧sip_i \wedge s_i for the unique ii with x⊨pix \models p_i, that is, x⊨pix \models p_i and y⊨siy \models s_i. The sets of such pairs for different ii are disjoint, so the count is ∑i#pi⋅#si\sum_i \#p_i \cdot \#s_i with each count over the variables of vlv^l and vrv^r, which is what line L22 computes by induction (the primes respect nodes in sub(vl)\mathrm{sub}(v^l) and the subs nodes in sub(vr)\mathrm{sub}(v^r)). Finally fuf_u does not use the variables of vars(w)∖vars(vt(u))\mathrm{vars}(w) \setminus \mathrm{vars}(\mathrm{vt}(u)), so each model over vars(vt(u))\mathrm{vars}(\mathrm{vt}(u)) extends in 2∣vars(w)∣−∣vars(vt(u))∣2^{|\mathrm{vars}(w)| - |\mathrm{vars}(\mathrm{vt}(u))|} ways, which is line L23. □\square

Corollary 7 (equivalence). Two nodes of one manager have equal functions if and only if their ids are equal: every node is normal by Theorem 5 and Lemmas 3 and 4, and Theorem 1 applies. □\square

Complexity

operation time
APPLY without lines L15 to L17 O(st)O(s t) (Darwiche 2011, Algorithm 1)
APPLY with compression exponential in the worst case (Van den Broeck and Darwiche 2015)
NEGATE O(s)O(s) expected
COUNT O(s)O(s) additions and multiplications of numbers of at most nn bits
equivalence O(1)O(1)

Without compression, each pair of elements makes at most one recursive pair of calls, and the cache gives each pair of nodes one call, which bounds the work by the product of the sizes. Compression calls APPLY with ∨\vee on primes inside UNIQUE, and Van den Broeck and Darwiche (2015) give functions for which this makes the result, and the time, exponential in the input sizes. The implementation on this page compresses, so it pays this cost when it occurs. NEGATE does no merging, because the negated subs are still distinct and are never exactly {true,false}\{\mathit{true}, \mathit{false}\} unless the original subs were, which trimming excludes.

As a d-DNNF, an SDD supports in polynomial time all the queries that Darwiche and Marquis (2002, Table 5) list for d-DNNF, including consistency, validity, clause entailment, model counting and model enumeration. Canonicity adds the equivalence test. Darwiche (2011, Theorems 12 and 13) shows that a CNF with nn variables and treewidth ww has an SDD of size O(n2w)O(n 2^w), while the corresponding OBDD bound uses the pathwidth in place of the treewidth. Bova (2016) gives functions with SDDs of polynomial size whose OBDDs all have exponential size.

Variants

  • OBDD. On a right-linear vtree, where every left child is a leaf, every prime is a literal or a constant, and the SDD is the reduced OBDD for the left-to-right order of the leaves (Darwiche 2011, Section 6). APPLY then works like OBDD apply.
  • Uncompressed SDDs. Dropping line L15 gives polynomial APPLY at the cost of canonicity (Van den Broeck and Darwiche 2015).
  • Weighted counting. Replace the 1 of a literal at line L22 by its weight and the power of 2 at lines L21 and L23 by the product of the sums of the weights of the free variables. With weights from a Bayesian network this gives probabilities.

When to use it

Use an SDD when a knowledge base is built up incrementally by conjunction and disjunction, as with an OBDD, and an OBDD for every variable order is too large. Choose the vtree from the structure of the problem: a vtree that follows a tree decomposition of a CNF gives the treewidth bound above. When the knowledge base is fixed and only needs counting or entailment queries, a d-DNNF compiled by search can be smaller, because it does not have to follow one vtree.

Pitfalls

  • Mixing vtrees. APPLY and the equivalence test are defined only for two SDDs of one manager. The same function has different SDDs on different vtrees.
  • Normalizing at the wrong node. The result of APPLY must be trimmed. If a decomposition {(true,s)}\{(\mathit{true}, s)\} is kept, the same function has two ids, and the equivalence test by id fails.
  • Counting over the wrong variables. A node that respects vv counts models over vars(v)\mathrm{vars}(v) only. A sub true\mathit{true}, or a node that respects a lower vtree node, needs the factor of line L23.
  • Primes that are not exclusive. Building a decomposition by hand from overlapping conditions gives a circuit that is not deterministic, and COUNT then overcounts.

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.

sentential_decision_diagram.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sentential-decision-diagram/. The authors are listed in prov/YVT6ET.jsonl.
"""Compressed and trimmed sentential decision diagrams (SDDs) for a fixed vtree.

The variables are the integers 1 to n, and a literal is v or -v.

A vtree is a full binary tree whose leaves are the variables, in a fixed
left to right order. It is given as a nested structure: an int is a leaf
and a pair (left, right) is an inner node. right_linear, balanced and
random_vtree build the usual shapes.

An SDD node of the manager is one of

    0                              FALSE
    1                              TRUE
    ("lit", l)                     a literal, at the leaf of its variable
    ("dec", v, ((p1, s1), ...))    a decomposition at the inner vtree node v

In a decomposition the primes p_i are SDDs for the variables of the left
subtree of v, and the subs s_i for the right subtree. The primes are
consistent, pairwise exclusive and their disjunction is TRUE, and the node
means (p1 and s1) or (p2 and s2) or ... . Every node that the manager makes
is compressed (the subs of one decomposition are distinct) and trimmed (no
decomposition {(TRUE, a)} and no decomposition {(a, TRUE), (not a, FALSE)}).
A unique table maps each node to one id, so for a fixed vtree two
equivalent SDDs get the same id (Darwiche 2011, Theorem 10).
"""

from __future__ import annotations

import random

FALSE, TRUE = 0, 1
AND, OR = "and", "or"


class Vtree:
    """A vtree with integer node ids; leaves carry a variable."""

    def __init__(self, shape) -> None:
        self.left: list[int | None] = []
        self.right: list[int | None] = []
        self.var: list[int | None] = []
        self.parent: list[int | None] = []
        self.depth: list[int] = []
        self.lo: list[int] = []
        self.hi: list[int] = []
        self.vars: list[frozenset[int]] = []
        self.leaf_of: dict[int, int] = {}
        self._leaves = 0
        self.root = self._build(shape, None, 0)

    def _build(self, shape, parent, depth) -> int:
        u = len(self.var)
        self.left.append(None)
        self.right.append(None)
        self.var.append(None)
        self.parent.append(parent)
        self.depth.append(depth)
        self.lo.append(0)
        self.hi.append(0)
        self.vars.append(frozenset())
        if isinstance(shape, int):
            self.var[u] = shape
            self.leaf_of[shape] = u
            self.lo[u] = self.hi[u] = self._leaves
            self._leaves += 1
            self.vars[u] = frozenset([shape])
        else:
            a = self._build(shape[0], u, depth + 1)
            b = self._build(shape[1], u, depth + 1)
            self.left[u], self.right[u] = a, b
            self.lo[u], self.hi[u] = self.lo[a], self.hi[b]
            self.vars[u] = self.vars[a] | self.vars[b]
        return u

    def is_leaf(self, u: int) -> bool:
        return self.var[u] is not None

    def inside(self, a: int, v: int) -> bool:
        """Is vtree node a in the subtree of v?"""
        return self.lo[v] <= self.lo[a] and self.hi[a] <= self.hi[v]

    def lca(self, a: int, b: int) -> int:
        while self.depth[a] > self.depth[b]:
            a = self.parent[a]
        while self.depth[b] > self.depth[a]:
            b = self.parent[b]
        while a != b:
            a, b = self.parent[a], self.parent[b]
        return a


def right_linear(order):
    """The vtree (x1, (x2, (... , xn))): each left child is a leaf."""
    shape = order[-1]
    for v in reversed(order[:-1]):
        shape = (v, shape)
    return Vtree(shape)


def balanced(order):
    def build(vs):
        if len(vs) == 1:
            return vs[0]
        h = len(vs) // 2
        return (build(vs[:h]), build(vs[h:]))

    return Vtree(build(list(order)))


def random_vtree(order, rng: random.Random):
    def build(vs):
        if len(vs) == 1:
            return vs[0]
        h = rng.randint(1, len(vs) - 1)
        return (build(vs[:h]), build(vs[h:]))

    return Vtree(build(list(order)))


class SddManager:
    def __init__(self, vtree: Vtree) -> None:
        self.vtree = vtree
        self.nodes: list = [("false",), ("true",)]
        self.vt: list[int | None] = [None, None]
        self.unique: dict[tuple, int] = {}
        self.apply_cache: dict[tuple, int] = {}
        self.neg_cache: dict[int, int] = {FALSE: TRUE, TRUE: FALSE}

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

    def literal(self, l: int) -> int:
        return self._make(("lit", l), self.vtree.leaf_of[abs(l)])

    def _decomposition(self, v: int, elements) -> int:
        """Compress, trim and look up a decomposition at vtree node v."""
        by_sub: dict[int, int] = {}
        for p, s in elements:
            if p == FALSE:
                continue
            by_sub[s] = self.apply(by_sub[s], p, OR) if s in by_sub else p  # @line L15
        if len(by_sub) == 1:  # @line L16
            ((s, p),) = by_sub.items()
            return s  # {(TRUE, s)} trims to s
        if len(by_sub) == 2 and set(by_sub) == {TRUE, FALSE}:  # @line L17
            return by_sub[TRUE]  # {(a, TRUE), (not a, FALSE)} trims to a
        elems = tuple(sorted((p, s) for s, p in by_sub.items()))
        return self._make(("dec", v, elems), v)  # @line L18

    def negate(self, u: int) -> int:
        r = self.neg_cache.get(u)
        if r is not None:
            return r
        key = self.nodes[u]
        if key[0] == "lit":  # @line L19
            r = self.literal(-key[1])
        else:
            r = self._decomposition(key[1], [(p, self.negate(s)) for p, s in key[2]])  # @line L20
        self.neg_cache[u] = r
        self.neg_cache[r] = u
        return r

    def _elements_at(self, u: int, v: int):
        """The node u written as a partition at the inner vtree node v above or at vt(u)."""
        if self.vt[u] == v:  # @line L12
            return self.nodes[u][2]
        if self.vtree.inside(self.vt[u], self.vtree.left[v]):  # @line L13
            return ((u, TRUE), (self.negate(u), FALSE))
        return ((TRUE, u),)  # @line L14

    def apply(self, a: int, b: int, op: str) -> int:
        if op == AND:  # @line L1
            if a == FALSE or b == FALSE:
                return FALSE
            if a == TRUE:
                return b
            if b == TRUE:
                return a
        else:
            if a == TRUE or b == TRUE:
                return TRUE
            if a == FALSE:
                return b
            if b == FALSE:
                return a
        if a == b:
            return a
        if a > b:
            a, b = b, a
        key = (op, a, b)
        r = self.apply_cache.get(key)
        if r is not None:  # @line L2
            return r
        va, vb = self.vt[a], self.vt[b]
        if va == vb and self.vtree.is_leaf(va):  # @line L3
            # Two different literals of one variable: x and not x.
            r = FALSE if op == AND else TRUE
        else:
            v = self.vtree.lca(va, vb)  # @line L4
            elements = []  # @line L5
            for p, s in self._elements_at(a, v):  # @line L6
                for q, t in self._elements_at(b, v):  # @line L7
                    pq = self.apply(p, q, AND)  # @line L8
                    if pq != FALSE:  # @line L9
                        elements.append((pq, self.apply(s, t, op)))
            r = self._decomposition(v, elements)  # @line L10
        self.apply_cache[key] = r  # @line L11
        return r

    def conjoin(self, a: int, b: int) -> int:
        return self.apply(a, b, AND)

    def disjoin(self, a: int, b: int) -> int:
        return self.apply(a, b, OR)

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

    def evaluate(self, u: int, assignment: dict[int, bool]) -> bool:
        while True:
            if u in (FALSE, TRUE):
                return u == TRUE
            key = self.nodes[u]
            if key[0] == "lit":
                return assignment[abs(key[1])] == (key[1] > 0)
            u = next(s for p, s in key[2] if self.evaluate(p, assignment))

    def _count_over(self, u: int, w: int, memo: dict) -> int:
        """The number of models of u over the variables of vtree node w (vt(u) is inside w)."""
        width = len(self.vtree.vars[w])
        if u == FALSE:  # @line L21
            return 0
        if u == TRUE:
            return 1 << width
        return self._count(u, memo) << (width - len(self.vtree.vars[self.vt[u]]))  # @line L23

    def _count(self, u: int, memo: dict) -> int:
        if u in memo:
            return memo[u]
        key = self.nodes[u]
        if key[0] == "lit":
            r = 1
        else:
            v = key[1]
            left, right = self.vtree.left[v], self.vtree.right[v]
            r = sum(self._count_over(p, left, memo) * self._count_over(s, right, memo) for p, s in key[2])  # @line L22
        memo[u] = r
        return r

    def model_count(self, u: int) -> int:
        """The number of models of u over all the variables of the vtree."""
        return self._count_over(u, self.vtree.root, {})

    def reachable(self, u: int) -> set[int]:
        seen = set()
        stack = [u]
        while stack:
            x = stack.pop()
            if x in seen:
                continue
            seen.add(x)
            key = self.nodes[x]
            if key[0] == "dec":
                for p, s in key[2]:
                    stack.append(p)
                    stack.append(s)
        return seen

    def size(self, u: int) -> int:
        """The sum of the number of elements over the decompositions below u."""
        return sum(len(self.nodes[x][2]) for x in self.reachable(u) if self.nodes[x][0] == "dec")
test_sentential_decision_diagram.py 222 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sentential-decision-diagram/. The authors are listed in prov/YVT6ET.jsonl.
"""Tests of the SDD package against truth tables on at most 6 variables."""

import random

from sentential_decision_diagram import (
    AND,
    FALSE,
    OR,
    TRUE,
    SddManager,
    balanced,
    random_vtree,
    right_linear,
)


def table_of(mgr: SddManager, u: int, n: int) -> tuple:
    out = []
    for a in range(1 << n):
        asg = {v: bool((a >> (v - 1)) & 1) for v in range(1, n + 1)}
        out.append(mgr.evaluate(u, asg))
    return tuple(out)


def random_formula(rng: random.Random, n: int, depth: int):
    if depth == 0 or rng.random() < 0.2:
        v = rng.randint(1, n)
        return ("lit", v if rng.random() < 0.5 else -v)
    op = rng.choice(["and", "or", "not"])
    if op == "not":
        return ("not", random_formula(rng, n, depth - 1))
    return (op, random_formula(rng, n, depth - 1), random_formula(rng, n, depth - 1))


def formula_table(f, n: int) -> tuple:
    def ev(f, a):
        if f[0] == "lit":
            l = f[1]
            return bool((a >> (abs(l) - 1)) & 1) == (l > 0)
        if f[0] == "not":
            return not ev(f[1], a)
        if f[0] == "and":
            return ev(f[1], a) and ev(f[2], a)
        return ev(f[1], a) or ev(f[2], a)

    return tuple(ev(f, a) for a in range(1 << n))


def build(mgr: SddManager, f) -> int:
    if f[0] == "lit":
        return mgr.literal(f[1])
    if f[0] == "not":
        return mgr.negate(build(mgr, f[1]))
    a, b = build(mgr, f[1]), build(mgr, f[2])
    return mgr.apply(a, b, AND if f[0] == "and" else OR)


def vtrees(rng: random.Random, n: int):
    order = list(range(1, n + 1))
    rng.shuffle(order)
    return [right_linear(order), balanced(order), random_vtree(order, rng)]


def from_table(mgr: SddManager, table: tuple, n: int, rng: random.Random) -> int:
    """The DNF of the models, built term by term in a random order."""
    models = [a for a in range(1 << n) if table[a]]
    rng.shuffle(models)
    u = FALSE
    for a in models:
        lits = [v if (a >> (v - 1)) & 1 else -v for v in range(1, n + 1)]
        rng.shuffle(lits)
        t = TRUE
        for l in lits:
            t = mgr.conjoin(t, mgr.literal(l))
        u = mgr.disjoin(u, t)
    return u


def from_cnf_table(mgr: SddManager, table: tuple, n: int, rng: random.Random) -> int:
    """The CNF of the non-models, built clause by clause in a random order."""
    rows = [a for a in range(1 << n) if not table[a]]
    rng.shuffle(rows)
    u = TRUE
    for a in rows:
        lits = [-v if (a >> (v - 1)) & 1 else v for v in range(1, n + 1)]
        rng.shuffle(lits)
        c = FALSE
        for l in lits:
            c = mgr.disjoin(c, mgr.literal(l))
        u = mgr.conjoin(u, c)
    return u


def check_invariants(mgr: SddManager, u: int) -> None:
    vt = mgr.vtree
    for x in mgr.reachable(u):
        key = mgr.nodes[x]
        if key[0] != "dec":
            continue
        v = key[1]
        primes = [p for p, s in key[2]]
        subs = [s for p, s in key[2]]
        assert len(set(subs)) == len(subs)  # compressed
        assert not (len(key[2]) == 1)  # trimmed: no {(TRUE, a)}
        assert set(subs) != {TRUE, FALSE}  # trimmed: no {(a, TRUE), (not a, FALSE)}
        for p in primes:
            assert p != FALSE
            assert p == TRUE or vt.inside(mgr.vt[p], vt.left[v])
        for s in subs:
            assert s in (TRUE, FALSE) or vt.inside(mgr.vt[s], vt.right[v])
        # the primes form a partition
        acc = FALSE
        for i, p in enumerate(primes):
            for q in primes[i + 1 :]:
                assert mgr.conjoin(p, q) == FALSE
            acc = mgr.disjoin(acc, p)
        assert acc == TRUE


def test_apply_matches_truth_tables():
    rng = random.Random(1)
    for _ in range(120):
        n = rng.randint(1, 6)
        for vt in vtrees(rng, n):
            mgr = SddManager(vt)
            f = random_formula(rng, n, 5)
            g = random_formula(rng, n, 5)
            a, b = build(mgr, f), build(mgr, g)
            ta, tb = formula_table(f, n), formula_table(g, n)
            assert table_of(mgr, a, n) == ta
            assert table_of(mgr, mgr.conjoin(a, b), n) == tuple(x and y for x, y in zip(ta, tb))
            assert table_of(mgr, mgr.disjoin(a, b), n) == tuple(x or y for x, y in zip(ta, tb))
            assert table_of(mgr, mgr.negate(a), n) == tuple(not x for x in ta)
            check_invariants(mgr, mgr.conjoin(a, b))
            check_invariants(mgr, mgr.disjoin(a, b))


def test_canonical_for_a_fixed_vtree():
    rng = random.Random(2)
    for _ in range(80):
        n = rng.randint(1, 5)
        for vt in vtrees(rng, n):
            mgr = SddManager(vt)
            f = random_formula(rng, n, 5)
            t = formula_table(f, n)
            a = build(mgr, f)
            b = from_table(mgr, t, n, rng)
            c = from_cnf_table(mgr, t, n, rng)
            assert a == b == c
            assert mgr.negate(mgr.negate(a)) == a


def test_model_count_matches_brute_force():
    rng = random.Random(3)
    for _ in range(150):
        n = rng.randint(1, 6)
        for vt in vtrees(rng, n):
            mgr = SddManager(vt)
            f = random_formula(rng, n, 6)
            assert mgr.model_count(build(mgr, f)) == sum(formula_table(f, n))
    mgr = SddManager(balanced([1, 2, 3]))
    assert mgr.model_count(TRUE) == 8 and mgr.model_count(FALSE) == 0


def obdd_node_count(table: tuple, order: list[int], n: int) -> int:
    """The nodes of the reduced OBDD for the order: distinct non-constant subfunctions."""
    seen = set()
    for i in range(len(order) + 1):
        fixed = order[:i]
        for bits in range(1 << i):
            sub = []
            for a in range(1 << n):
                b = a
                for j, v in enumerate(fixed):
                    b = (b & ~(1 << (v - 1))) | (((bits >> j) & 1) << (v - 1))
                sub.append(table[b])
            sub = tuple(sub)
            if len(set(sub)) == 2:
                seen.add(sub)
    return len(seen)


def test_right_linear_vtree_gives_the_obdd():
    """On a right-linear vtree each node reached through subs is one node of the reduced OBDD."""
    rng = random.Random(4)
    for _ in range(100):
        n = rng.randint(1, 5)
        order = list(range(1, n + 1))
        rng.shuffle(order)
        mgr = SddManager(right_linear(order))
        f = random_formula(rng, n, 5)
        u = build(mgr, f)
        via_subs = set()
        stack = [u]
        while stack:
            x = stack.pop()
            if x in (TRUE, FALSE) or x in via_subs:
                continue
            via_subs.add(x)
            if mgr.nodes[x][0] == "dec":
                stack.extend(s for p, s in mgr.nodes[x][2])
        assert len(via_subs) == obdd_node_count(formula_table(f, n), order, n)
        for x in mgr.reachable(u):
            if mgr.nodes[x][0] == "dec":
                assert all(p == TRUE or mgr.nodes[p][0] == "lit" for p, s in mgr.nodes[x][2])


def test_worked_example():
    # f = (x1 and x2) or (x3 and x4) on the balanced vtree ((1, 2), (3, 4)).
    mgr = SddManager(balanced([1, 2, 3, 4]))
    x = {v: mgr.literal(v) for v in range(1, 5)}
    f = mgr.disjoin(mgr.conjoin(x[1], x[2]), mgr.conjoin(x[3], x[4]))
    key = mgr.nodes[f]
    assert key[0] == "dec" and key[1] == mgr.vtree.root
    elems = dict(key[2])
    a12 = mgr.conjoin(x[1], x[2])
    assert elems[a12] == TRUE
    assert elems[mgr.negate(a12)] == mgr.conjoin(x[3], x[4])
    assert mgr.model_count(f) == 7
    assert mgr.size(f) == 8

History

Darwiche introduced SDDs in 2011 with the canonicity theorem, the apply operation and the treewidth bound, and showed that OBDDs are the SDDs on right-linear vtrees. Van den Broeck and Darwiche (2015) showed that apply with compression is not polynomial in the worst case and studied SDDs without compression. Bova (2016) showed that SDDs are exponentially more succinct than OBDDs.

References

  1. Adnan Darwiche, SDD: A new canonical representation of propositional knowledge bases, Proceedings of the Twenty-Second International Joint Conference on Artificial Intelligence (IJCAI), 2011, Definition 1 (X-partition), Theorem 3 (the compressed partition is unique), Definitions 4 and 5 (vtree and SDD), Definitions 6 and 8 (compressed and trimmed), Theorem 10 (canonicity), Algorithm 1 (apply), Section 6 (OBDDs as SDDs on right-linear vtrees), Theorems 12 and 13 (size bounds by treewidth and pathwidth)
  2. Guy Van den Broeck and Adnan Darwiche, On the role of canonicity in knowledge compilation, Proceedings of the Twenty-Ninth AAAI Conference on Artificial Intelligence, 2015, pages 1641 to 1648, apply with compression can take exponential time, and dropping compression keeps apply polynomial (general locator)
  3. Simone Bova, SDDs are exponentially more succinct than OBDDs, Proceedings of the Thirtieth AAAI Conference on Artificial Intelligence, 2016, a family of functions with polynomial SDDs and only exponential OBDDs (general locator)
  4. Adnan Darwiche and Pierre Marquis, A knowledge compilation map, Journal of Artificial Intelligence Research 17, 2002, Table 5 on page 239 (the polynomial queries of d-DNNF and OBDD)

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.apply_uncompressed
  • a full proof of time.evaluate
  • a full proof of time.model_count
  • a full proof of time.negate
  • a full proof of space.sdd
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/YVT6ET/text.yaml