Algorithm Search⌘K

Algorithmcore

Transition density

Also called Najm transition density.

Najm's measure of average transitions per second and its propagation through gates by Boolean difference probabilities, giving power without simulation vectors.

Time
O(G + P K) worst
Space
O(G + n) extra
Where
G = the number of gates; K = the largest fanin of a gate; P = the number of gate input pins; n = the number of primary inputs
Properties
deterministicnot exactofflineiterative
Origin
Farid N. Najm, 1991

The transition density D(x)D(x) of a logic signal xx is its average number of transitions per unit time. Najm (1991, 1993) showed that for a gate or block y=f(x1,…,xn)y = f(x_1, \ldots, x_n) with independent inputs,

D(y)  =  ∑i=1nP ⁣(∂y∂xi)D(xi),D(y) \;=\; \sum_{i=1}^{n} P\!\left(\frac{\partial y}{\partial x_i}\right) D(x_i),

where ∂y/∂xi\partial y / \partial x_i is the Boolean difference of yy with respect to xix_i. The algorithm applies this rule gate by gate in topological order, with the signal probabilities of the gate inputs, and so turns input statistics into a density at every node in one pass, without input vectors or simulation. The dynamic power of a node is then 12CVDD2D(y)\frac{1}{2} C V_{DD}^2 D(y). The result is exact on circuits without reconvergent fanout when no two inputs switch at the same instant. With reconvergent fanout it is an approximation, and with inputs that switch together at a clock edge it counts glitches that a zero-delay view does not see.

In plain words

Each input wire turns on and off at random, a known number of times per second, and the inputs act independently. The question is how often each wire inside the circuit switches.

When one input of a gate switches, the output switches only if the other inputs let the change through. An AND gate passes a change on one input only when its other inputs are on. So the output switches as often as each input switches, times the chance that the gate passes that input, summed over the inputs.

Going through the gates from the inputs to the outputs gives a switching rate for every wire. Multiply each rate by the energy of one switch and you have the power, with no simulation at all.

The problem

The input is a combinational circuit CC with primary inputs x1,…,xnx_1, \ldots, x_n and gates in topological order, and for each input xix_i two numbers: its equilibrium probability pi=P(xi=1)p_i = P(x_i = 1), the fraction of time it is 1, and its transition density did_i, its mean number of transitions per unit time. The model treats each input as a random 0-1 signal xi(t)x_i(t) in continuous time. The signals are mutually independent and stationary, with a finite number of transitions in each finite interval. For a node yy with Ny(T)N_y(T) transitions in [0,T][0, T],

D(y)  =  lim⁡T→∞E[Ny(T)]T.D(y) \;=\; \lim_{T \to \infty} \frac{E[N_y(T)]}{T}.

The output is P(y)P(y) and D(y)D(y) for every node yy.

For a Boolean function ff of x1,…,xnx_1, \ldots, x_n, the Boolean difference of ff with respect to xix_i is

∂f∂xi  =  f∣xi=1⊕f∣xi=0,\frac{\partial f}{\partial x_i} \;=\; f|_{x_i = 1} \oplus f|_{x_i = 0},

the XOR of the two cofactors of ff. It does not depend on xix_i, and it is 1 at exactly those values of the other variables for which a change of xix_i changes ff. In test it is the condition for the effect of a fault on xix_i to reach the output. For a single gate it is simple: ∂ AND(z1,…,zk)/∂zj\partial\, \mathrm{AND}(z_1, \ldots, z_k) / \partial z_j is the AND of the other inputs, the derivative of OR is the AND of the complements of the other inputs, and the derivative of XOR, BUF or NOT is 1. Complementing ff does not change ∂f/∂xi\partial f / \partial x_i, so NAND, NOR and XNOR have the same derivatives as AND, OR and XOR.

The algorithm

  1. TRANSITION-DENSITY(C, p, d)
  2. 1for each primary input x_i do P[x_i] ← p_i; D[x_i] ← d_i
  3. 2for each gate y = kind(z_1, …, z_k) in topological order do
  4. 3P[y] ← the signal probability of kind with input probabilities P[z_1], …, P[z_k]
  5. 4D[y] ← 0
  6. 5for j ← 1 to k do
  7. 6b ← P(∂y/∂z_j): ∏_{l≠j} P[z_l] for AND and NAND, ∏_{l≠j} (1 − P[z_l]) for OR and NOR, 1 for XOR, XNOR, BUF and NOT
  8. 7D[y] ← D[y] + b · D[z_j]
  9. 8return P, D

Line L3 is the numeric mode of signal probability propagation. Line L6 computes the probability of the Boolean difference of the gate under the assumption that its inputs are independent, from the probabilities found at line L3 for the earlier gates.

Example

A fanout-free circuit. Take u=AND(a,b)u = \mathrm{AND}(a, b) and y=OR(u,c)y = \mathrm{OR}(u, c), with densities in transitions per nanosecond.

node PP DD
aa 1/21/2 22
bb 1/41/4 11
cc 1/21/2 44
uu 1/2⋅1/4=1/81/2 \cdot 1/4 = 1/8 P(b)D(a)+P(a)D(b)=1/2+1/2=1P(b) D(a) + P(a) D(b) = 1/2 + 1/2 = 1
yy 1−(7/8)(1/2)=9/161 - (7/8)(1/2) = 9/16 (1−P(c))D(u)+(1−P(u))D(c)=1/2+7/2=4(1 - P(c)) D(u) + (1 - P(u)) D(c) = 1/2 + 7/2 = 4

Each node drives one pin, so these values are exact under the model. A change on cc passes the OR gate whenever u=0u = 0, which is 7/8 of the time, so yy inherits most of the activity of cc. If yy drives 10 fF at 1 V, its power is 12⋅10−14⋅12⋅4⋅109=20\frac{1}{2} \cdot 10^{-14} \cdot 1^2 \cdot 4 \cdot 10^9 = 20 µW.

A reconvergent circuit. Take u=AND(a,b)u = \mathrm{AND}(a, b), v=AND(a,c)v = \mathrm{AND}(a, c) and y=OR(u,v)y = \mathrm{OR}(u, v), all inputs with P=1/2P = 1/2 and D=1D = 1. The algorithm gives D(u)=D(v)=1D(u) = D(v) = 1 and D(y)=34⋅1+34⋅1=3/2D(y) = \frac{3}{4} \cdot 1 + \frac{3}{4} \cdot 1 = 3/2. The rule applied to the whole function y=a(b∨c)y = a(b \lor c) gives the true value: ∂y/∂a=b∨c\partial y / \partial a = b \lor c, ∂y/∂b=acˉ\partial y / \partial b = a \bar c and ∂y/∂c=abˉ\partial y / \partial c = a \bar b, so

D(y)=34⋅1+14⋅1+14⋅1=54.D(y) = \tfrac{3}{4} \cdot 1 + \tfrac{1}{4} \cdot 1 + \tfrac{1}{4} \cdot 1 = \tfrac{5}{4}.

The gate-by-gate value is 20 percent too high, because uu and vv both depend on aa and the gate rule at yy treats them as independent.

Correctness

The proof has two parts, both in the full proof.

The rule for one block. Suppose the inputs of y=f(x1,…,xn)y = f(x_1, \ldots, x_n) are independent stationary signals, no two of them switch at the same instant, and yy follows ff with zero delay or with a fixed delay. Then yy changes only at a transition of some xix_i, and at such an instant it changes exactly when ∂f/∂xi=1\partial f / \partial x_i = 1 at the values of the other inputs. The other inputs are independent of the transition times of xix_i and stationary, so the expected count of the transitions of xix_i that pass is P(∂f/∂xi)P(\partial f / \partial x_i) times the expected count of the transitions of xix_i. Summing over ii gives the formula. A fixed delay moves the transitions in time but does not change their number.

The pass over the gates. When the input pins of every gate have disjoint supports, as in a fanout-free circuit, the inputs of each gate are functions of disjoint groups of independent primary input signals. So they are independent stationary signals, with no common transition instants, and the rule for one block holds at each gate. The probabilities of line L3 are exact under the same condition. By induction in topological order every P[y]P[y] and D[y]D[y] is exact. Under reconvergent fanout the independence of the gate inputs fails, and the example above shows that the result can then be wrong.

Proof: The transition density formula for independent inputs, and exactness of the gate-by-gate pass without reconvergencefull

Model. A logic signal is a random function x:R→{0,1}x : \mathbb{R} \to \{0, 1\} that is right-continuous and has finitely many transitions in every bounded interval. Write NxN_x for the random set of its transition times and Nx(A)N_x(A) for the number of them in a set AA. The signal is stationary when the law of (x(t+s))t(x(t + s))_{t} does not depend on ss; then P(x(t)=1)=pxP(x(t) = 1) = p_x for every tt and E[Nx((a,b])]=D(x) (b−a)E[N_x((a, b])] = D(x)\,(b - a) for a constant D(x)D(x), the transition density, which we assume finite. Signals are independent when they are independent as random functions.

Lemma 1 (no common transitions). If xx and zz are independent stationary signals with finite densities, then with probability 1 they have no transition time in common.

Proof. For a fixed instant tt, E[Nz({t})]=lim⁡h→0E[Nz((t−h,t])]=lim⁡h→0D(z)h=0E[N_z(\{t\})] = \lim_{h \to 0} E[N_z((t - h, t])] = \lim_{h \to 0} D(z) h = 0, so P(t∈Nz)=0P(t \in N_z) = 0. Condition on xx. Its transition times in (0,T](0, T] form a finite set that is independent of zz, so the expected number of them that are also transitions of zz is a finite sum of zeros. Taking expectations and letting T→∞T \to \infty over the integers gives the claim. □\square

Lemma 2 (sampling at independent instants). Let NN be a random set of instants with E[N((0,T])]=DTE[N((0, T])] = D T, and let ZZ be a stationary 0-1 signal independent of NN. Then

E[∑t∈N∩(0,T]Z(t)]  =  D T P(Z=1).E\Big[\sum_{t \in N \cap (0, T]} Z(t)\Big] \;=\; D\, T\, P(Z = 1).

Proof. Condition on NN. The sum then has finitely many terms Z(t1),…,Z(tm)Z(t_1), \ldots, Z(t_m) at fixed instants, and since ZZ is independent of NN and stationary, E[Z(tk)∣N]=P(Z=1)E[Z(t_k) \mid N] = P(Z = 1) for each kk. So the conditional expectation is m P(Z=1)=N((0,T]) P(Z=1)m\,P(Z = 1) = N((0, T])\,P(Z = 1), and its expectation is DT P(Z=1)D T\,P(Z = 1). □\square

Theorem 1 (one block). Let x1,…,xnx_1, \ldots, x_n be independent stationary signals with finite densities, f:{0,1}n→{0,1}f : \{0,1\}^n \to \{0,1\}, and y(t)=f(x1(t−τ),…,xn(t−τ))y(t) = f(x_1(t - \tau), \ldots, x_n(t - \tau)) for a fixed delay τ≥0\tau \ge 0. Then yy is stationary and

D(y)  =  ∑i=1nP ⁣(∂f∂xi(X)=1)D(xi),D(y) \;=\; \sum_{i=1}^n P\!\left(\frac{\partial f}{\partial x_i}(X) = 1\right) D(x_i),

where XX has independent coordinates with P(Xi=1)=pxiP(X_i = 1) = p_{x_i}.

Proof. The vector signal (x1,…,xn)(x_1, \ldots, x_n) is stationary because its coordinates are independent and stationary, so yy is stationary, and a shift by τ\tau changes neither the law nor the density. So take τ=0\tau = 0. By Lemma 1, with probability 1 no two inputs switch at the same instant. Then yy is constant between the transitions of the inputs, and at a transition time tt of xix_i only xix_i changes. So yy changes at tt exactly when ff takes different values at the two vectors that differ only in coordinate ii, which is ∂f∂xi(x(t))=1\frac{\partial f}{\partial x_i}(x(t)) = 1. The Boolean difference does not depend on xix_i, so its value is Zi(t)=∂f∂xi(x−i(t))Z_i(t) = \frac{\partial f}{\partial x_i}(x_{-i}(t)), a function of the other inputs only. Hence

Ny((0,T])  =  ∑i=1n∑t∈Nxi∩(0,T]Zi(t).N_y((0, T]) \;=\; \sum_{i=1}^n \sum_{t \in N_{x_i} \cap (0, T]} Z_i(t).

ZiZ_i is a stationary signal that depends only on x−ix_{-i}, so it is independent of NxiN_{x_i}. Lemma 2 gives E[Ny((0,T])]=T∑iD(xi) P(Zi=1)E[N_y((0, T])] = T \sum_i D(x_i)\, P(Z_i = 1), and P(Zi=1)=P(∂f∂xi(X)=1)P(Z_i = 1) = P(\frac{\partial f}{\partial x_i}(X) = 1) because the values of x1(t),…,xn(t)x_1(t), \ldots, x_n(t) at one instant are independent with P(xi(t)=1)=pxiP(x_i(t) = 1) = p_{x_i}. Divide by TT. □\square

Lemma 3 (gate rules). For a gate y=kind(z1,…,zk)y = \mathrm{kind}(z_1, \ldots, z_k) with independent 0-1 inputs, P(zl=1)=qlP(z_l = 1) = q_l, the probability of ∂y/∂zj\partial y / \partial z_j is ∏l≠jql\prod_{l \ne j} q_l for AND and NAND, ∏l≠j(1−ql)\prod_{l \ne j} (1 - q_l) for OR and NOR, and 1 for XOR, XNOR, BUF and NOT, which is line L6.

Proof. AND∣zj=1=∏l≠jzl\mathrm{AND}|_{z_j = 1} = \prod_{l \ne j} z_l and AND∣zj=0=0\mathrm{AND}|_{z_j = 0} = 0, so the difference is ∏l≠jzl\prod_{l \ne j} z_l. For OR the cofactors are 1 and ⋁l≠jzl\bigvee_{l \ne j} z_l, whose XOR is ∏l≠jzˉl\prod_{l \ne j} \bar z_l. For XOR the cofactors are complements of each other, so the difference is 1, and the same holds for BUF and NOT. Since fˉ∣x=1⊕fˉ∣x=0=f∣x=1⊕f∣x=0\bar f|_{x = 1} \oplus \bar f|_{x = 0} = f|_{x = 1} \oplus f|_{x = 0}, the complemented gates have the same differences. The probabilities follow from the independence of the zlz_l. □\square

Theorem 2 (the pass is exact without reconvergence). Suppose the primary inputs are independent stationary signals with finite densities, every gate output follows its function with a fixed delay, and for every gate the supports of its input pins are pairwise disjoint (this holds in every fanout-free circuit). Then TRANSITION-DENSITY returns P[y]=P(y(t)=1)P[y] = P(y(t) = 1) and D[y]=D(y)D[y] = D(y) for every node yy.

Proof. By induction in topological order we show that each node yy is a stationary signal that is a function of the primary input signals in its support S(y)S(y) (with time shifts), and that P[y]P[y] and D[y]D[y] are exact. For a primary input this is line L1. For a gate y=kind(z1,…,zk)y = \mathrm{kind}(z_1, \ldots, z_k), the signals zjz_j are functions of the disjoint groups (xi)i∈S(zj)(x_i)_{i \in S(z_j)} of independent signals, so they are independent, and each is stationary with a finite density by the induction hypothesis. The node yy is kind(z1,…,zk)\mathrm{kind}(z_1, \ldots, z_k) with a fixed delay, so it is a function of the inputs in S(y)=⋃jS(zj)S(y) = \bigcup_j S(z_j), and Theorem 1 applies with z1,…,zkz_1, \ldots, z_k as the inputs. With the values at one instant independent, line L3 gives P(y=1)P(y = 1) (the numeric mode of signal probability propagation is exact for independent gate inputs), Lemma 3 shows that line L6 gives P(∂y/∂zj)P(\partial y / \partial z_j), and lines L4 to L7 then compute the sum of Theorem 1 with the exact D(zj)D(z_j). □\square

Reconvergence. For u=AND(a,b)u = \mathrm{AND}(a, b), v=AND(a,c)v = \mathrm{AND}(a, c), y=OR(u,v)y = \mathrm{OR}(u, v) with all p=1/2p = 1/2 and D=1D = 1, Theorem 1 applied to y=a(b∨c)y = a(b \lor c) as one block gives D(y)=34+14+14=54D(y) = \frac{3}{4} + \frac{1}{4} + \frac{1}{4} = \frac{5}{4}, which is the true density. The pass gives 34D(u)+34D(v)=32\frac{3}{4} D(u) + \frac{3}{4} D(v) = \frac{3}{2}. The step that fails is the independence of uu and vv in Theorem 1 at the gate yy: both depend on aa, and they switch together at every transition of aa that both pass, so Lemma 1 fails for them as well.

What is not proved. For synchronous inputs that all switch at a clock edge, Lemma 1 fails, and the formula is not the zero-delay activity per cycle. For an AND gate with fresh uniform inputs every cycle the formula gives 1/21/2 per cycle and the zero-delay output changes in 3/83/8 of the cycles. The gap is the expected number of glitches that the formula assumes when the two input transitions are separated in time.

Complexity

A gate with kk inputs costs O(k)O(k) at line L3 and O(k)O(k) for each of its kk pins at line L6, so the pass costs O(G+PK)O(G + P K) arithmetic operations. With prefix and suffix products of P[zl]P[z_l] and 1−P[zl]1 - P[z_l], line L6 costs O(1)O(1) per pin and the pass costs O(G+P)O(G + P). The space is one probability and one density per node, O(G+n)O(G + n). This is the same cost as one zero-delay logic simulation of one vector, while a simulation-based estimate needs many vectors.

Applying the rule to whole functions in place of gates is exact on every circuit with independent inputs, but it needs P(∂y/∂xi)P(\partial y / \partial x_i) for every node and input. That is a signal probability, which is #P-hard in general. With BDDs it costs time linear in the size of the BDD of ∂y/∂xi\partial y / \partial x_i, which can be exponential in nn.

Properties

  • What it measures. D(y)D(y) counts all transitions, rising and falling, including glitches. The dynamic power of a node with load CC is 12CVDD2D(y)\frac{1}{2} C V_{DD}^2 D(y), because a full charge and discharge, two transitions, costs CVDD2C V_{DD}^2.
  • Continuous time. The density is a rate per unit time, not per clock cycle. For a synchronous circuit with clock frequency ff, the switching activity per cycle is D(y)/fD(y) / f if the assumptions hold.
  • Linear in the input densities. For fixed probabilities, every D[y]D[y] is a linear function of the input densities with nonnegative coefficients. So the share of each input in the activity of a node is explicit, and doubling all input densities doubles all node densities.
  • Delay does not enter. The algorithm uses no gate delays. In the model a delay shifts the transitions of a signal but does not change their number.
  • Glitches through a gate. When the inputs of a gate switch at different times, each passing input transition is counted, so the density includes the glitches that come from skew between independent inputs.

Variants and improvements

  • Blocks in place of gates. Najm's program, DENSIM, applies the rule to groups of gates, computing the Boolean difference probabilities of each block with BDDs. Larger blocks absorb local reconvergence, at a cost that grows with the block size.
  • Low-pass filtering. A real gate with inertial delay does not pass a pulse shorter than its delay (see inertial and transport delay). Najm (1994) modified the rule to filter such pulses, which lowers the overestimate on deep logic.
  • Correlation coefficients. Add pairwise correlation terms between gate inputs to correct part of the error from reconvergent fanout. This is a heuristic without a general bound.
  • Exact zero-delay activity. If the question is the activity per clock cycle with zero delay, compute P(y(t)≠y(t+1))P(y(t) \ne y(t+1)) symbolically, as in BDD-based switching activity estimation.
  • Statistical estimates. Monte Carlo power estimation simulates the circuit with a real delay model and stops at a stated accuracy, at a much higher cost per node.

When to use it

Use transition density for fast, vectorless activity estimates on large gate-level netlists, for example to find the most active nets early, to compare design options, or to give an activity number to every net when no simulation testbench exists. It suits circuits with mostly independent inputs and limited reconvergence. When a number must be accurate within a known error, use simulation with a stopping rule, and use the density result as a starting point or a sanity check.

Pitfalls

  • Simultaneous switching. The rule assumes that two inputs never switch at the same instant. In a synchronous circuit all register outputs switch near the clock edge. For an AND gate with fresh random inputs each cycle (P=1/2P = 1/2, D=1/2D = 1/2 per cycle), the rule gives 1/21/2 transition per cycle, while the zero-delay output changes only in 3/83/8 of the cycles. If one input arrives a little later, the true count with that delay is again 1/21/2: the difference is the glitch that the skew creates.
  • Reconvergent fanout. The gate inputs then depend on each other and the result can be too high or too low. For y=AND(a,NOT(a))y = \mathrm{AND}(a, \mathrm{NOT}(a)) the rule gives D(y)=D(a)D(y) = D(a), while the output is 0 with zero delay. With a delay on the inverter, each rising edge of aa makes a pulse of two transitions, so D(a)D(a) is right for that delay model and wrong for a fast inverter that filters the pulse.
  • Correlated inputs. Inputs from a counter, a shift register or the same bus are not independent, and the result can be far off.
  • Densities are not probabilities. DD is a rate with a unit, not a number between 0 and 1. Mixing per-cycle and per-second values is a common unit error.
  • Glitches that do not exist. In deep logic the rule passes every short pulse, while real gates filter many of them, so the estimate tends to be too high there.

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.

netlist.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the pr1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate-level combinational netlists for the power estimation pages.

A circuit has named primary inputs and gates in topological order. Each gate
has a kind (BUF, NOT, AND, OR, NAND, NOR, XOR, XNOR), a list of fanin names
and an integer delay (1 by default). A node is a primary input or a gate.

This module holds the circuit model, plain evaluation of one input vector,
structural queries (fanout, support, reconvergence) and a step simulation of
the transport delay model. It holds no estimation algorithm.
"""

from __future__ import annotations

import random
from typing import Iterable, Optional, Sequence

KINDS = ("BUF", "NOT", "AND", "OR", "NAND", "NOR", "XOR", "XNOR")


def gate_value(kind: str, bits: Sequence[int]) -> int:
    """Value of one gate on 0-1 inputs."""
    if kind == "BUF":
        return bits[0]
    if kind == "NOT":
        return 1 - bits[0]
    if kind in ("AND", "NAND"):
        v = int(all(bits))
    elif kind in ("OR", "NOR"):
        v = int(any(bits))
    elif kind in ("XOR", "XNOR"):
        v = sum(bits) % 2
    else:
        raise ValueError(f"unknown gate kind {kind}")
    return 1 - v if kind in ("NAND", "NOR", "XNOR") else v


class Circuit:
    """Inputs, then gates (name, kind, fanins) in topological order."""

    def __init__(
        self,
        inputs: Sequence[str],
        gates: Sequence[tuple[str, str, Sequence[str]]],
        delay: Optional[dict[str, int]] = None,
    ) -> None:
        self.inputs = list(inputs)
        self.gates = [(g, k, list(f)) for g, k, f in gates]
        seen = set(self.inputs)
        if len(seen) != len(self.inputs):
            raise ValueError("repeated input name")
        for g, k, fins in self.gates:
            if k not in KINDS:
                raise ValueError(f"unknown gate kind {k}")
            if g in seen:
                raise ValueError(f"repeated node name {g}")
            if not fins or (k in ("BUF", "NOT") and len(fins) != 1):
                raise ValueError(f"bad fanin count at {g}")
            for f in fins:
                if f not in seen:
                    raise ValueError(f"{g} reads {f} before it is defined")
            seen.add(g)
        self.nodes = self.inputs + [g for g, _, _ in self.gates]
        self.delay = {g: 1 for g, _, _ in self.gates}
        if delay:
            self.delay.update(delay)

    def evaluate(self, x: Sequence[int]) -> dict[str, int]:
        """Values of all nodes for the input vector x (in the order of self.inputs)."""
        val = dict(zip(self.inputs, x))
        for g, k, fins in self.gates:
            val[g] = gate_value(k, [val[f] for f in fins])
        return val

    def fanout(self) -> dict[str, int]:
        """Number of gate input pins that each node drives."""
        cnt = {v: 0 for v in self.nodes}
        for _, _, fins in self.gates:
            for f in fins:
                cnt[f] += 1
        return cnt

    def is_fanout_free(self) -> bool:
        return all(c <= 1 for c in self.fanout().values())

    def support(self) -> dict[str, frozenset[str]]:
        """The primary inputs in the transitive fanin of each node."""
        sup: dict[str, frozenset[str]] = {x: frozenset([x]) for x in self.inputs}
        for g, _, fins in self.gates:
            sup[g] = frozenset().union(*(sup[f] for f in fins))
        return sup

    def has_reconvergence(self) -> bool:
        """True when some gate has two fanin pins whose supports meet."""
        sup = self.support()
        for _, _, fins in self.gates:
            for i in range(len(fins)):
                for j in range(i + 1, len(fins)):
                    if sup[fins[i]] & sup[fins[j]]:
                        return True
        return False

    def arrival(self) -> dict[str, int]:
        """Latest time at which each node can change after the inputs change at time 0."""
        t = {x: 0 for x in self.inputs}
        for g, _, fins in self.gates:
            t[g] = self.delay[g] + max(t[f] for f in fins)
        return t


def waveforms(c: Circuit, x: Sequence[int], y: Sequence[int]) -> dict[str, list[int]]:
    """Transport delay simulation: the inputs change from x to y at time 0.

    Returns, for each node, its values at times -1, 0, 1, ..., T, where T is the
    largest arrival time. A gate with delay d has at time t the value of its
    function on the values of its fanins at time t - d. Before time 0 every
    node holds its value under x.
    """
    old = c.evaluate(x)
    horizon = max(c.arrival().values())
    wave = {v: [old[v]] for v in c.nodes}  # index 0 is time -1
    for xi, a, b in zip(c.inputs, x, y):
        wave[xi] = [a] + [b] * (horizon + 1)
    for g, k, fins in c.gates:
        d = c.delay[g]
        w = [old[g]]
        for t in range(horizon + 1):
            s = t - d
            w.append(gate_value(k, [wave[f][s + 1] if s >= -1 else old[f] for f in fins]))
        wave[g] = w
    return wave


def transitions(c: Circuit, x: Sequence[int], y: Sequence[int], delay_model: str = "zero") -> dict[str, int]:
    """Number of value changes of each node when the inputs change from x to y.

    delay_model "zero": a node changes at most once, when its value under x and y differ.
    delay_model "transport": the step simulation of waveforms(), which counts glitches.
    """
    if delay_model == "zero":
        a, b = c.evaluate(x), c.evaluate(y)
        return {v: int(a[v] != b[v]) for v in c.nodes}
    if delay_model == "transport":
        w = waveforms(c, x, y)
        return {v: sum(1 for t in range(1, len(s)) if s[t] != s[t - 1]) for v, s in w.items()}
    raise ValueError(delay_model)


def random_circuit(
    rng: random.Random,
    n_inputs: int,
    n_gates: int,
    kinds: Iterable[str] = KINDS,
    max_fanin: int = 3,
    fanout_free: bool = False,
    max_delay: int = 1,
) -> Circuit:
    """A random circuit. With fanout_free, every node drives at most one gate pin."""
    kinds = list(kinds)
    inputs = [f"x{i}" for i in range(n_inputs)]
    free = list(inputs)
    names = list(inputs)
    gates = []
    delay = {}
    for j in range(n_gates):
        pool = free if fanout_free else names
        if not pool:
            break
        k = rng.choice(kinds)
        if k in ("BUF", "NOT"):
            m = 1
        else:
            m = min(len(pool), rng.randint(2, max_fanin))
            if m < 2:
                k = rng.choice(["BUF", "NOT"])
                m = 1
        fins = rng.sample(pool, m)
        g = f"g{j}"
        gates.append((g, k, fins))
        delay[g] = rng.randint(1, max_delay)
        if fanout_free:
            for f in fins:
                free.remove(f)
            free.append(g)
        names.append(g)
    return Circuit(inputs, gates, delay)
transition_density.py 80 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transition-density/. The authors are listed in prov/G6GC4V.jsonl.
"""Transition density propagation (Najm 1993).

Each primary input x is a 0-1 signal in time with equilibrium probability
p[x] = P(x = 1) and transition density d[x] (mean number of transitions per
unit time). The inputs are independent. transition_densities(c, p, d) walks the
gates of a netlist.Circuit in topological order and sets, for y = f(z_1..z_k),

    P(y) by the signal probability formula for independent fanins,
    D(y) = sum_j P(df/dz_j) D(z_j),

where df/dz_j = f(z_j = 0) XOR f(z_j = 1) is the Boolean difference. The
result is exact when the fanins of every gate depend on disjoint sets of
inputs (for example in a fanout-free circuit) and no two inputs switch at
the same instant. Values are Fractions when the inputs are.
"""

from __future__ import annotations

from fractions import Fraction
from typing import Mapping, Sequence


def gate_probability(kind: str, q: Sequence[Fraction]) -> Fraction:
    """P(output = 1) for independent fanins with P(fanin j = 1) = q[j]."""
    if kind in ("AND", "NAND"):
        r = Fraction(1)
        for v in q:
            r *= v
    elif kind in ("OR", "NOR"):
        r = Fraction(1)
        for v in q:
            r *= 1 - v
        r = 1 - r
    elif kind in ("XOR", "XNOR"):
        r = Fraction(0)
        for v in q:
            r = r + v - 2 * r * v
    elif kind in ("BUF", "NOT"):
        r = Fraction(q[0])
    else:
        raise ValueError(kind)
    return 1 - r if kind in ("NAND", "NOR", "XNOR", "NOT") else r


def boolean_difference_probability(kind: str, q: Sequence[Fraction], j: int) -> Fraction:
    """P(df/dz_j = 1) for one gate, with independent fanins.

    AND and NAND are sensitive to pin j when every other pin is 1, OR and NOR
    when every other pin is 0, and XOR, XNOR, BUF and NOT always.
    """
    r = Fraction(1)
    if kind in ("AND", "NAND"):
        for k, v in enumerate(q):
            if k != j:
                r *= v
    elif kind in ("OR", "NOR"):
        for k, v in enumerate(q):
            if k != j:
                r *= 1 - v
    elif kind not in ("XOR", "XNOR", "BUF", "NOT"):
        raise ValueError(kind)
    return r


def transition_densities(c, p: Mapping[str, Fraction], d: Mapping[str, Fraction]):
    """Return (P, D): the probability and the transition density of every node."""
    P: dict[str, Fraction] = {}
    D: dict[str, Fraction] = {}
    for x in c.inputs:
        P[x], D[x] = Fraction(p[x]), Fraction(d[x])  # @line L1
    for y, kind, fins in c.gates:  # @line L2
        q = [P[z] for z in fins]
        P[y] = gate_probability(kind, q)  # @line L3
        D[y] = Fraction(0)  # @line L4
        for j, z in enumerate(fins):  # @line L5
            b = boolean_difference_probability(kind, q, j)  # @line L6
            D[y] += b * D[z]  # @line L7
    return P, D  # @line L8
test_transition_density.py 212 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transition-density/. The authors are listed in prov/G6GC4V.jsonl.

import itertools
import random
from fractions import Fraction

from netlist import KINDS, Circuit, random_circuit, transitions
from transition_density import boolean_difference_probability, gate_probability, transition_densities

HALF = Fraction(1, 2)

# y = ab + ac, the reconvergent example of the page.
RECONV = Circuit(["a", "b", "c"], [("u", "AND", ["a", "b"]), ("v", "AND", ["a", "c"]), ("y", "OR", ["u", "v"])])


def weight(c, p, x):
    w = Fraction(1)
    for name, b in zip(c.inputs, x):
        w *= p[name] if b else 1 - p[name]
    return w


def flip(x, i):
    y = list(x)
    y[i] = 1 - y[i]
    return tuple(y)


def global_densities(c, p, d):
    """D(y) = sum_i P(dy/dx_i) D(x_i) with the Boolean differences of whole node functions, by enumeration."""
    out = {v: Fraction(0) for v in c.nodes}
    for x in itertools.product((0, 1), repeat=len(c.inputs)):
        w = weight(c, p, x)
        if w == 0:
            continue
        a = c.evaluate(x)
        for i, name in enumerate(c.inputs):
            b = c.evaluate(flip(x, i))
            for v in c.nodes:
                if a[v] != b[v]:
                    out[v] += w * d[name]
    return out


class Chain:
    """Inputs as one Markov chain: each step picks input i with probability w[i]
    and flips it with probability up[i] if it is 0 and down[i] if it is 1."""

    def __init__(self, rng, n):
        self.w = [Fraction(1, n + 1)] * n
        self.up = [Fraction(rng.randint(1, 6), 6) for _ in range(n)]
        self.down = [Fraction(rng.randint(1, 6), 6) for _ in range(n)]

    def marginal(self, i):
        return self.up[i] / (self.up[i] + self.down[i])

    def rate(self, i):
        return self.w[i] * 2 * self.up[i] * self.down[i] / (self.up[i] + self.down[i])

    def flip_prob(self, i, bit):
        return self.w[i] * (self.down[i] if bit else self.up[i])


def markov_toggles(c, ch):
    """Expected node transitions per step of the chain, from the product distribution, by enumeration."""
    p = {name: ch.marginal(i) for i, name in enumerate(c.inputs)}
    out = {v: Fraction(0) for v in c.nodes}
    for x in itertools.product((0, 1), repeat=len(c.inputs)):
        w = weight(c, p, x)
        a = c.evaluate(x)
        for i in range(len(c.inputs)):
            b = c.evaluate(flip(x, i))
            t = w * ch.flip_prob(i, x[i])
            for v in c.nodes:
                if a[v] != b[v]:
                    out[v] += t
    return out


def chain_inputs(c, ch):
    p = {name: ch.marginal(i) for i, name in enumerate(c.inputs)}
    d = {name: ch.rate(i) for i, name in enumerate(c.inputs)}
    return p, d


def test_gate_rules_against_truth_tables():
    rng = random.Random(1)
    for kind in KINDS:
        for k in ([1] if kind in ("BUF", "NOT") else [2, 3, 4]):
            c = Circuit([f"i{j}" for j in range(k)], [("o", kind, [f"i{j}" for j in range(k)])])
            for _ in range(5):
                p = {x: Fraction(rng.randint(0, 6), 6) for x in c.inputs}
                d = {x: Fraction(rng.randint(0, 9), 3) for x in c.inputs}
                q = [p[x] for x in c.inputs]
                for j in range(k):
                    one = {x: Fraction(int(x == c.inputs[j])) for x in c.inputs}
                    assert boolean_difference_probability(kind, q, j) == global_densities(c, p, one)["o"]
                P, D = transition_densities(c, p, d)
                assert D["o"] == global_densities(c, p, d)["o"]
                assert P["o"] == gate_probability(kind, q)


def test_product_distribution_is_stationary():
    rng = random.Random(2)
    for n in range(1, 5):
        ch = Chain(rng, n)
        names = [f"x{i}" for i in range(n)]
        c = Circuit(names, [])
        p = {name: ch.marginal(i) for i, name in enumerate(names)}
        states = list(itertools.product((0, 1), repeat=n))
        pi = {x: weight(c, p, x) for x in states}
        nxt = {x: Fraction(0) for x in states}
        for x in states:
            stay = Fraction(1)
            for i in range(n):
                t = ch.flip_prob(i, x[i])
                nxt[flip(x, i)] += pi[x] * t
                stay -= t
            nxt[x] += pi[x] * stay
        assert nxt == pi
        # The input rates of the chain are the transition densities D(x_i).
        for i, name in enumerate(names):
            assert markov_toggles(c, ch)[name] == ch.rate(i)


def test_page_fanout_free_example():
    c = Circuit(["a", "b", "c"], [("u", "AND", ["a", "b"]), ("y", "OR", ["u", "c"])])
    p = {"a": HALF, "b": Fraction(1, 4), "c": HALF}
    d = {"a": Fraction(2), "b": Fraction(1), "c": Fraction(4)}
    P, D = transition_densities(c, p, d)
    assert (P["u"], D["u"]) == (Fraction(1, 8), 1)
    assert (P["y"], D["y"]) == (Fraction(9, 16), 4)
    assert D == global_densities(c, p, d)


def test_page_reconvergent_example():
    p = {"a": HALF, "b": HALF, "c": HALF}
    d = {"a": Fraction(1), "b": Fraction(1), "c": Fraction(1)}
    P, D = transition_densities(RECONV, p, d)
    assert D["u"] == D["v"] == 1
    assert D["y"] == Fraction(3, 2)
    assert P["y"] == Fraction(7, 16)
    assert global_densities(RECONV, p, d)["y"] == Fraction(5, 4)


def test_exact_without_reconvergence_against_markov_chain():
    rng = random.Random(3)
    count = 0
    for _ in range(250):
        c = random_circuit(rng, rng.randint(1, 6), rng.randint(1, 8), fanout_free=rng.random() < 0.5)
        if c.has_reconvergence():
            continue
        count += 1
        ch = Chain(rng, len(c.inputs))
        p, d = chain_inputs(c, ch)
        _, D = transition_densities(c, p, d)
        assert D == markov_toggles(c, ch)
    assert count > 80


def test_global_formula_matches_markov_chain_on_every_circuit():
    rng = random.Random(4)
    for _ in range(100):
        c = random_circuit(rng, rng.randint(1, 5), rng.randint(1, 8))
        ch = Chain(rng, len(c.inputs))
        p, d = chain_inputs(c, ch)
        assert global_densities(c, p, d) == markov_toggles(c, ch)


def test_propagation_is_wrong_under_reconvergence():
    rng = random.Random(5)
    wrong = 0
    for _ in range(300):
        c = random_circuit(rng, rng.randint(2, 5), rng.randint(3, 8))
        if not c.has_reconvergence():
            continue
        ch = Chain(rng, len(c.inputs))
        p, d = chain_inputs(c, ch)
        if transition_densities(c, p, d)[1] != markov_toggles(c, ch):
            wrong += 1
    assert wrong > 50


def per_cycle(c, delay_model):
    """Expected transitions per cycle for fresh uniform vectors each cycle, over all pairs."""
    n = len(c.inputs)
    tot = {v: Fraction(0) for v in c.nodes}
    for x in itertools.product((0, 1), repeat=n):
        for y in itertools.product((0, 1), repeat=n):
            for v, k in transitions(c, x, y, delay_model).items():
                tot[v] += Fraction(k, 4**n)
    return tot


def test_simultaneous_switching():
    # Fresh uniform vectors every cycle: P = 1/2 and D = 1/2 per cycle for each input.
    same_time = Circuit(["a", "b"], [("y", "AND", ["a", "b"])])
    skewed = Circuit(["a", "b"], [("bd", "BUF", ["b"]), ("y", "AND", ["a", "bd"])])
    p = {"a": HALF, "b": HALF}
    _, D = transition_densities(same_time, p, p)
    assert D["y"] == HALF
    assert per_cycle(same_time, "zero")["y"] == Fraction(3, 8)
    assert per_cycle(skewed, "transport")["y"] == HALF


def test_glitch_of_a_and_not_a():
    c = Circuit(["a"], [("n", "NOT", ["a"]), ("y", "AND", ["a", "n"])])
    _, D = transition_densities(c, {"a": HALF}, {"a": HALF})
    assert D["y"] == HALF
    assert per_cycle(c, "zero")["y"] == 0
    assert per_cycle(c, "transport")["y"] == HALF

History

Najm introduced the transition density at the Design Automation Conference in 1991 and gave the full treatment in IEEE Transactions on CAD in 1993. He modeled logic signals as stationary random processes, proved the Boolean difference formula for a module with independent inputs, and propagated densities through a circuit by blocks whose Boolean differences were computed with BDDs. In 1994 he added a low-pass filter for gates with inertial delay, and his survey of power estimation in the same year placed the method next to simulation, signal probability and BDD-based methods.

References

  1. Farid N. Najm, Transition density, a new measure of activity in digital circuits, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 12(2), 310 to 323, February 1993, the definition of the transition density and equilibrium probability, the theorem that gives the density at the output of a Boolean module with independent inputs, and the propagation algorithm
  2. Farid N. Najm, Transition density, a stochastic measure of activity in digital circuits, Proceedings of the 28th ACM/IEEE Design Automation Conference, 644 to 649, June 1991, the first presentation of the measure and of its propagation
  3. Farid N. Najm, A survey of power estimation techniques in VLSI circuits, IEEE Transactions on VLSI Systems 2(4), 446 to 455, December 1994, the section on probabilistic techniques, which compares transition density with signal probability and BDD methods
  4. Farid N. Najm, Low-pass filter for computing the transition density in digital circuits, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 13(9), 1123 to 1131, September 1994, the filtering of short pulses by gates with inertial delay

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.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example