Algorithm Search⌘K

Algorithmcore

Signal probability propagation

Also called Parker-McCluskey signal probability, probability polynomial with exponent suppression.

Compute P(signal = 1) for each node from input probabilities by gate formulas. Numbers are exact only without reconvergence; Parker-McCluskey polynomials are exact but can be exponential.

Time
O(G + P) worst
Space
O(G + n) extra
Where
G = the number of gates; P = the number of gate input pins; n = the number of primary inputs
Properties
deterministicnot exactofflineiterative
Origin
Kenneth P. Parker, Edward J. McCluskey, 1975

Signal probability propagation computes, for each node yy of a combinational circuit, the signal probability P(y=1)P(y = 1), given the probability that each primary input is 1 and assuming that the primary inputs are independent. It walks the gates in topological order and applies one formula per gate, for example P(y)=P(a)P(b)P(y) = P(a) P(b) for y=AND(a,b)y = \mathrm{AND}(a, b). With plain numbers the formulas assume that the inputs of each gate are independent, so the result is exact on circuits without reconvergent fanout and can be wrong otherwise. Parker and McCluskey (1975) carry each probability as a polynomial in the input probabilities and replace xkx^k by xx after each product. That version is exact on every circuit, but the polynomials can have 2n2^n terms, and no method can avoid such a cost in general: exact signal probability is #P-hard. Signal probabilities are the base of switching activity estimates for power, of transition density, and of COP testability for random test.

In plain words

Each input wire of a circuit is on with some chance, and the inputs do not influence each other. The question is how often each wire inside the circuit is on.

For one gate this is easy if its inputs are unrelated. An AND gate is on only when both inputs are on, so you multiply the two chances. An inverter turns the chance into one minus the chance. So you go through the gates from the inputs to the outputs and fill in a number for each wire.

The trouble starts when one input feeds two paths that meet again. Then the two inputs of the meeting gate share a cause, and multiplying their chances is wrong. The exact method keeps a formula in the input chances instead of a number. When one input chance appears twice in a product, it keeps it once.

The problem

The input is a combinational circuit CC with primary inputs x1,…,xnx_1, \ldots, x_n and gates g1,…,gGg_1, \ldots, g_G in topological order, each gate being BUF, NOT, AND, OR, NAND, NOR, XOR or XNOR, and a probability pi=P(xi=1)p_i = P(x_i = 1) for each input. The inputs are random variables X1,…,XnX_1, \ldots, X_n, mutually independent, with P(Xi=1)=piP(X_i = 1) = p_i. Each node yy computes a Boolean function fyf_y of the inputs. The output is

P(y)  =  P(fy(X)=1)  =  ∑x∈{0,1}nfy(x)∏i=1npixi(1−pi)1−xiP(y) \;=\; P\big(f_y(X) = 1\big) \;=\; \sum_{x \in \{0,1\}^n} f_y(x) \prod_{i=1}^{n} p_i^{x_i} (1 - p_i)^{1 - x_i}

for every node yy. The support S(y)S(y) is the set of primary inputs in the transitive fanin of yy. A gate has reconvergent fanout when two of its input pins have supports that meet; a circuit in which every node drives at most one gate pin (a fanout-free circuit) has none.

The algorithm

The algorithm is one pass in topological order. It has two modes that differ only in the type of the values: numbers, or polynomials over the input probabilities with exponent suppression.

  1. SIGNAL-PROBABILITIES(C, p, mode)
  2. 1for each primary input x_i do
  3. 2if mode = numeric then P[x_i] ← p_i else P[x_i] ← the polynomial x_i
  4. 3for each gate y = kind(z_1, …, z_k) in topological order do
  5. 4q_j ← P[z_j] for j = 1, …, k
  6. 5if kind ∈ {AND, NAND} then r ← q_1 · q_2 · … · q_k
  7. 6if kind ∈ {OR, NOR} then r ← 1 − (1 − q_1)(1 − q_2) … (1 − q_k)
  8. 7if kind ∈ {XOR, XNOR} then r ← q_1, then r ← r + q_j − 2 r q_j for j = 2, …, k
  9. 8if kind ∈ {BUF, NOT} then r ← q_1
  10. 9if kind ∈ {NAND, NOR, XNOR, NOT} then r ← 1 − r
  11. 10P[y] ← r
  12. 11if mode = polynomial then
  13. 12for each node y do P[y] ← the value of P[y] at x_i = p_i for all i
  14. 13return P

In the polynomial mode every product of lines L5 to L7 is followed by exponent suppression: each monomial c∏ixieic \prod_i x_i^{e_i} becomes c∏i:ei≥1xic \prod_{i : e_i \ge 1} x_i. A polynomial is then a map from sets of inputs to integer coefficients, and the product of two monomials is the union of their sets. Line L12 evaluates the final polynomials. In the numeric mode the same formulas run on numbers, with no suppression.

Example

A fanout-free circuit. Take u=AND(a,b)u = \mathrm{AND}(a, b), w=NOT(c)w = \mathrm{NOT}(c), y=OR(u,w)y = \mathrm{OR}(u, w) and z=XOR(y,d)z = \mathrm{XOR}(y, d), with pa=1/2p_a = 1/2, pb=1/4p_b = 1/4, pc=3/4p_c = 3/4 and pd=1/3p_d = 1/3. Each node drives one pin, so the numeric mode is exact.

node formula value
uu papbp_a p_b 1/81/8
ww 1−pc1 - p_c 1/41/4
yy 1−(1−1/8)(1−1/4)1 - (1 - 1/8)(1 - 1/4) 11/3211/32
zz 11/32+1/3−2⋅11/32⋅1/311/32 + 1/3 - 2 \cdot 11/32 \cdot 1/3 43/9643/96

Summing the input probabilities over the 242^4 vectors on which z=1z = 1 gives the same 43/9643/96.

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), so y=ab∨acy = ab \lor ac, and let every input have probability 1/21/2. The input aa reaches yy through both uu and vv.

node numeric mode polynomial mode
uu 1/41/4 abab
vv 1/41/4 acac
yy 1−(3/4)2=7/161 - (3/4)^2 = 7/16 1−(1−ab)(1−ac)=ab+ac−a2bc→ab+ac−abc1 - (1 - ab)(1 - ac) = ab + ac - a^2 bc \to ab + ac - abc

The polynomial evaluates to 1/4+1/4−1/8=3/81/4 + 1/4 - 1/8 = 3/8, which is right: y=1y = 1 exactly when a=1a = 1 and b∨c=1b \lor c = 1, with probability 1/2⋅3/41/2 \cdot 3/4. The numeric mode gives 7/167/16, too high by 1/161/16, because it treats uu and vv as independent when both need a=1a = 1. The extreme case is y=AND(a,NOT(a))y = \mathrm{AND}(a, \mathrm{NOT}(a)): the true value is 0, and the numeric mode gives pa(1−pa)p_a (1 - p_a).

Correctness

The polynomial mode is exact on every circuit. Each gate formula of lines L5 to L9 is a polynomial identity on 0 and 1 values, so the polynomial of a node agrees with its Boolean function at every corner of the cube {0,1}n\{0,1\}^n, and suppression keeps the values at the corners. A polynomial with no exponent above 1 is fixed by its corner values, and the function p↦P(fy(X)=1)p \mapsto P(f_y(X) = 1) is such a polynomial with the same corner values. So they are the same polynomial.

The numeric mode is exact when no gate has reconvergent fanout. By induction in topological order, each node is a function of the inputs in its support. The fanins of a gate then depend on disjoint sets of independent inputs, so they are independent, and each gate formula is the probability law of its gate for independent inputs. With reconvergent fanout the fanins can be dependent, and the example above shows that the result can then be wrong.

Exact signal probability is #P-hard, so the exponential worst case of the polynomial mode is expected. A CNF formula FF over nn variables becomes a circuit with one OR gate per clause and one AND gate over the clauses. With every pi=1/2p_i = 1/2, P(output)=#F/2nP(\text{output}) = \#F / 2^n, so an exact signal probability gives the number of models of FF, which is the #P-complete model counting problem (Valiant 1979). The full proof gives the details of the three results.

Proof: The polynomial mode is exact, the numeric mode is exact without reconvergence, and exact signal probability isfull

The inputs X1,…,XnX_1, \ldots, X_n are independent with P(Xi=1)=piP(X_i = 1) = p_i. For a function f:{0,1}n→{0,1}f : \{0,1\}^n \to \{0,1\} write

Pr⁡p(f)  =  ∑x∈{0,1}nf(x)∏i=1npixi(1−pi)1−xi,\Pr\nolimits_p(f) \;=\; \sum_{x \in \{0,1\}^n} f(x) \prod_{i=1}^n p_i^{x_i} (1 - p_i)^{1 - x_i},

which is P(f(X)=1)P(f(X) = 1). A polynomial in x1,…,xnx_1, \ldots, x_n is multilinear when no variable has an exponent above 1. The suppression σ(q)\sigma(q) of a polynomial qq replaces each monomial c∏ixieic \prod_i x_i^{e_i} by c∏i:ei≥1xic \prod_{i : e_i \ge 1} x_i and collects terms.

Lemma 1 (gate identities). For each gate kind, the formula r(q1,…,qk)r(q_1, \ldots, q_k) of lines L5 to L9 satisfies r(b1,…,bk)=kind(b1,…,bk)r(b_1, \ldots, b_k) = \mathrm{kind}(b_1, \ldots, b_k) for all b∈{0,1}kb \in \{0,1\}^k.

Proof. AND: the product of 0-1 values is 1 exactly when all are 1. OR: 1−∏j(1−bj)1 - \prod_j (1 - b_j) is 0 exactly when all bjb_j are 0. XOR: for r,b∈{0,1}r, b \in \{0,1\}, r+b−2rbr + b - 2 r b is 1 exactly when one of them is 1, so the fold of line L7 computes the parity. BUF returns b1b_1. Line L9 complements the value for NAND, NOR, XNOR and NOT, since 1−b1 - b is the complement of a 0-1 value. □\square

Lemma 2 (uniqueness). If two multilinear polynomials qq and q′q' agree on {0,1}n\{0,1\}^n, then q=q′q = q'.

Proof. Let d=q−q′d = q - q', a multilinear polynomial that is 0 on {0,1}n\{0,1\}^n, and suppose d≠0d \ne 0. Take a monomial c∏i∈Sxic \prod_{i \in S} x_i of dd with c≠0c \ne 0 and ∣S∣|S| smallest. Evaluate dd at the corner xx with xi=1x_i = 1 for i∈Si \in S and xi=0x_i = 0 otherwise. A monomial with set TT is 1 at this corner if T⊆ST \subseteq S and 0 otherwise. By the choice of SS, no monomial of dd has a set strictly inside SS, so d(x)=c≠0d(x) = c \ne 0. This contradicts d(x)=0d(x) = 0. □\square

Lemma 3 (suppression keeps corner values). For every polynomial qq and every b∈{0,1}nb \in \{0,1\}^n, σ(q)(b)=q(b)\sigma(q)(b) = q(b). Also σ(qq′)=σ(σ(q)σ(q′))\sigma(q q') = \sigma(\sigma(q) \sigma(q')) and σ(q+q′)=σ(q)+σ(q′)\sigma(q + q') = \sigma(q) + \sigma(q').

Proof. For bi∈{0,1}b_i \in \{0,1\} and e≥1e \ge 1, bie=bib_i^e = b_i. So each monomial has the same value before and after suppression. The two identities hold because suppression only lowers exponents e≥1e \ge 1 to 1, and the exponent of xix_i in a product is the sum of the exponents in the factors, which is at least 1 exactly when one of them is. □\square

Lemma 4 (the probability is the multilinear extension). Pr⁡p(f)\Pr_p(f) is a multilinear polynomial in p1,…,pnp_1, \ldots, p_n, and Pr⁡b(f)=f(b)\Pr_b(f) = f(b) for every b∈{0,1}nb \in \{0,1\}^n.

Proof. Each term f(x)∏ipixi(1−pi)1−xif(x) \prod_i p_i^{x_i} (1 - p_i)^{1 - x_i} is a product of one factor pip_i or (1−pi)(1 - p_i) for each ii, which is multilinear, and a sum of multilinear polynomials is multilinear. At a corner p=bp = b, the factor bixi(1−bi)1−xib_i^{x_i} (1 - b_i)^{1 - x_i} is 1 if xi=bix_i = b_i and 0 otherwise. So only the term x=bx = b is not zero, and it equals f(b)f(b). □\square

Theorem 1 (the polynomial mode is exact). In the polynomial mode, for every node yy, line L12 sets P[y]=Pr⁡p(fy)P[y] = \Pr_p(f_y).

Proof. We show by induction in topological order that before line L12 the value QyQ_y of P[y]P[y] is a multilinear polynomial with Qy(b)=fy(b)Q_y(b) = f_y(b) for all b∈{0,1}nb \in \{0,1\}^n. For a primary input, Qxi=xiQ_{x_i} = x_i, which is multilinear and equals the projection fxif_{x_i} on the corners. For a gate y=kind(z1,…,zk)y = \mathrm{kind}(z_1, \ldots, z_k), lines L5 to L9 combine Qz1,…,QzkQ_{z_1}, \ldots, Q_{z_k} with the formula rr and suppress after each product, so by Lemma 3 the result is σ(r(Qz1,…,Qzk))\sigma(r(Q_{z_1}, \ldots, Q_{z_k})), which is multilinear. At a corner bb, Lemma 3, the induction hypothesis and Lemma 1 give

Qy(b)=r(Qz1(b),…,Qzk(b))=r(fz1(b),…,fzk(b))=kind(fz1(b),…,fzk(b))=fy(b).Q_y(b) = r\big(Q_{z_1}(b), \ldots, Q_{z_k}(b)\big) = r\big(f_{z_1}(b), \ldots, f_{z_k}(b)\big) = \mathrm{kind}\big(f_{z_1}(b), \ldots, f_{z_k}(b)\big) = f_y(b).

So QyQ_y and Pr⁡p(fy)\Pr_p(f_y) are multilinear and agree on all corners by Lemma 4. By Lemma 2 they are the same polynomial, and line L12 evaluates it at pp. □\square

Theorem 2 (the numeric mode without reconvergence). Suppose that for every gate the supports of its input pins are pairwise disjoint. Then the numeric mode returns P[y]=Pr⁡p(fy)P[y] = \Pr_p(f_y) for every node yy.

Proof. By induction in topological order we show two facts: fyf_y depends only on the inputs in S(y)S(y), and P[y]=P(fy(X)=1)P[y] = P(f_y(X) = 1). For a primary input both are clear. For a gate y=kind(z1,…,zk)y = \mathrm{kind}(z_1, \ldots, z_k), fy=kind(fz1,…,fzk)f_y = \mathrm{kind}(f_{z_1}, \ldots, f_{z_k}) depends only on S(z1)∪⋯∪S(zk)=S(y)S(z_1) \cup \cdots \cup S(z_k) = S(y). The random variables fzj(X)f_{z_j}(X) are functions of the disjoint groups of variables (Xi)i∈S(zj)(X_i)_{i \in S(z_j)}, and the XiX_i are mutually independent, so fz1(X),…,fzk(X)f_{z_1}(X), \ldots, f_{z_k}(X) are mutually independent. For independent 0-1 variables BjB_j with P(Bj=1)=qjP(B_j = 1) = q_j:

  • AND: P(all Bj=1)=∏jqjP(\text{all } B_j = 1) = \prod_j q_j;
  • OR: P(some Bj=1)=1−∏j(1−qj)P(\text{some } B_j = 1) = 1 - \prod_j (1 - q_j);
  • XOR: if RR is the parity of B1,…,Bj−1B_1, \ldots, B_{j-1} with P(R=1)=rP(R = 1) = r, and BjB_j is independent of RR, then P(R⊕Bj=1)=r(1−qj)+(1−r)qj=r+qj−2rqjP(R \oplus B_j = 1) = r (1 - q_j) + (1 - r) q_j = r + q_j - 2 r q_j;
  • BUF and the complements of line L9 are clear.

With qj=P[zj]=P(fzj(X)=1)q_j = P[z_j] = P(f_{z_j}(X) = 1) by the induction hypothesis, line L10 sets P[y]=P(fy(X)=1)P[y] = P(f_y(X) = 1). □\square

A fanout-free circuit satisfies the hypothesis: if two input pins of a gate had a common input xix_i in their supports, there would be two paths from xix_i to the gate that end at different pins, and the node where these paths split would drive two gate pins.

Counterexample under 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) and all p=1/2p = 1/2, the numeric mode returns 1−(1−1/4)2=7/161 - (1 - 1/4)^2 = 7/16, while P(y=1)=P(a=1)P(b∨c=1)=3/8P(y = 1) = P(a = 1) P(b \lor c = 1) = 3/8. The supports {a,b}\{a, b\} and {a,c}\{a, c\} of the pins of yy meet, and the step that fails is the independence of uu and vv: P(u=v=1)=1/8≠1/16P(u = v = 1) = 1/8 \ne 1/16.

Theorem 3 (hardness). Computing Pr⁡p(fy)\Pr_p(f_y) for a circuit and rational input probabilities is #P-hard under polynomial-time reductions that make one query. It stays #P-hard with every pi=1/2p_i = 1/2 and gates AND, OR and NOT only.

Proof. Counting the satisfying assignments of a CNF formula is #P-complete (Valiant 1979). Let F=C1∧⋯∧CmF = C_1 \land \cdots \land C_m be a CNF formula over x1,…,xnx_1, \ldots, x_n. Build a circuit with inputs x1,…,xnx_1, \ldots, x_n, one NOT gate per variable that appears negated, one OR gate per clause over its literals, and one AND gate over the clause outputs. Its size is linear in the size of FF, and its output yy computes FF. With pi=1/2p_i = 1/2 for all ii, every vector has probability 2−n2^{-n}, so Pr⁡p(fy)=#F/2n\Pr_p(f_y) = \#F / 2^{n}. One query of the signal probability, and a multiplication by 2n2^n, give #F\#F. □\square

Since the number 2nPr⁡1/2(fy)2^n \Pr_{1/2}(f_y) counts the inputs that set yy to 1, it is itself a #P function, so for pi=1/2p_i = 1/2 the problem is #P-complete. The decision version, whether Pr⁡p(fy)>0\Pr_p(f_y) > 0 for probabilities in (0,1)(0, 1), is satisfiability of the circuit and is NP-complete.

Complexity

Let GG be the number of gates, PP the number of gate input pins and nn the number of primary inputs.

  • Numeric mode. Each gate with kk inputs costs O(k)O(k) arithmetic operations, so the pass costs O(G+P)O(G + P) operations and O(G+n)O(G + n) space. With exact rationals the numbers grow, so a tool uses floating point.
  • Polynomial mode. A node's polynomial has at most 2∣S(y)∣≤2n2^{|S(y)|} \le 2^n monomials, one per subset of its support. A product of two such polynomials costs at most 4n4^n monomial products, each a set union of cost O(n)O(n), so the pass costs O(P n 4n)O(P \, n \, 4^n) time in the worst case and O(G 2n)O(G \, 2^n) space. A gate with small supports costs much less: the cost depends on the supports, not on nn alone.
  • Lower bound. No polynomial-time algorithm computes exact signal probabilities unless every #P function is computable in polynomial time, which would give P=NP\mathrm{P} = \mathrm{NP}. Even deciding whether P(y)>0P(y) > 0 is NP-complete, because it is circuit satisfiability.

Properties

  • Exact cases. The numeric mode is exact without reconvergent fanout, which includes every fanout-free circuit and every circuit in which fanout stems feed only different outputs. The polynomial mode is always exact.
  • Not a bound. Under reconvergence the numeric value can be too high or too low. For y=AND(a,NOT(a))y = \mathrm{AND}(a, \mathrm{NOT}(a)) it is too high; for y=OR(a,NOT(a))y = \mathrm{OR}(a, \mathrm{NOT}(a)), which is always 1, it gives 1−pa(1−pa)1 - p_a(1 - p_a), too low.
  • Multilinear. In the polynomial mode each result is the multilinear polynomial of its function, so it gives P(y)P(y) for every choice of input probabilities, not only one. This is useful when the input probabilities change, as in weighted random pattern testing.
  • Only spatial correlation. Both modes compute probabilities at one instant. They say nothing about the correlation of a signal with itself at the next clock cycle, which switching activity needs.

Variants and improvements

  • Reduced ordered BDDs. Build the BDD of each node and compute P(y)P(y) by the weighted form of BDD satisfy-count, in time linear in the BDD size. This is exact and is fast whenever the BDDs are small; the BDD-based switching activity page uses the same traversal on pairs of vectors.
  • Cutting algorithm. Savir, Ditlow and Bardell (1984) cut all but one branch of each fanout stem, give each cut line the interval [0,1][0, 1], and propagate intervals. The result is a lower and an upper bound on each P(y)P(y), which holds on every circuit, but the interval can be wide.
  • Local correction. Keep the numeric mode, and add correlation terms only for pairs of signals that share a stem within a few levels. This is a heuristic with no general bound.
  • Bayesian networks. A circuit with independent inputs is a Bayesian network in which each gate is a deterministic node. Exact inference by junction trees is exponential only in the treewidth, and belief propagation on the circuit is the numeric mode written as messages.
  • Simulation. Simulate random vectors and count. The error falls as one over the square root of the number of vectors, as on Monte Carlo power estimation, and the cost does not depend on the reconvergence.

When to use it

Use the numeric mode as a fast first estimate, for example for power budgeting during synthesis or for the COP measure in test, and accept its error on reconvergent logic. Use the polynomial mode, or BDDs, when the circuit or the cone of interest is small and an exact value is needed, for example to check an estimator or to compute the state probabilities that set the average leakage power of a gate. For large circuits that need accuracy, use simulation with a stated confidence.

Pitfalls

  • Forgetting suppression. In the polynomial mode, a product without x2→xx^2 \to x is just the numeric mode in disguise, and it is wrong under reconvergence.
  • Suppressing too early. Suppression is valid only because the polynomial is in the primary input probabilities. Applying q2→qq^2 \to q to the probability of an internal node qq is wrong unless that node is a primary input.
  • The XOR formula. P(a⊕b)=P(a)+P(b)−2P(a)P(b)P(a \oplus b) = P(a) + P(b) - 2 P(a) P(b) needs independent aa and bb. For three inputs, fold the two-input rule, or use (1−∏j(1−2qj))/2(1 - \prod_j (1 - 2 q_j)) / 2.
  • Dependent primary inputs. Both modes assume that the primary inputs are independent. Inputs that come from the same register bank, or from a counter, are often correlated, and then even the polynomial mode is wrong.
  • Probability is not activity. A node with P(y)=1/2P(y) = 1/2 can switch every cycle or never. Power needs the switching activity, which also depends on how inputs change over time.

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)
signal_probability_propagation.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/signal-probability-propagation/. The authors are listed in prov/CC4R1Y.jsonl.
"""Signal probability propagation (Parker and McCluskey 1975).

The probability of a node is the probability that it is 1 when each primary
input x is 1 with probability p[x], independently of the others.

signal_probabilities(c, p, mode) runs the gate formulas in topological order:

- mode "numeric": one Fraction per node. Exact when no gate has two fanins
  whose supports meet (for example a fanout-free circuit), wrong in general.
- mode "polynomial": one multilinear polynomial per node in the input
  probabilities, with exponent suppression (x^k = x) after each product, then
  evaluated at p. Exact on every circuit, with up to 2^n terms per node.
"""

from __future__ import annotations

from fractions import Fraction
from typing import Mapping, Sequence, Union


class Poly:
    """A polynomial with integer coefficients over the input names, kept suppressed.

    A monomial is a frozenset of input names, so x * x = x by construction.
    """

    __slots__ = ("terms",)

    def __init__(self, terms: Mapping[frozenset[str], int]) -> None:
        self.terms = {m: c for m, c in terms.items() if c != 0}

    @staticmethod
    def var(name: str) -> "Poly":
        return Poly({frozenset([name]): 1})

    @staticmethod
    def _lift(other: Union["Poly", int]) -> "Poly":
        return other if isinstance(other, Poly) else Poly({frozenset(): other})

    def __add__(self, other: Union["Poly", int]) -> "Poly":
        r = dict(self.terms)
        for m, c in Poly._lift(other).terms.items():
            r[m] = r.get(m, 0) + c
        return Poly(r)

    __radd__ = __add__

    def __neg__(self) -> "Poly":
        return Poly({m: -c for m, c in self.terms.items()})

    def __sub__(self, other: Union["Poly", int]) -> "Poly":
        return self + (-Poly._lift(other))

    def __rsub__(self, other: int) -> "Poly":
        return Poly._lift(other) + (-self)

    def __mul__(self, other: Union["Poly", int]) -> "Poly":
        r: dict[frozenset[str], int] = {}
        for ma, ca in self.terms.items():
            for mb, cb in Poly._lift(other).terms.items():
                m = ma | mb  # exponent suppression
                r[m] = r.get(m, 0) + ca * cb
        return Poly(r)

    __rmul__ = __mul__

    def __eq__(self, other: object) -> bool:
        return isinstance(other, Poly) and self.terms == other.terms

    def __repr__(self) -> str:
        return f"Poly({self.terms!r})"

    def evaluate(self, p: Mapping[str, Fraction]) -> Fraction:
        total = Fraction(0)
        for m, c in self.terms.items():
            t = Fraction(c)
            for x in m:
                t *= p[x]
            total += t
        return total


Value = Union[Fraction, Poly]


def gate_formula(kind: str, q: Sequence[Value]) -> Value:
    """P(output = 1) from P(input = 1) = q, by the formulas for independent gate inputs."""
    if kind in ("AND", "NAND"):
        r = q[0]
        for v in q[1:]:
            r = r * v  # @line L5
    elif kind in ("OR", "NOR"):
        r = 1 - q[0]
        for v in q[1:]:
            r = r * (1 - v)
        r = 1 - r  # @line L6
    elif kind in ("XOR", "XNOR"):
        r = q[0]
        for v in q[1:]:
            r = r + v - 2 * r * v  # @line L7
    elif kind in ("BUF", "NOT"):
        r = q[0]  # @line L8
    else:
        raise ValueError(kind)
    if kind in ("NAND", "NOR", "XNOR", "NOT"):
        r = 1 - r  # @line L9
    return r


def signal_probabilities(c, p: Mapping[str, Fraction], mode: str = "numeric") -> dict[str, Fraction]:
    """P(node = 1) for every node of the netlist.Circuit c."""
    if mode not in ("numeric", "polynomial"):
        raise ValueError(mode)
    val: dict[str, Value] = {}
    for x in c.inputs:  # @line L1
        val[x] = Fraction(p[x]) if mode == "numeric" else Poly.var(x)  # @line L2
    for y, kind, fins in c.gates:  # @line L3
        q = [val[z] for z in fins]  # @line L4
        val[y] = gate_formula(kind, q)  # @line L10
    if mode == "polynomial":  # @line L11
        return {v: f.evaluate(p) for v, f in val.items()}  # @line L12
    return val  # @line L13


def probability_polynomials(c) -> dict[str, Poly]:
    """The suppressed polynomial of every node, before evaluation."""
    val: dict[str, Poly] = {x: Poly.var(x) for x in c.inputs}
    for y, kind, fins in c.gates:
        val[y] = gate_formula(kind, [val[z] for z in fins])
    return val


def propagate(c, p: Mapping[str, Fraction]) -> dict[str, Fraction]:
    """The numeric mode."""
    return signal_probabilities(c, p, "numeric")


def exact_probabilities(c, p: Mapping[str, Fraction]) -> dict[str, Fraction]:
    """The polynomial mode."""
    return signal_probabilities(c, p, "polynomial")
test_signal_probability_propagation.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/signal-probability-propagation/. The authors are listed in prov/CC4R1Y.jsonl.

import itertools
import random
from fractions import Fraction

from netlist import KINDS, Circuit, random_circuit
from signal_probability_propagation import (
    Poly,
    exact_probabilities,
    gate_formula,
    probability_polynomials,
    propagate,
    signal_probabilities,
)

HALF = Fraction(1, 2)


def brute_force(c, p):
    """Exact P(node = 1) by enumeration of all 2^n input vectors, in Fraction."""
    out = {v: Fraction(0) for v in c.nodes}
    for x in itertools.product((0, 1), repeat=len(c.inputs)):
        w = Fraction(1)
        for name, b in zip(c.inputs, x):
            w *= p[name] if b else 1 - p[name]
        if w == 0:
            continue
        val = c.evaluate(x)
        for v in c.nodes:
            if val[v]:
                out[v] += w
    return out


def random_probs(rng, c):
    return {x: Fraction(rng.randint(0, 8), 8) for x in c.inputs}


# 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"])])

# The fanout-free example of the page: y = (a AND b) OR (NOT c), z = y XOR d.
TREE = Circuit(
    ["a", "b", "c", "d"],
    [("u", "AND", ["a", "b"]), ("w", "NOT", ["c"]), ("y", "OR", ["u", "w"]), ("z", "XOR", ["y", "d"])],
)


def test_gate_formulas_against_truth_tables():
    rng = random.Random(1)
    for kind in KINDS:
        arity = [1] if kind in ("BUF", "NOT") else [2, 3, 4]
        for k in arity:
            for _ in range(5):
                c = Circuit([f"i{j}" for j in range(k)], [("o", kind, [f"i{j}" for j in range(k)])])
                p = random_probs(rng, c)
                assert gate_formula(kind, [p[x] for x in c.inputs]) == brute_force(c, p)["o"]


def test_page_examples():
    p = {"a": HALF, "b": HALF, "c": HALF}
    assert brute_force(RECONV, p)["y"] == Fraction(3, 8)
    assert propagate(RECONV, p)["y"] == Fraction(7, 16)
    assert exact_probabilities(RECONV, p)["y"] == Fraction(3, 8)
    poly = probability_polynomials(RECONV)["y"]
    assert poly == Poly({frozenset("ab"): 1, frozenset("ac"): 1, frozenset("abc"): -1})
    assert signal_probabilities(RECONV, p, "numeric") == propagate(RECONV, p)
    q = {"a": Fraction(1, 2), "b": Fraction(1, 4), "c": Fraction(3, 4), "d": Fraction(1, 3)}
    exact = brute_force(TREE, q)
    assert propagate(TREE, q) == exact
    assert exact["y"] == Fraction(11, 32) and exact["z"] == Fraction(43, 96)


def test_x_and_not_x():
    c = Circuit(["a"], [("n", "NOT", ["a"]), ("y", "AND", ["a", "n"])])
    p = {"a": HALF}
    assert exact_probabilities(c, p)["y"] == 0
    assert propagate(c, p)["y"] == Fraction(1, 4)


def test_propagation_exact_without_reconvergence():
    rng = random.Random(2)
    count = 0
    for _ in range(300):
        c = random_circuit(rng, rng.randint(1, 7), rng.randint(1, 8), fanout_free=rng.random() < 0.5)
        if c.has_reconvergence():
            continue
        count += 1
        p = random_probs(rng, c)
        assert propagate(c, p) == brute_force(c, p)
    assert count > 100


def test_fanout_free_circuits_have_no_reconvergence():
    rng = random.Random(3)
    for _ in range(200):
        c = random_circuit(rng, rng.randint(1, 7), rng.randint(1, 8), fanout_free=True)
        assert c.is_fanout_free() and not c.has_reconvergence()
        p = random_probs(rng, c)
        assert propagate(c, p) == brute_force(c, p)


def test_polynomials_exact_on_every_circuit():
    rng = random.Random(4)
    for _ in range(200):
        c = random_circuit(rng, rng.randint(1, 6), rng.randint(1, 9))
        p = random_probs(rng, c)
        assert exact_probabilities(c, p) == brute_force(c, p)


def test_polynomials_are_multilinear_and_match_on_vertices():
    rng = random.Random(5)
    for _ in range(50):
        c = random_circuit(rng, rng.randint(1, 5), rng.randint(1, 7))
        polys = probability_polynomials(c)
        for x in itertools.product((0, 1), repeat=len(c.inputs)):
            vertex = {name: Fraction(b) for name, b in zip(c.inputs, x)}
            val = c.evaluate(x)
            for v in c.nodes:
                assert polys[v].evaluate(vertex) == val[v]


def test_independence_is_wrong_under_reconvergence():
    rng = random.Random(6)
    wrong = 0
    for _ in range(300):
        c = random_circuit(rng, rng.randint(2, 6), rng.randint(3, 9))
        if not c.has_reconvergence():
            continue
        p = {x: HALF for x in c.inputs}
        if propagate(c, p) != brute_force(c, p):
            wrong += 1
    assert wrong > 50


def test_model_counting_reduction():
    # (a or not b) and (b or c) and (not a or not c): P(F = 1) with p = 1/2 is #F / 2^n.
    c = Circuit(
        ["a", "b", "c"],
        [
            ("nb", "NOT", ["b"]),
            ("na", "NOT", ["a"]),
            ("nc", "NOT", ["c"]),
            ("c1", "OR", ["a", "nb"]),
            ("c2", "OR", ["b", "c"]),
            ("c3", "OR", ["na", "nc"]),
            ("F", "AND", ["c1", "c2", "c3"]),
        ],
    )
    models = sum(c.evaluate(x)["F"] for x in itertools.product((0, 1), repeat=3))
    pr = exact_probabilities(c, {x: HALF for x in c.inputs})["F"]
    assert pr * 8 == models == 2

History

Parker and McCluskey (1975) defined the probability of a signal and the independence of two signals for combinational networks, gave the gate formulas, and handled reconvergent fanout by computing a polynomial in the input probabilities in which exponents are suppressed. Their motivation was the analysis of random testing and of circuits with faults. The cutting algorithm of Savir, Ditlow and Bardell (1984) gave bounds in place of exact values for large circuits. In power estimation, signal probabilities became the input of the probabilistic methods surveyed by Najm (1994), next to transition densities and BDD-based methods.

References

  1. K. P. Parker and E. J. McCluskey, Probabilistic treatment of general combinational networks, IEEE Transactions on Computers C-24(6), 668 to 670, June 1975, the definition of signal probability and signal independence, the gate formulas, and the polynomial algorithm with exponent suppression for reconvergent fanout
  2. 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 (signal probabilities, the independence assumption and the effect of reconvergent fanout)
  3. Leslie G. Valiant, The complexity of enumeration and reliability problems, SIAM Journal on Computing 8(3), 410 to 421, 1979, the
  4. Jacob Savir, Gary S. Ditlow and Paul H. Bardell, Random pattern testability, IEEE Transactions on Computers C-33(1), 79 to 90, 1984, the cutting algorithm, which cuts fanout branches and propagates intervals to bound the signal probabilities

Where this leads

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