Data structureadvanced
Determinant decision diagram
Also called DDD.
Shi and Tan's BDD-like canonical graph of the symbolic determinant of a circuit matrix, which shares subexpressions so exact symbolic analysis scales to large circuits.
- Time
- O(n M) expected buildO(V) count_terms · evaluateO(n T + V) list_terms
- Space
- O(n M) vertices
- Where
- M = the number of distinct minors that BUILD reaches; T = the number of nonzero terms of the determinant; V = the number of DDD vertices; n = the order of the matrix
- Model
- Word RAM
- Properties
- not concurrentnot externalpersistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- C. J. Richard Shi, Xiang Dong Tan, 1997
A determinant decision diagram, or DDD, is a directed acyclic graph that holds the determinant of a sparse matrix with symbolic entries, one vertex for each entry in each minor that it appears in, and one path for each term. It is a zero-suppressed BDD of the set of terms, with a sign on each vertex. Its topic is symbolic circuit analysis: the matrix comes from modified nodal analysis of a small-signal circuit, and the determinant and its cofactors give the network functions of symbolic circuit analysis. A DDD can have far fewer vertices than the determinant has terms, so a computer can store, evaluate and count an exact expression whose expanded form does not fit in memory.
In plain words
The determinant of a matrix, written out in full, is a long sum of products. Each product takes one entry from each row, and no two entries from the same column. For a circuit, these sums grow so fast that a printed formula becomes useless after a few dozen nodes.
Many products share their tails. After you choose the entries of the first rows, the rest of the product only depends on which columns are still free. A DDD stores each such tail one time, and every product that ends with it points to it. Each node of the graph asks one question: do we use this entry or not? Follow the yes and no arrows from the top to the end marked one, and you read one product. The graph can be small when the list of products is huge.
The abstract type
The input is an matrix whose nonzero entries are distinct symbols. The DDD represents the polynomial in these symbols, and the set of its nonzero terms. It has these operations:
- BUILD: make the DDD of .
- EVALUATE: the value of when each symbol has a number.
- COUNT-TERMS: the number of nonzero terms of .
- TERMS: list the terms, each with its sign.
- SIZE: the number of vertices.
A network function of a linear circuit is a ratio of a cofactor and the determinant, by Cramer's rule. A cofactor is the determinant of a submatrix, so the same structure holds it. The DDDs of the determinant and of its cofactors can share one table of vertices, with one root for each.
Representation
There are two terminal vertices, and . Each inner vertex has five fields:
- an entry of and its symbol ,
- a sign ,
- a hi child (the 1-edge): the DDD of the minor without row and column ,
- a lo child (the 0-edge): the DDD of the rest of the expansion of row .
The value of a vertex is
A 1-path goes from the root to the terminal . Its term is the product of the symbols and signs of the vertices that it leaves by a hi edge. The value of the root is the sum of the terms of all 1-paths.
Two rules keep the graph small and canonical, as in a reduced ordered BDD:
- Zero suppression. A vertex whose hi child is adds nothing. It is never made, and its lo child takes its place.
- Unique table. A hash table on (row, column, sign, hi, lo) returns the old vertex when the same vertex is asked for again. This is hash consing.
The entries are ordered row by row, and in each row by column. Each vertex comes before all vertices below it in this order. Shi and Tan allow other orders of the entries and choose one with a heuristic, because the size depends on the order, as for a BDD and its variable ordering.
Operations
BUILD makes the DDD by Laplace expansion along the first row of each minor, with memoization on the minor. A minor is fixed by its set of columns: its rows are the last rows. Laplace expansion along its first row is
CHAIN is the part of this sum with the -th to the last nonzero column of row .
BUILD(A) ▷ A is n × n- 1
return MINOR({0, …, n − 1}) MINOR(C) ▷ rows n − |C| .. n − 1, columns C; memoized on C- 2
if C = ∅ then return the terminal 1 - 3
r ← n − |C| - 4
c_1 < … < c_m ← the columns c ∈ C with A[r, c] ≠ 0 - 5
return CHAIN(C, 1) CHAIN(C, k) ▷ memoized on (C, k)- 6
if k > m then return the terminal 0 - 7
c ← c_k, s ← (−1)^|{c' ∈ C : c' < c}| - 8
h ← MINOR(C \ {c}) - 9
l ← CHAIN(C, k + 1) - 10
if h = 0 then return l ▷ zero suppression - 11
return UNIQUE(r, c, s, h, l) ▷ an old vertex with these fields, or a new one
EVALUATE computes for every vertex in one pass from the terminals up, with the numbers in place of the symbols. COUNT-TERMS computes the number of 1-paths with , and , in one pass. TERMS walks all 1-paths. In the implementation, a vertex is made after its two children, so the index order is a valid bottom-up order.
Example
Take the tridiagonal matrix
BUILD makes 10 inner vertices, one for each nonzero entry:
| vertex | entry | sign | hi | lo |
|---|---|---|---|---|
| (0, 0) | + | |||
| (0, 1) | − | 0 | ||
| (1, 0) | + | 0 | ||
| (1, 1) | + | |||
| (1, 2) | − | 0 | ||
| (2, 1) | + | 0 | ||
| (2, 2) | + | |||
| (2, 3) | − | 0 | ||
| (3, 2) | + | 1 | 0 | |
| (3, 3) | + | 1 | 0 |
The vertices and share the hi child , which is the DDD of the minor with rows 2, 3 and columns 2, 3. After takes column 1, the minor has rows 1 to 3 and columns 0, 2 and 3. In its row 1, the entry leads to a minor with no terms, because then no row is left that has an entry in column 0. Zero suppression drops this vertex, so the lo child of is 0. The five 1-paths give
The path counts are , , , and . With , EVALUATE gives , , , , , , and . The five terms give , the same value.
Larger cases show the gap between terms and vertices:
| matrix | order | terms | DDD vertices |
|---|---|---|---|
| tridiagonal | 10 | 89 | 28 |
| tridiagonal | 30 | 1,346,269 | 88 |
| dense | 6 | 720 | 192 |
| dense | 8 | 40,320 | 1,024 |
A tridiagonal matrix of order has terms, a Fibonacci number, and its DDD in this order has vertices. The reason: the minors that BUILD reaches at row have the columns , which gives the vertices of the entries and , or the columns , where only the entry leads to a nonzero minor. So each nonzero entry has exactly one vertex. A dense matrix has terms and vertices: each nonempty column set is reached, and it gives one vertex for each of its columns, so the count is .
Correctness
BUILD is correct by induction on the number of columns of the minor. For the empty minor it returns the terminal 1, the determinant of a matrix. For a larger minor, CHAIN follows the Laplace expansion along the first row term by term: the sign of line L7 is the sign of the column's position in the minor, and the hi child is the DDD of the smaller minor. Zero suppression drops only a term whose minor has no terms. The symbols are distinct, so no two terms cancel, and the 1-paths are in bijection with the nonzero terms. The unique table merges only vertices with the same five fields, so it changes neither the value nor the paths. Two vertices with the same set of signed terms are the same vertex, which makes the DDD canonical for a fixed order of the entries. The full proof is below.
Proof: BUILD gives a DDD whose value is the determinant and whose 1-paths are its termsfull
Let be an matrix whose nonzero entries are distinct symbols. For a set of columns, let and let be the submatrix with rows and the columns of in increasing order. Let be the columns of with .
For a vertex , the value is defined by , and . A 1-path of is a path from to the 1-terminal. Its term is the product of the symbols of the vertices that the path leaves by a hi edge, with the product of their signs. Let be the set of these signed terms.
For a permutation of (a bijection from the rows to ), write , where the sign is the sign of the permutation of positions that gives after the columns of are numbered in increasing order. By the Leibniz formula, . Let be the set of the terms that are not zero, that is, whose entries are all nonzero.
Lemma 1 (sign of a first-row choice). Let map row to column , and let be the position of in . Let be the restriction of to the rows , a bijection onto . Then .
Proof. In positions, sends the first row to position . The inversions of are the inversions of (the relative order of the other columns does not change when is removed) and the pairs of the first row with a later row whose column is left of . There are exactly columns left of in , and each of them is the image of exactly one later row. So the number of inversions grows by .
The sign of line L7 is .
Lemma 2. For every set that the recursion reaches, , and as a polynomial. For , is the set of the terms of whose row uses one of the columns , and is the sum of these terms.
Proof. By induction on , and for a fixed by induction on .
If , line L2 returns the 1-terminal. The only permutation is the empty one, with term . So and .
Let . If , line L6 returns the 0-terminal, which has no 1-path and value 0, and no term uses a column with . So the claim holds.
Let and . A term of whose row uses column is by Lemma 1, where is a term of , and each term of gives one such term. By the outer induction, of line L8 has . By the inner induction, of line L9 holds the terms that use .
If is the 0-terminal, then is empty, so no term uses column , and line L10 returns , which is correct. Else line L11 returns a vertex with symbol , sign , and . A 1-path of either takes the hi edge and then a 1-path of , which gives the term for a term , or takes the lo edge and then a 1-path of . These are exactly the terms that use , and the terms that use . The value is , which is the sum of the same terms.
Last, MINOR returns (line L5). Each term of uses some nonzero entry of row , so the terms with columns are all of , and the sum of all terms of the Leibniz formula is .
Theorem. The root has . The 1-paths of the root are in bijection with the nonzero terms of , and the number of terms equals the number of 1-paths.
Proof. Lemma 2 with gives and the value. Two different permutations use two different sets of entries. The symbols are distinct, so their terms are different monomials, and no two terms cancel. Take two different 1-paths and the first vertex where they part. One path leaves by the hi edge, so its term contains the entry of . The other leaves by the lo edge. After a lo edge, each vertex is in the same row with a larger column or in a later row, so this path never meets the entry of again. So the two paths give different sets of entries, and different terms.
The memo and the unique table do not change the result. The memo of MINOR and CHAIN returns a vertex that was built for the same arguments, so it returns the same vertex as a new call would. The unique table returns an old vertex when a new vertex would have the same row, column, sign, hi child and lo child. Then and the new vertex have the same value and the same 1-paths, because both are defined only by these five fields.
Canonical form. Order the entries row by row, and in a row by column. For each vertex , its entry comes before every entry below it: a hi edge goes to a later row, and a lo edge goes to a later column of the same row. Its hi child is not the 0-terminal (line L10), so its entry is the first entry that occurs in a term of . Let and be two inner vertices with . Then they have the same entry . The terms of are the terms of that contain , with and its sign removed, and is the rest. So by induction on the depth, and have the same children, and their signs are equal because a term that contains has one sign. The unique table then makes . So two vertices with the same set of signed terms are the same vertex. This is the canonical property of a zero-suppressed BDD, which a DDD is, with a sign on each vertex.
Evaluation and counting. Each child has a smaller index than its parent, because a vertex is made after its two children. So one pass in index order computes for all vertices from the rule above. The number of 1-paths satisfies , and , because each 1-path of leaves by exactly one of its two edges. One pass in index order computes it.
Complexity
The costs are in the word-RAM model, with a column set stored as a bit mask of bits, and with expected hash operations.
- BUILD. Let be the number of distinct column sets that MINOR reaches. Each needs time to list its nonzero columns (line L4), and it has at most CHAIN calls of time each. So BUILD takes expected time and makes vertices. For a dense matrix , so BUILD takes time, against the terms of a full expansion. For a tridiagonal matrix, is 11, 56 and 466 for , 10 and 30, because BUILD also enters minors with no terms before zero suppression drops them. A check of the structural rank of each minor (a bipartite matching) would stop these calls early.
- EVALUATE and COUNT-TERMS. One pass over the vertices: arithmetic operations. The term count can be exponential in , so its numbers can have bits.
- TERMS. Each term has entries, so listing terms takes time. This cost is the reason to keep the expression as a DDD.
The size of the DDD depends on the order of the entries. A good order for a circuit matrix follows the structure of the circuit. No order makes every matrix small: the dense matrix of order has vertices in the row order above.
Variants
- Multiroot DDDs. The determinant and the cofactors of one matrix share one unique table. Shi and Tan also expand each entry by powers of the frequency variable , and build one root for each coefficient of each power, so the numerator and the denominator of a network function come out as polynomials in .
- Other entry orders. The row order of this page is the simplest. Shi and Tan order the entries with a heuristic that follows the circuit graph.
- Approximate generation. The dominant terms of a DDD can be found by a shortest-path search on the graph, with the logarithm of each term's size as the path length. This is one of the methods of approximate symbolic analysis.
- Hierarchical analysis. Tan and Shi split a large circuit into blocks, build one DDD for each block, and combine their results.
When to use it
Use a DDD when you need the exact symbolic determinant or network function of a circuit with tens to hundreds of nodes, and need to evaluate it many times with new numbers, count its terms, or take the largest terms from it. To get a number for one set of values, Gaussian elimination is faster. To give a designer a short formula, the exact expression is too long, and an approximate method is the right tool.
Pitfalls
- Expanding the terms. The terms can be many more than the vertices. Count and evaluate on the graph. Do not list the terms unless you need a few of them.
- A bad order of the entries. The size depends on the order. A random order of the rows and columns of a band matrix can make the graph much larger.
- Equal symbols. The term count and the bijection with the paths assume distinct symbols. If two entries carry the same symbol, for example the conductance in four entries of a nodal matrix, then terms can cancel or merge, and the 1-paths overcount the terms of the polynomial in the element values.
- The wrong sign. The sign depends on the position of the column in the current minor, not in the full matrix.
- No zero suppression. Without line L10, the graph keeps vertices for entries that lead to no term. The value is still right, but the canonical form and the size are lost.
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/determinant-decision-diagram/. The authors are listed in prov/09FYV2.jsonl.
"""A determinant decision diagram (DDD) of a sparse symbolic matrix.
The matrix is a dict {(row, col): symbol} of its nonzero entries, with rows
and columns 0 .. n - 1. The DDD is built by Laplace expansion along the first
row of each minor, with a memo on the minor and a unique table on the vertices.
Node 0 is the 0-terminal and node 1 is the 1-terminal. An inner node is a tuple
(row, col, symbol, sign, hi, lo): hi is the DDD of the minor without this row
and column, lo is the rest of the expansion of the current row.
"""
from fractions import Fraction
ZERO, ONE = 0, 1
class DDD:
def __init__(self, n: int, entries: dict) -> None:
self.n = n
self.entries = {k: v for k, v in entries.items()}
self.nodes: list = [None, None] # the two terminals
self.unique: dict = {}
self._minor: dict = {}
self._chain: dict = {}
self.root = self._build()
def _mk(self, r: int, c: int, s: int, hi: int, lo: int) -> int:
key = (r, c, s, hi, lo)
v = self.unique.get(key)
if v is None:
v = len(self.nodes)
self.nodes.append((r, c, self.entries[(r, c)], s, hi, lo))
self.unique[key] = v
return v
def _build(self) -> int:
return self._minor_of((1 << self.n) - 1) # @line L1
def _minor_of(self, cset: int) -> int:
"""The DDD of the minor with rows n - |C| .. n - 1 and columns C (a bit set)."""
if cset == 0: # @line L2
return ONE
if cset in self._minor:
return self._minor[cset]
r = self.n - bin(cset).count("1") # @line L3
cols = [c for c in range(self.n) if cset >> c & 1 and (r, c) in self.entries] # @line L4
v = self._chain_of(cset, r, cols, 0) # @line L5
self._minor[cset] = v
return v
def _chain_of(self, cset: int, r: int, cols: list, k: int) -> int:
key = (cset, k)
if key in self._chain:
return self._chain[key]
if k == len(cols): # @line L6
v = ZERO
else:
c = cols[k] # @line L7
s = -1 if bin(cset & ((1 << c) - 1)).count("1") % 2 else 1
hi = self._minor_of(cset & ~(1 << c)) # @line L8
lo = self._chain_of(cset, r, cols, k + 1) # @line L9
if hi == ZERO: # @line L10: zero suppression
v = lo
else:
v = self._mk(r, c, s, hi, lo) # @line L11
self._chain[key] = v
return v
def size(self) -> int:
"""The number of inner vertices."""
return len(self.nodes) - 2
def count_terms(self) -> int:
"""The number of 1-paths, that is, of nonzero terms of the determinant."""
paths = [0, 1]
for v in range(2, len(self.nodes)):
_, _, _, _, hi, lo = self.nodes[v]
paths.append(paths[hi] + paths[lo]) # children have smaller ids
return paths[self.root]
def evaluate(self, values: dict) -> Fraction:
"""The determinant for numeric values {symbol: number}, in one pass."""
val = [Fraction(0), Fraction(1)]
for v in range(2, len(self.nodes)):
_, _, sym, s, hi, lo = self.nodes[v]
val.append(s * Fraction(values[sym]) * val[hi] + val[lo])
return val[self.root]
def terms(self) -> list:
"""All terms as (sign, tuple of (row, col)) pairs, by a walk of the 1-paths."""
out = []
def walk(v: int, s: int, path: list) -> None:
if v == ONE:
out.append((s, tuple(path)))
return
if v == ZERO:
return
r, c, _, sv, hi, lo = self.nodes[v]
walk(hi, s * sv, path + [(r, c)])
walk(lo, s, path)
walk(self.root, 1, [])
return out
test_determinant_decision_diagram.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/determinant-decision-diagram/. The authors are listed in prov/09FYV2.jsonl.
import itertools
import random
from fractions import Fraction
from determinant_decision_diagram import DDD
def leibniz_terms(n: int, entries: dict) -> set:
"""Full expansion: every permutation whose entries are all nonzero, with its sign."""
out = set()
for p in itertools.permutations(range(n)):
if all((i, p[i]) in entries for i in range(n)):
inv = sum(1 for i in range(n) for j in range(i + 1, n) if p[i] > p[j])
out.add((-1 if inv % 2 else 1, tuple((i, p[i]) for i in range(n))))
return out
def gauss_det(n: int, a: list) -> Fraction:
m = [[Fraction(x) for x in row] for row in a]
det = Fraction(1)
for col in range(n):
piv = next((r for r in range(col, n) if m[r][col] != 0), None)
if piv is None:
return Fraction(0)
if piv != col:
m[col], m[piv] = m[piv], m[col]
det = -det
det *= m[col][col]
for r in range(col + 1, n):
f = m[r][col] / m[col][col]
for c in range(col, n):
m[r][c] -= f * m[col][c]
return det
def random_pattern(n: int, density: float, rng: random.Random) -> dict:
return {(i, j): f"a{i}{j}" for i in range(n) for j in range(n) if i == j or rng.random() < density}
def tridiagonal(n: int) -> dict:
return {(i, j): f"a{i}{j}" for i in range(n) for j in range(n) if abs(i - j) <= 1}
def check(n: int, entries: dict, rng: random.Random) -> DDD:
d = DDD(n, entries)
terms = leibniz_terms(n, entries)
assert set(d.terms()) == terms
assert len(d.terms()) == len(terms) == d.count_terms()
for _ in range(3):
vals = {s: Fraction(rng.randint(-9, 9), rng.randint(1, 5)) for s in entries.values()}
a = [[vals[entries[(i, j)]] if (i, j) in entries else 0 for j in range(n)] for i in range(n)]
assert d.evaluate(vals) == gauss_det(n, a)
return d
def test_example_4x4() -> None:
letters = iter("abcdefghij")
e = {k: next(letters) for k in sorted(tridiagonal(4))}
d = DDD(4, e)
assert d.count_terms() == 5
got = {(s, "".join(e[p] for p in path)) for s, path in d.terms()}
assert got == {(1, "adgj"), (-1, "adhi"), (-1, "aefj"), (-1, "bcgj"), (1, "bchi")}
assert d.size() == 10
vals = dict(zip("abcdefghij", range(1, 11)))
assert d.evaluate(vals) == gauss_det(4, [[1, 2, 0, 0], [3, 4, 5, 0], [0, 6, 7, 8], [0, 0, 9, 10]])
def test_edges() -> None:
assert DDD(0, {}).root == 1
d = DDD(1, {(0, 0): "x"})
assert d.count_terms() == 1 and d.evaluate({"x": 3}) == 3
d = DDD(2, {(0, 1): "x", (1, 1): "y"}) # singular pattern: no term
assert d.root == 0 and d.count_terms() == 0 and d.size() == 0
def test_random_sparse_against_leibniz_and_gauss() -> None:
rng = random.Random(2000)
for n in range(1, 7):
for _ in range(15):
check(n, random_pattern(n, rng.choice([0.2, 0.4, 0.7]), rng), rng)
def test_dense() -> None:
rng = random.Random(7)
for n in range(1, 7):
e = {(i, j): f"a{i}{j}" for i in range(n) for j in range(n)}
d = check(n, e, rng)
assert d.count_terms() == len(list(itertools.permutations(range(n))))
assert d.size() == n * 2 ** (n - 1)
def test_tridiagonal_fibonacci_terms_linear_size() -> None:
fib = [0, 1]
while len(fib) < 40:
fib.append(fib[-1] + fib[-2])
for n in range(1, 31):
d = DDD(n, tridiagonal(n))
assert d.count_terms() == fib[n + 1]
assert d.size() == 3 * n - 2
History
Shi and Tan presented determinant decision diagrams at ICCAD in 1997 and in IEEE Transactions on Computer-Aided Design in 2000. They built them on the zero-suppressed BDDs of Minato from 1993. In 2001 they gave multiroot DDDs for the coefficients of the powers of the frequency variable.
References
- C.-J. R. Shi and X.-D. Tan, Canonical symbolic analysis of large analog circuits with determinant decision diagrams, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 19(1), 1 to 18, January 2000, the definition of the DDD (a signed vertex per matrix entry with a 1-edge and a 0-edge), its relation to zero-suppressed BDDs, its canonical form under a fixed order, its construction by Laplace expansion, and the vertex ordering
- C.-J. R. Shi and X.-D. Tan, Symbolic analysis of large analog circuits with determinant decision diagrams, ICCAD 1997, pages 366 to 373, the conference version
- C.-J. R. Shi and X.-D. Tan, Compact representation and efficient generation of s-expanded symbolic network functions for computer-aided analog circuit design, IEEE Transactions on Computer-Aided Design 20(7), 813 to 827, 2001, multiroot DDDs for the coefficients of each power of s of a network function
- S. Minato, Zero-suppressed BDDs for set manipulation in combinatorial problems, DAC 1993, pages 272 to 277, the zero-suppression rule and the canonical form of a family of sets
- X.-D. Tan and C.-J. R. Shi, Hierarchical symbolic analysis of analog integrated circuits via determinant decision diagrams, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 19(4), 401 to 412, April 2000, the analysis of a circuit split into blocks, with one DDD for each block
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 09FYV2 Edit this page History Report an error Markdown