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
- Model
- Word RAM
- Properties
- not concurrentnot externalpersistent
- Evidence
- Proof sketchCode in 1 languages
- 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 is a full binary tree whose leaves are in one-to-one correspondence with . For an inner node , and are its left and right children, and is the set of variables at the leaves below .
For a function and a split of its variables into and , an -partition of (Darwiche 2011, Definition 1) is a set of elements with primes over and subs over such that
each prime is satisfiable, the primes are pairwise inconsistent, and . The partition is compressed if the subs are distinct. Each function has exactly one compressed -partition (Theorem 3): the subs are the distinct functions over the assignments to , and the prime of a sub is the set of with .
An SDD that respects the vtree node (Definitions 4 and 5) is , , a literal of the variable at a leaf , or a decomposition at an inner node : a set of elements where the are SDDs that respect nodes in the subtree of , the are SDDs that respect nodes in the subtree of , and the functions of the form a -partition. An SDD is compressed if every decomposition has distinct subs, and trimmed if no decomposition has the form or (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 . The and-nodes are decomposable, because and use the disjoint sets and , 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 or , 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 and node 1 is . A literal node stores the literal, and a decomposition node stores its vtree node and the sorted tuple of its elements as pairs of node ids. Each node also records the vtree node it respects, written . 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 in the subtree of " 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 of the vtree nodes they respect and multiplies their partitions.
APPLY(α, β, ∘) ▷ ∘ is ∧ or ∨; returns a compressed, trimmed SDD- 1
if α or β is a constant, or α = β, then return the result by the rules of ∘ - 2
if (∘, α, β) is in the cache then return it - 3
if α and β are the two literals of one variable then r ← false if ∘ = ∧, else true - 4
else v ← the lowest common ancestor of vt(α) and vt(β) - 5
E ← ∅ - 6
for each (p, s) in ELEMENTS(α, v) do - 7
for each (q, t) in ELEMENTS(β, v) do - 8
pq ← APPLY(p, q, ∧) - 9
if pq ≠ false then add (pq, APPLY(s, t, ∘)) to E - 10
r ← UNIQUE(v, E) - 11
store 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.
ELEMENTS(u, v) ▷ vt(u) is in the subtree of v- 1
if vt(u) = v then return the elements of u - 2
if vt(u) is in the subtree of v^l then return {(u, true), (NEGATE(u), false)} - 3
return {(true, u)} UNIQUE(v, E) ▷ E is a partition at v- 4
merge the elements with equal subs: (p, s) and (p', s) become (APPLY(p, p', ∨), s) - 5
if one element (true, s) is left then return s - 6
if the elements are (a, true) and (b, false) then return a - 7
return the node for (v, E) from the unique table, made if it is new NEGATE(u) ▷ constants swap- 8
if u is a literal then return the opposite literal - 9
return UNIQUE(vt(u), {(p, NEGATE(s)) : (p, s) ∈ u}) COUNT(u, w) ▷ models of u over vars(w); vt(u) is in the subtree of w- 10
if u = false then return 0; if u = true then return 2^|vars(w)| - 11
c ← 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) - 12
return 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, with a memo on for line L22. Two SDDs for the same vtree are equivalent if and only if they are the same node.
Example
Take and the balanced vtree . At the root the left variables are . The assignments to them give two distinct subfunctions, when and otherwise, so the root decomposition is
The primes and the sub are decompositions at the two inner children:
| function | vtree node | elements |
|---|---|---|
The size is . COUNT at the root gives : the prime has 1 model over and the sub has 4 over , and the prime has 3 models and the sub has 1. On the right-linear vtree the same function has three decompositions of two elements each, size 6. They are the OBDD nodes for , and , and the OBDD node for is the literal . With the order on a right-linear vtree the size is 8.
The vtree decides the size. For , the implementation on this page gives these sizes:
| right-linear, | right-linear, | balanced, | |
|---|---|---|---|
| 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 . After ELEMENTS, both inputs are partitions at the same node . The nonempty products are pairwise inconsistent and cover all assignments to , and on an assignment in the function equals . So is a partition of .
- 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 , and a partition with the subs and is equal to the prime of .
- 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 over is a model of over joined with a model of over , so the counts multiply and add. Variables of outside 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 , is its function. For a vtree node , is the set of vtree nodes in the subtree of . We say is normal if it is a constant, or a literal, or a decomposition at some 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 be a normal decomposition at . Then depends on some variable of and on some variable of , and on no variable outside .
Proof. The last part holds because the primes and subs use only variables below . Let . For an assignment to , exactly one prime holds, and . If did not depend on , all would be equal, so all subs would be equal, and by compression there would be one element , which trimming excludes. If did not depend on , each would be a constant, so each sub would be or . By compression and since a partition has at least one element, the elements would be , (both with ) or , and trimming excludes all three.
Theorem 1 (canonicity; Darwiche 2011, Theorem 10). If and are normal and , then .
Proof. By induction on the size of the vtree subtree involved. Let and let be the set of variables that depends on. If , is a constant, and neither a literal nor (by Lemma 0) a decomposition has a constant function, so is that constant. If , is or , a decomposition depends on at least two variables by Lemma 0, so and are the same literal. Otherwise and are decompositions at and . By Lemma 0, and meets both and , so is the lowest common ancestor of the leaves of . The same holds for , so . Let . In a compressed partition, the sub of the element whose prime holds at is , so the subs are exactly the distinct functions and the prime of a sub is the set of with . So and 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 and are equal, and the unique table gives one id for one key.
Lemma 2 (ELEMENTS). If is normal, not a constant, and for an inner node , then ELEMENTS is a -partition of whose primes are normal and respect nodes in or are , and whose subs are normal and respect nodes in or are constants.
Proof. Line L12 returns the elements of , which have these properties by definition. At line L13, uses only variables of , so , and and are both satisfiable because is not constant. NEGATE is normal and respects by Lemma 4 below. At line L14, uses only variables of , and is a partition.
Lemma 3 (UNIQUE). If is a -partition of a function with normal primes in and normal subs in , then UNIQUE returns a normal node with and .
Proof. Line L15 replaces two elements and by . Since , the function is kept. The new prime is satisfiable and inconsistent with the other primes, and the primes still cover all assignments, so stays a partition. After the merges the subs are distinct. The primes come from APPLY, which is normal and stays in by Theorem 5 applied to smaller calls. At line L16, one element left means its prime is and , a normal node in . At line L17, the primes and partition, so and , a normal node in . Otherwise the node of line L18 is compressed and not of either trimmed form, so it is normal, and its function is .
Lemma 4 (NEGATE). If is normal, NEGATE is normal, has the function , and respects when is not constant.
Proof. By induction on . Constants swap and line L19 is clear. At line L20, , because exactly one prime holds at each assignment. The primes are unchanged, so is a partition. The negated subs are distinct because negation is a bijection, so line L15 merges nothing. The set of subs equals 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 .
Theorem 5 (APPLY). If and are normal, APPLY returns a normal node with , and is a constant or is in the subtree of the lowest common ancestor of and .
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 or on constants. Line L1: , , , and the duals for ; 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 is a leaf and , the two nodes are and , and , . Otherwise 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 of and of over . For an assignment to , exactly one and one hold, so exactly one product holds, and there . Hence the products that are not (line L9) are satisfiable, pairwise inconsistent, cover all of , and
By induction, is normal in or a constant, and is normal in or a constant; a prime of arises only when both and are , which is a partition of one element. So satisfies the condition of Lemma 3, and line L10 gives the claim.
Lemma 6 (COUNT). For a normal node and a vtree node with constant or , COUNT is the number of assignments to that satisfy .
Proof. Line L21 is clear. Let be the value of line L22; we show it is the number of models of over . A literal has one model over its variable. For a decomposition at with elements , an assignment to is a pair of assignments to and . It satisfies if and only if it satisfies for the unique with , that is, and . The sets of such pairs for different are disjoint, so the count is with each count over the variables of and , which is what line L22 computes by induction (the primes respect nodes in and the subs nodes in ). Finally does not use the variables of , so each model over extends in ways, which is line L23.
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.
Complexity
| operation | time |
|---|---|
| APPLY without lines L15 to L17 | (Darwiche 2011, Algorithm 1) |
| APPLY with compression | exponential in the worst case (Van den Broeck and Darwiche 2015) |
| NEGATE | expected |
| COUNT | additions and multiplications of numbers of at most bits |
| equivalence |
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 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 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 variables and treewidth has an SDD of size , 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 is kept, the same function has two ids, and the equivalence test by id fails.
- Counting over the wrong variables. A node that respects counts models over only. A sub , 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.
# 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
- 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)
- 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)
- 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)
- 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.
| 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 YVT6ET Edit this page History Report an error Markdown