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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kenneth P. Parker, Edward J. McCluskey, 1975
Signal probability propagation computes, for each node of a combinational circuit, the signal probability , 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 for . 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 by after each product. That version is exact on every circuit, but the polynomials can have 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 with primary inputs and gates in topological order, each gate being BUF, NOT, AND, OR, NAND, NOR, XOR or XNOR, and a probability for each input. The inputs are random variables , mutually independent, with . Each node computes a Boolean function of the inputs. The output is
for every node . The support is the set of primary inputs in the transitive fanin of . 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.
SIGNAL-PROBABILITIES(C, p, mode)- 1
for each primary input x_i do - 2
if mode = numeric then P[x_i] ← p_i else P[x_i] ← the polynomial x_i - 3
for each gate y = kind(z_1, …, z_k) in topological order do - 4
q_j ← P[z_j] for j = 1, …, k - 5
if kind ∈ {AND, NAND} then r ← q_1 · q_2 · … · q_k - 6
if kind ∈ {OR, NOR} then r ← 1 − (1 − q_1)(1 − q_2) … (1 − q_k) - 7
if kind ∈ {XOR, XNOR} then r ← q_1, then r ← r + q_j − 2 r q_j for j = 2, …, k - 8
if kind ∈ {BUF, NOT} then r ← q_1 - 9
if kind ∈ {NAND, NOR, XNOR, NOT} then r ← 1 − r - 10
P[y] ← r - 11
if mode = polynomial then - 12
for each node y do P[y] ← the value of P[y] at x_i = p_i for all i - 13
return P
In the polynomial mode every product of lines L5 to L7 is followed by exponent suppression: each monomial becomes . 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 , , and , with , , and . Each node drives one pin, so the numeric mode is exact.
| node | formula | value |
|---|---|---|
Summing the input probabilities over the vectors on which gives the same .
A reconvergent circuit. Take , and , so , and let every input have probability . The input reaches through both and .
| node | numeric mode | polynomial mode |
|---|---|---|
The polynomial evaluates to , which is right: exactly when and , with probability . The numeric mode gives , too high by , because it treats and as independent when both need . The extreme case is : the true value is 0, and the numeric mode gives .
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 , and suppression keeps the values at the corners. A polynomial with no exponent above 1 is fixed by its corner values, and the function 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 over variables becomes a circuit with one OR gate per clause and one AND gate over the clauses. With every , , so an exact signal probability gives the number of models of , 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 are independent with . For a function write
which is . A polynomial in is multilinear when no variable has an exponent above 1. The suppression of a polynomial replaces each monomial by and collects terms.
Lemma 1 (gate identities). For each gate kind, the formula of lines L5 to L9 satisfies for all .
Proof. AND: the product of 0-1 values is 1 exactly when all are 1. OR: is 0 exactly when all are 0. XOR: for , is 1 exactly when one of them is 1, so the fold of line L7 computes the parity. BUF returns . Line L9 complements the value for NAND, NOR, XNOR and NOT, since is the complement of a 0-1 value.
Lemma 2 (uniqueness). If two multilinear polynomials and agree on , then .
Proof. Let , a multilinear polynomial that is 0 on , and suppose . Take a monomial of with and smallest. Evaluate at the corner with for and otherwise. A monomial with set is 1 at this corner if and 0 otherwise. By the choice of , no monomial of has a set strictly inside , so . This contradicts .
Lemma 3 (suppression keeps corner values). For every polynomial and every , . Also and .
Proof. For and , . So each monomial has the same value before and after suppression. The two identities hold because suppression only lowers exponents to 1, and the exponent of in a product is the sum of the exponents in the factors, which is at least 1 exactly when one of them is.
Lemma 4 (the probability is the multilinear extension). is a multilinear polynomial in , and for every .
Proof. Each term is a product of one factor or for each , which is multilinear, and a sum of multilinear polynomials is multilinear. At a corner , the factor is 1 if and 0 otherwise. So only the term is not zero, and it equals .
Theorem 1 (the polynomial mode is exact). In the polynomial mode, for every node , line L12 sets .
Proof. We show by induction in topological order that before line L12 the value of is a multilinear polynomial with for all . For a primary input, , which is multilinear and equals the projection on the corners. For a gate , lines L5 to L9 combine with the formula and suppress after each product, so by Lemma 3 the result is , which is multilinear. At a corner , Lemma 3, the induction hypothesis and Lemma 1 give
So and are multilinear and agree on all corners by Lemma 4. By Lemma 2 they are the same polynomial, and line L12 evaluates it at .
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 for every node .
Proof. By induction in topological order we show two facts: depends only on the inputs in , and . For a primary input both are clear. For a gate , depends only on . The random variables are functions of the disjoint groups of variables , and the are mutually independent, so are mutually independent. For independent 0-1 variables with :
- AND: ;
- OR: ;
- XOR: if is the parity of with , and is independent of , then ;
- BUF and the complements of line L9 are clear.
With by the induction hypothesis, line L10 sets .
A fanout-free circuit satisfies the hypothesis: if two input pins of a gate had a common input in their supports, there would be two paths from to the gate that end at different pins, and the node where these paths split would drive two gate pins.
Counterexample under reconvergence. For , , and all , the numeric mode returns , while . The supports and of the pins of meet, and the step that fails is the independence of and : .
Theorem 3 (hardness). Computing for a circuit and rational input probabilities is #P-hard under polynomial-time reductions that make one query. It stays #P-hard with every and gates AND, OR and NOT only.
Proof. Counting the satisfying assignments of a CNF formula is #P-complete (Valiant 1979). Let be a CNF formula over . Build a circuit with inputs , 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 , and its output computes . With for all , every vector has probability , so . One query of the signal probability, and a multiplication by , give .
Since the number counts the inputs that set to 1, it is itself a #P function, so for the problem is #P-complete. The decision version, whether for probabilities in , is satisfiability of the circuit and is NP-complete.
Complexity
Let be the number of gates, the number of gate input pins and the number of primary inputs.
- Numeric mode. Each gate with inputs costs arithmetic operations, so the pass costs operations and space. With exact rationals the numbers grow, so a tool uses floating point.
- Polynomial mode. A node's polynomial has at most monomials, one per subset of its support. A product of two such polynomials costs at most monomial products, each a set union of cost , so the pass costs time in the worst case and space. A gate with small supports costs much less: the cost depends on the supports, not on alone.
- Lower bound. No polynomial-time algorithm computes exact signal probabilities unless every #P function is computable in polynomial time, which would give . Even deciding whether 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 it is too high; for , which is always 1, it gives , too low.
- Multilinear. In the polynomial mode each result is the multilinear polynomial of its function, so it gives 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 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 , and propagate intervals. The result is a lower and an upper bound on each , 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 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 to the probability of an internal node is wrong unless that node is a primary input.
- The XOR formula. needs independent and . For three inputs, fold the two-input rule, or use .
- 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 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.
# 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
- 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
- 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)
- Leslie G. Valiant, The complexity of enumeration and reliability problems, SIAM Journal on Computing 8(3), 410 to 421, 1979, the
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag CC4R1Y Edit this page History Report an error Markdown