Algorithm Search⌘K

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
Properties
not concurrentnot externalpersistent
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 n×nn \times n matrix AA whose nonzero entries are distinct symbols. The DDD represents the polynomial det⁡A\det A in these symbols, and the set of its nonzero terms. It has these operations:

  • BUILD(A)(A): make the DDD of det⁡A\det A.
  • EVALUATE(x)(x): the value of det⁡A\det A when each symbol has a number.
  • COUNT-TERMS: the number of nonzero terms of det⁡A\det A.
  • 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, 00 and 11. Each inner vertex vv has five fields:

  • an entry (r,c)(r, c) of AA and its symbol av=A[r,c]a_v = A[r, c],
  • a sign sv∈{+1,−1}s_v \in \{+1, -1\},
  • a hi child (the 1-edge): the DDD of the minor without row rr and column cc,
  • a lo child (the 0-edge): the DDD of the rest of the expansion of row rr.

The value of a vertex is

D(0)=0,D(1)=1,D(v)=sv av D(hi(v))+D(lo(v)).D(0) = 0, \qquad D(1) = 1, \qquad D(v) = s_v \, a_v \, D(\mathrm{hi}(v)) + D(\mathrm{lo}(v)).

A 1-path goes from the root to the terminal 11. 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 00 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 CC of columns: its rows are the last ∣C∣|C| rows. Laplace expansion along its first row rr is

det⁡AC=∑c∈C, A[r,c]≠0(−1)∣{c′∈C : c′<c}∣ A[r,c] det⁡AC∖{c}.\det A_C = \sum_{c \in C,\ A[r,c] \neq 0} (-1)^{|\{c' \in C \,:\, c' < c\}|} \, A[r, c] \, \det A_{C \setminus \{c\}}.

CHAIN(C,k)(C, k) is the part of this sum with the kk-th to the last nonzero column of row rr.

  1. BUILD(A) ▷ A is n × n
  2. 1return MINOR({0, …, n − 1})
  3. MINOR(C) ▷ rows n − |C| .. n − 1, columns C; memoized on C
  4. 2if C = ∅ then return the terminal 1
  5. 3r ← n − |C|
  6. 4c_1 < … < c_m ← the columns c ∈ C with A[r, c] ≠ 0
  7. 5return CHAIN(C, 1)
  8. CHAIN(C, k) ▷ memoized on (C, k)
  9. 6if k > m then return the terminal 0
  10. 7c ← c_k, s ← (−1)^|{c' ∈ C : c' < c}|
  11. 8h ← MINOR(C \ {c})
  12. 9l ← CHAIN(C, k + 1)
  13. 10if h = 0 then return l ▷ zero suppression
  14. 11return UNIQUE(r, c, s, h, l) ▷ an old vertex with these fields, or a new one

EVALUATE computes DD 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 P(0)=0P(0) = 0, P(1)=1P(1) = 1 and P(v)=P(hi(v))+P(lo(v))P(v) = P(\mathrm{hi}(v)) + P(\mathrm{lo}(v)), 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 4×44 \times 4 tridiagonal matrix

A=(ab00cde00fgh00ij).A = \begin{pmatrix} a & b & 0 & 0 \\ c & d & e & 0 \\ 0 & f & g & h \\ 0 & 0 & i & j \end{pmatrix}.

BUILD makes 10 inner vertices, one for each nonzero entry:

vertex entry sign hi lo
aa (0, 0) + dd bb
bb (0, 1) − cc 0
cc (1, 0) + gg 0
dd (1, 1) + gg ee
ee (1, 2) − ff 0
ff (2, 1) + jj 0
gg (2, 2) + jj hh
hh (2, 3) − ii 0
ii (3, 2) + 1 0
jj (3, 3) + 1 0

The vertices cc and dd share the hi child gg, which is the DDD of the minor with rows 2, 3 and columns 2, 3. After bb takes column 1, the minor has rows 1 to 3 and columns 0, 2 and 3. In its row 1, the entry ee 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 cc is 0. The five 1-paths give

det⁡A=adgj−adhi−aefj−bcgj+bchi.\det A = adgj - adhi - aefj - bcgj + bchi.

The path counts are P(i)=P(j)=P(h)=P(f)=P(e)=1P(i) = P(j) = P(h) = P(f) = P(e) = 1, P(g)=2P(g) = 2, P(c)=P(b)=2P(c) = P(b) = 2, P(d)=3P(d) = 3 and P(a)=5P(a) = 5. With a,b,…,j=1,2,…,10a, b, \ldots, j = 1, 2, \ldots, 10, EVALUATE gives D(h)=−72D(h) = -72, D(g)=70−72=−2D(g) = 70 - 72 = -2, D(f)=60D(f) = 60, D(e)=−300D(e) = -300, D(d)=−8−300=−308D(d) = -8 - 300 = -308, D(c)=−6D(c) = -6, D(b)=12D(b) = 12 and D(a)=−308+12=−296D(a) = -308 + 12 = -296. The five terms give 280−288−300−420+432=−296280 - 288 - 300 - 420 + 432 = -296, the same value.

Larger cases show the gap between terms and vertices:

matrix order nn 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 nn has Fn+1F_{n+1} terms, a Fibonacci number, and its DDD in this order has 3n−23n - 2 vertices. The reason: the minors that BUILD reaches at row rr have the columns {r,…,n−1}\{r, \ldots, n-1\}, which gives the vertices of the entries (r,r)(r, r) and (r,r+1)(r, r+1), or the columns {r−1,r+1,…,n−1}\{r-1, r+1, \ldots, n-1\}, where only the entry (r,r−1)(r, r-1) leads to a nonzero minor. So each nonzero entry has exactly one vertex. A dense matrix has n!n! terms and n 2n−1n \, 2^{n-1} vertices: each nonempty column set CC is reached, and it gives one vertex for each of its ∣C∣|C| columns, so the count is ∑kk(nk)=n 2n−1\sum_k k \binom{n}{k} = n \, 2^{n-1}.

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 0×00 \times 0 matrix. For a larger minor, CHAIN follows the Laplace expansion along the first row term by term: the sign (−1)∣{c′<c}∣(-1)^{|\{c' < c\}|} 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 AA be an n×nn \times n matrix whose nonzero entries are distinct symbols. For a set CC of kk columns, let r=n−kr = n - k and let ACA_C be the k×kk \times k submatrix with rows r,…,n−1r, \ldots, n-1 and the columns of CC in increasing order. Let c1<⋯<cmc_1 < \cdots < c_m be the columns of CC with A[r,c]≠0A[r, c] \neq 0.

For a vertex vv, the value D(v)D(v) is defined by D(0)=0D(0) = 0, D(1)=1D(1) = 1 and D(v)=sv av D(hi(v))+D(lo(v))D(v) = s_v \, a_v \, D(\mathrm{hi}(v)) + D(\mathrm{lo}(v)). A 1-path of vv is a path from vv 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 T(v)T(v) be the set of these signed terms.

For a permutation σ\sigma of CC (a bijection from the rows r,…,n−1r, \ldots, n-1 to CC), write t(σ)=sgn(σ)∏iA[i,σ(i)]t(\sigma) = \mathrm{sgn}(\sigma) \prod_i A[i, \sigma(i)], where the sign is the sign of the permutation of positions that σ\sigma gives after the columns of CC are numbered 1,…,k1, \ldots, k in increasing order. By the Leibniz formula, det⁡AC=∑σt(σ)\det A_C = \sum_\sigma t(\sigma). Let L(C)L(C) be the set of the terms t(σ)t(\sigma) that are not zero, that is, whose entries are all nonzero.

Lemma 1 (sign of a first-row choice). Let σ\sigma map row rr to column cc, and let j=1+∣{c′∈C:c′<c}∣j = 1 + |\{c' \in C : c' < c\}| be the position of cc in CC. Let σ′\sigma' be the restriction of σ\sigma to the rows r+1,…,n−1r+1, \ldots, n-1, a bijection onto C∖{c}C \setminus \{c\}. Then sgn(σ)=(−1)j−1 sgn(σ′)\mathrm{sgn}(\sigma) = (-1)^{j-1} \, \mathrm{sgn}(\sigma').

Proof. In positions, σ\sigma sends the first row to position jj. The inversions of σ\sigma are the inversions of σ′\sigma' (the relative order of the other columns does not change when cc is removed) and the pairs of the first row with a later row whose column is left of cc. There are exactly j−1j - 1 columns left of cc in CC, and each of them is the image of exactly one later row. So the number of inversions grows by j−1j - 1. □\square

The sign ss of line L7 is (−1)∣{c′∈C:c′<c}∣=(−1)j−1(-1)^{|\{c' \in C : c' < c\}|} = (-1)^{j-1}.

Lemma 2. For every set CC that the recursion reaches, T(MINOR(C))=L(C)T(\mathrm{MINOR}(C)) = L(C), and D(MINOR(C))=det⁡ACD(\mathrm{MINOR}(C)) = \det A_C as a polynomial. For 1≤k≤m+11 \le k \le m + 1, T(CHAIN(C,k))T(\mathrm{CHAIN}(C, k)) is the set of the terms of L(C)L(C) whose row rr uses one of the columns ck,…,cmc_k, \ldots, c_m, and D(CHAIN(C,k))D(\mathrm{CHAIN}(C, k)) is the sum of these terms.

Proof. By induction on ∣C∣|C|, and for a fixed CC by induction on m+1−km + 1 - k.

If C=∅C = \emptyset, line L2 returns the 1-terminal. The only permutation is the empty one, with term +1+1. So T={+1}=L(∅)T = \{+1\} = L(\emptyset) and D=1=det⁡A∅D = 1 = \det A_\emptyset.

Let C≠∅C \neq \emptyset. If k=m+1k = m + 1, line L6 returns the 0-terminal, which has no 1-path and value 0, and no term uses a column cjc_j with j>mj > m. So the claim holds.

Let k≤mk \le m and c=ckc = c_k. A term of L(C)L(C) whose row rr uses column cc is A[r,c]⋅(−1)j−1⋅t(σ′)A[r, c] \cdot (-1)^{j-1} \cdot t(\sigma') by Lemma 1, where t(σ′)t(\sigma') is a term of L(C∖{c})L(C \setminus \{c\}), and each term of L(C∖{c})L(C \setminus \{c\}) gives one such term. By the outer induction, h=MINOR(C∖{c})h = \mathrm{MINOR}(C \setminus \{c\}) of line L8 has T(h)=L(C∖{c})T(h) = L(C \setminus \{c\}). By the inner induction, l=CHAIN(C,k+1)l = \mathrm{CHAIN}(C, k+1) of line L9 holds the terms that use ck+1,…,cmc_{k+1}, \ldots, c_m.

If hh is the 0-terminal, then L(C∖{c})L(C \setminus \{c\}) is empty, so no term uses column cc, and line L10 returns ll, which is correct. Else line L11 returns a vertex vv with symbol A[r,c]A[r, c], sign s=(−1)j−1s = (-1)^{j-1}, hi(v)=h\mathrm{hi}(v) = h and lo(v)=l\mathrm{lo}(v) = l. A 1-path of vv either takes the hi edge and then a 1-path of hh, which gives the term s A[r,c] ts \, A[r, c] \, t for a term t∈T(h)t \in T(h), or takes the lo edge and then a 1-path of ll. These are exactly the terms that use ckc_k, and the terms that use ck+1,…,cmc_{k+1}, \ldots, c_m. The value is D(v)=s A[r,c] D(h)+D(l)D(v) = s \, A[r, c] \, D(h) + D(l), which is the sum of the same terms.

Last, MINOR returns CHAIN(C,1)\mathrm{CHAIN}(C, 1) (line L5). Each term of L(C)L(C) uses some nonzero entry A[r,cj]A[r, c_j] of row rr, so the terms with columns c1,…,cmc_1, \ldots, c_m are all of L(C)L(C), and the sum of all terms of the Leibniz formula is det⁡AC\det A_C. □\square

Theorem. The root BUILD(A)=MINOR({0,…,n−1})\mathrm{BUILD}(A) = \mathrm{MINOR}(\{0, \ldots, n-1\}) has D(root)=det⁡AD(\mathrm{root}) = \det A. The 1-paths of the root are in bijection with the nonzero terms of det⁡A\det A, and the number of terms equals the number of 1-paths.

Proof. Lemma 2 with C={0,…,n−1}C = \{0, \ldots, n-1\} gives T(root)=L(C)T(\mathrm{root}) = L(C) 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 ww where they part. One path leaves ww by the hi edge, so its term contains the entry of ww. The other leaves ww 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 ww again. So the two paths give different sets of entries, and different terms. ■\blacksquare

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 uu when a new vertex would have the same row, column, sign, hi child and lo child. Then uu 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 vv, 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 T(v)T(v). Let uu and vv be two inner vertices with T(u)=T(v)T(u) = T(v). Then they have the same entry ee. The terms of T(hi)T(\mathrm{hi}) are the terms of T(v)T(v) that contain ee, with ee and its sign removed, and T(lo)T(\mathrm{lo}) is the rest. So by induction on the depth, uu and vv have the same children, and their signs are equal because a term that contains ee has one sign. The unique table then makes u=vu = v. 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 DD for all vertices from the rule above. The number of 1-paths satisfies P(0)=0P(0) = 0, P(1)=1P(1) = 1 and P(v)=P(hi(v))+P(lo(v))P(v) = P(\mathrm{hi}(v)) + P(\mathrm{lo}(v)), because each 1-path of vv leaves vv 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 n≤wn \le w bits, and with expected O(1)O(1) hash operations.

  • BUILD. Let MM be the number of distinct column sets that MINOR reaches. Each needs O(n)O(n) time to list its nonzero columns (line L4), and it has at most n+1n + 1 CHAIN calls of O(1)O(1) time each. So BUILD takes O(nM)O(n M) expected time and makes V≤nMV \le n M vertices. For a dense matrix M=2nM = 2^n, so BUILD takes O(n 2n)O(n \, 2^n) time, against the n!n! terms of a full expansion. For a tridiagonal matrix, MM is 11, 56 and 466 for n=4n = 4, 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: O(V)O(V) arithmetic operations. The term count can be exponential in nn, so its numbers can have O(nlog⁡n)O(n \log n) bits.
  • TERMS. Each term has nn entries, so listing TT terms takes O(nT+V)O(n T + V) 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 nn has n 2n−1n \, 2^{n-1} 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 g+sCg + s C by powers of the frequency variable ss, 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 ss.
  • 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 gg 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.

determinant_decision_diagram.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.count_terms
  • a full proof of time.evaluate
  • a full proof of time.list_terms
  • a full proof of space.vertices
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/09FYV2/text.yaml