Algorithm Search⌘K

Algorithmcore

Symbolic simulation

Also called COSMOS symbolic simulation.

Simulates a circuit with Boolean variables instead of constants on the inputs, so each node holds a BDD or formula that covers all input values at once.

Time
O(k P B^2) worst
Space
O(k P B^2) extra
Where
B = the number of nodes of the largest BDD of the run (at most 2^(v + 1), v the number of variables); P = the number of gate inputs of the circuit; k = the number of simulated cycles
Properties
completedeterministicexactrecursive
Origin
William C. Carter, William H. Joyner, Daniel Brand, Randal E. Bryant, 1979

Symbolic simulation runs a gate-level circuit with Boolean variables on its inputs in place of 0 and 1. Each node then holds a Boolean function of the variables, kept as a reduced ordered BDD, and one run covers every input value at once. For a synchronous circuit the method gives the inputs a fresh variable in each clock cycle, and it gives each register either its reset value or a variable for an unknown initial value. After kk cycles the BDD of an output is the exact function from all input sequences of length kk to the value of that output. This is a verification page. The simulation here is zero-delay cycle-based logic simulation with the values 0 and 1, and the method is a check of the design before manufacturing. A property that must hold for all inputs becomes one BDD that must be the constant 1, and two designs are equal on all inputs when their BDDs are the same node.

In plain words

A normal simulator puts one test vector on the inputs and gets one answer. To check all inputs of a 64-bit adder this way you need 21282^{128} runs.

A symbolic simulator puts a name, such as a0a_0, on each input instead of a value. Each gate then works on formulas, not bits: an AND gate with inputs a0a_0 and b0b_0 gives the formula "a0a_0 and b0b_0". At the end, each output holds a formula that says what the output is for every input at once.

The formulas are kept in a form in which equal functions look the same, so a check is a comparison. The price is that some formulas get very large, for example those of a multiplier.

The problem

The input is a synchronous circuit CC with one clock, a number kk of cycles, and a variable order. The circuit has primary inputs XX, latches SS with a next-state node next(s)\mathrm{next}(s) and an initial value init(s)∈{0,1,?}\mathrm{init}(s) \in \{0, 1, ?\}, where ?? means unknown, gates in topological order, and outputs OO. A run of length kk is a choice of a value for every unknown initial latch and of an input vector for each cycle 0,…,k−10, \ldots, k - 1. Two-valued simulation of a run gives a value valt(u)\mathrm{val}_t(u) for every node uu in every cycle tt.

The variables are one variable s0s^0 for each latch ss with unknown initial value and one variable xtx_t for each input xx and cycle tt. A run is then the same thing as an assignment α\alpha of 0 or 1 to all variables. The output is, for each cycle tt and output oo, the BDD Ot(o)O_t(o) with Ot(o)(α)=valt(o)O_t(o)(\alpha) = \mathrm{val}_t(o) for the run α\alpha, for all α\alpha.

The algorithm

  1. SYMBOLIC-SIMULATE(C, k)
  2. 1for each latch s do S(s) ← init(s) if it is 0 or 1, else a fresh variable s⁰
  3. 2for t ← 0 to k − 1 do
  4. 3for each primary input x do V(x) ← a fresh variable x_t
  5. 4for each latch s do V(s) ← S(s)
  6. 5for each gate u in topological order do V(u) ← APPLY(op(u), V of the fanins of u)
  7. 6for each output o do O_t(o) ← V(o)
  8. 7for each latch s do S(s) ← V(next(s))
  9. 8return O_0, ..., O_(k−1)

The loop is the loop of a cycle-based simulator. The only change is the value type. Line L1 gives a known reset value as the constant BDD, and an unknown value as a variable, so the result holds for every initial state. Line L3 makes a new variable in every cycle. The input of cycle 1 is then free to differ from the input of cycle 0. Line L5 is the Apply operation of the gate, for example the AND of two BDDs, and the BDD package keeps one node per function in its unique table. Line L7 moves the next-state functions into the latches, which is the clock edge.

A check comes after the run. To prove that a property PP of the outputs holds in all runs, build the BDD of PP from the Ot(o)O_t(o) and compare it with the constant 1. If it is not 1, any path to the 0 terminal is a run that breaks PP, which a normal simulator can then replay. To compare two circuits, simulate both with one manager and the same variables. They agree on all runs of length kk exactly when their output BDDs are the same nodes.

Example

Take one input aa, one latch rr with reset value 0, and two gates n=r⊕an = r \oplus a and z=r∧az = r \wedge a, with next(r)=n\mathrm{next}(r) = n and the output zz. So rr holds the parity of the inputs so far, and zz is 1 when the input and the parity are both 1. Simulate k=3k = 3 cycles. The sizes count the BDD nodes, terminals included, under the order a0<a1<a2a_0 < a_1 < a_2.

cycle tt V(a)V(a) V(r)V(r) at L4 V(z)=Ot(z)V(z) = O_t(z) size V(n)V(n), the next rr size
0 a0a_0 00 00 1 a0a_0 3
1 a1a_1 a0a_0 a0∧a1a_0 \wedge a_1 4 a0⊕a1a_0 \oplus a_1 5
2 a2a_2 a0⊕a1a_0 \oplus a_1 (a0⊕a1)∧a2(a_0 \oplus a_1) \wedge a_2 6 a0⊕a1⊕a2a_0 \oplus a_1 \oplus a_2 7

The three BDDs of zz cover all 23=82^3 = 8 runs of length 3. Each run takes 3 cycles of normal simulation, and the 8 runs together take 24.

Now check the property "zz is never 1 in two cycles in a row" for cycles 1 and 2. The BDD of O1(z)∧O2(z)O_1(z) \wedge O_2(z) is a0a1(a0⊕a1)a2a_0 a_1 (a_0 \oplus a_1) a_2. When a0=a1=1a_0 = a_1 = 1, the parity a0⊕a1a_0 \oplus a_1 is 0, so the BDD package returns the 0 terminal, and the property holds in every run. If the latch starts unknown instead, line L1 gives it the variable r0r^0. Then O0(z)=r0∧a0O_0(z) = r^0 \wedge a_0, and the result covers 16 runs.

The parity BDD grows by 2 nodes per cycle, so its size is linear in kk while the number of runs is 2k2^k. That gap is the gain of the method. The tests build these BDDs and check them against normal simulation of all runs.

Correctness

The result is exact: for every cycle tt, output oo and assignment α\alpha, Ot(o)(α)O_t(o)(\alpha) is the value of oo in cycle tt of the run α\alpha. The invariant, kept in each cycle and at each gate in topological order, is that V(u)V(u) evaluated at α\alpha equals valt(u)\mathrm{val}_t(u) in the run α\alpha. Inputs and latches start it at lines L3, L4 and L1. Line L5 keeps it because Apply returns the BDD of the gate function of its arguments, and evaluation at one point commutes with every gate operator. Line L7 carries it to the next cycle. Since a reduced ordered BDD is canonical for a fixed variable order (Bryant 1986), two outputs agree in all runs exactly when their BDDs are the same node, and a property holds in all runs exactly when its BDD is the terminal 1. The full proof is in the correctness proof.

Proof: Symbolic simulation gives the exact output function of every cyclefull

Setting. CC is a synchronous circuit with primary inputs XX, latches SS, gates g1,…,gmg_1, \ldots, g_m in topological order and outputs OO. Each gate uu has an operator op(u)\mathrm{op}(u), a Boolean function of its fanins, and each latch ss has a next-state node next(s)\mathrm{next}(s) and an initial value init(s)∈{0,1,?}\mathrm{init}(s) \in \{0, 1, ?\}. The variables are s0s^0 for each latch with init(s)=?\mathrm{init}(s) = {?} and xtx_t for each input xx and each cycle 0≤t<k0 \le t < k. A run is an assignment α\alpha of 0 or 1 to all variables. It fixes the unknown initial values and the input vector of every cycle, and every such choice is one assignment.

Concrete semantics. For a run α\alpha, two-valued simulation defines σ0(s)=init(s)\sigma_0(s) = \mathrm{init}(s) if it is 0 or 1 and σ0(s)=α(s0)\sigma_0(s) = \alpha(s^0) otherwise. In cycle tt it sets valt(x)=α(xt)\mathrm{val}_t(x) = \alpha(x_t) for x∈Xx \in X, valt(s)=σt(s)\mathrm{val}_t(s) = \sigma_t(s) for s∈Ss \in S, valt(u)=op(u)(valt of the fanins of u)\mathrm{val}_t(u) = \mathrm{op}(u)(\mathrm{val}_t \text{ of the fanins of } u) for each gate in topological order, and then σt+1(s)=valt(next(s))\sigma_{t+1}(s) = \mathrm{val}_t(\mathrm{next}(s)).

Claim. After SYMBOLIC-SIMULATE(CC, kk), for every cycle t<kt < k, output oo and run α\alpha, the BDD Ot(o)O_t(o) evaluated at α\alpha is valt(o)\mathrm{val}_t(o) in the run α\alpha. Moreover, for outputs o,o′o, o' and cycles t,t′t, t' of circuits simulated with the same manager and variables, Ot(o)=Ot′(o′)O_t(o) = O_{t'}(o') as nodes if and only if the two values agree in every run.

For a BDD ff write f(α)f(\alpha) for its value at α\alpha.

Fact 1 (Apply). For every binary operator ∘\circ, Apply returns a BDD hh with h(α)=f(α)∘g(α)h(\alpha) = f(\alpha) \circ g(\alpha) for every α\alpha, and negation returns hh with h(α)=1−f(α)h(\alpha) = 1 - f(\alpha) (Bryant 1986, see Apply). A gate with dd fanins is folded as d−1d - 1 applies of an associative operator, followed by a negation for NAND, NOR and XNOR, so by induction on dd the BDD of line L5 evaluates at every α\alpha to op(u)\mathrm{op}(u) of the fanin values at α\alpha.

Lemma (invariant). At the start of cycle tt (before line L3), S(s)(α)=σt(s)S(s)(\alpha) = \sigma_t(s) for every latch ss and every run α\alpha. After line L5 of cycle tt, V(u)(α)=valt(u)V(u)(\alpha) = \mathrm{val}_t(u) for every node uu and every run α\alpha.

Proof. By induction on tt, and inside a cycle on the position of uu in the order inputs, latches, g1,…,gmg_1, \ldots, g_m.

Base, t=0t = 0, latches. Line L1 sets S(s)S(s) to the constant init(s)\mathrm{init}(s) or to the BDD of the variable s0s^0. The constant evaluates to init(s)=σ0(s)\mathrm{init}(s) = \sigma_0(s), and the variable evaluates to α(s0)=σ0(s)\alpha(s^0) = \sigma_0(s).

Inside cycle tt. Assume the claim on SS at the start of cycle tt. Line L3 sets V(x)V(x) to the variable xtx_t, so V(x)(α)=α(xt)=valt(x)V(x)(\alpha) = \alpha(x_t) = \mathrm{val}_t(x). Line L4 sets V(s)=S(s)V(s) = S(s), so V(s)(α)=σt(s)=valt(s)V(s)(\alpha) = \sigma_t(s) = \mathrm{val}_t(s). Take the gates in topological order, and assume the claim for every node before gjg_j. All fanins of gjg_j are inputs, latches or earlier gates, so their VV already holds and evaluates at α\alpha to their valt\mathrm{val}_t. By Fact 1, V(gj)(α)=op(gj)(valt of the fanins)=valt(gj)V(g_j)(\alpha) = \mathrm{op}(g_j)(\mathrm{val}_t \text{ of the fanins}) = \mathrm{val}_t(g_j). No later step of cycle tt changes V(gj)V(g_j).

Step to cycle t+1t + 1. Line L7 sets S(s)=V(next(s))S(s) = V(\mathrm{next}(s)), which evaluates at α\alpha to valt(next(s))=σt+1(s)\mathrm{val}_t(\mathrm{next}(s)) = \sigma_{t+1}(s). This is the claim on SS at the start of cycle t+1t + 1. □\square

Proof of the claim. Line L6 copies V(o)V(o) after line L5 of cycle tt, and no later line changes the copy, so the Lemma gives Ot(o)(α)=valt(o)O_t(o)(\alpha) = \mathrm{val}_t(o) for every run α\alpha. This is the first part.

For the second part, Ot(o)O_t(o) and Ot′(o′)O_{t'}(o') are reduced ordered BDDs of one manager over one variable order. Such a BDD is canonical: two of them are the same node exactly when they represent the same function of the variables (Bryant 1986, see reduced ordered BDD). The manager keeps this because MK returns the existing node of each triple and never makes a node with equal children. By the first part, the function of Ot(o)O_t(o) maps each run to the value of oo in cycle tt, and every assignment is a run. So the two nodes are equal exactly when the two values agree in every run. ■\blacksquare

Consequence. A property PP built from output values with Boolean operators holds in every run of length kk exactly when its BDD, built from the Ot(o)O_t(o) by Apply, is the terminal 1. If it is not, a path from the root to the terminal 0 gives values for some variables, and any values for the others give a run in which PP is false.

Complexity

The model is the word RAM with hashing in expected constant time. Let vv be the number of variables, PP the number of gate inputs, and BB the largest BDD of the run.

  • Apply of two BDDs with ∣f∣|f| and ∣g∣|g| nodes, with a cache, costs O(∣f∣∣g∣)O(|f| |g|) time (Bryant 1986). A gate with dd inputs costs d−1d - 1 applies, so line L5 costs O(PB2)O(P B^2) per cycle.
  • Lines L1, L3, L4, L6 and L7 cost O(∣S∣+∣X∣+∣O∣)O(|S| + |X| + |O|) per cycle.
  • Over kk cycles the time is O(kPB2)O(k P B^2), and the unique table and the cache hold one entry per step, which gives the same space bound.

A BDD over vv variables has at most 2i2^i nodes at depth ii, so B≤2v+1−1B \le 2^{v + 1} - 1, and for a sequential circuit vv grows by ∣X∣|X| per cycle. The exponent is real for some functions. For the middle output bit of an nn-bit multiplier, every variable order gives a BDD with at least 2n/82^{n/8} nodes (Bryant 1991). The method cannot be polynomial for all circuits in any case: a circuit is satisfiable exactly when its output BDD is not the 0 terminal, so a polynomial method would decide circuit SAT. In practice the cost depends on the variable order, and for control logic and datapaths without multipliers a good order keeps BB small.

Properties

  • Exact and complete for runs of the chosen length kk. It says nothing about longer runs.
  • Deterministic. The BDD of a function does not depend on the circuit that computes it, only on the variable order.
  • The result for a run is the same as normal two-valued simulation of that run, so a failing run from a BDD can be replayed in any simulator.
  • Unknown initial values cost one variable each. The method uses only the values 0 and 1. The value X is the subject of ternary simulation.

Variants and improvements

  • Formulas in place of BDDs. Each node holds a gate of a shared graph, such as an and-inverter graph, and the check is a SAT call. The graph is linear in kPk P, and the hard work moves to the solver. With a property at cycle kk, this is bounded model checking of the unrolled circuit.
  • Partly symbolic runs. Some inputs get constants and some get variables, for example a fixed opcode with symbolic operands. Each run then covers one slice of the input space, and the BDDs stay small.
  • Ternary symbolic simulation. Each node holds a pair of BDDs that encodes 0, 1 or X under each assignment. Unknown values that do not matter for a property then cost no variable. This is the engine of symbolic trajectory evaluation.
  • Switch level. COSMOS first turns a transistor network into Boolean equations, then simulates them. A switch-level simulator with BDD values gives symbolic simulation of MOS circuits.
  • Reachable states. Applying the transition relation to sets of states, with existential quantification of the inputs, gives symbolic reachability. It covers all run lengths, but needs image computation in place of a simple forward pass.
  • Software. Symbolic execution of programs keeps a path condition and splits at branches. A circuit has no branches, so symbolic simulation needs no path splitting.

When to use it

Use it to prove a property for all inputs over a bounded number of cycles: the result of a pipeline after kk cycles, a datapath without multipliers, a check that two versions of a block are equal for kk cycles from reset. It also finds counterexamples that random simulation misses, because one BDD covers all runs. For combinational equivalence with much shared structure, SAT sweeping or a SAT check of the miter is usually cheaper. For properties over all run lengths, use symbolic reachability or the model checkers. For multipliers, use word-level methods.

Pitfalls

  • One variable for an input in all cycles. If line L3 reuses x0x_0 in every cycle, the result covers only runs with a constant input. In the example, O2(z)O_2(z) would become (a⊕a)∧a=0(a \oplus a) \wedge a = 0, and a bug at a0=1,a2=1a_0 = 1, a_2 = 1 would be missed. Line L3 must make a fresh variable in every cycle.
  • Treating an unknown initial value as 0. If line L1 uses 0 for a latch with no reset, the proof covers only one initial state. Give the latch a variable, or prove that the reset sets it first.
  • A bad variable order. With the variables of one operand all before those of the other, the BDD of an nn-bit equality comparator has about 2n2^n nodes, while an interleaved order gives O(n)O(n) nodes. Interleave the bits of operands that are compared or added, and order the variables of a later cycle after those of an earlier one only when the circuit reads its inputs in that order.
  • Gates out of order. Line L5 needs a topological order of the combinational logic. A combinational cycle has no such order, and a simulator that evaluates a gate before its fanins uses stale BDDs from the previous cycle.

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.

bdd.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the hv2 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reduced ordered BDD package with a unique table and an ITE cache.

A node is an integer. The terminals are 0 (false) and 1 (true). A variable is a
non-negative integer, and a smaller integer is nearer the root. Every inner node
is a triple (var, lo, hi) with lo != hi, and the unique table keeps one node per
triple, so two BDDs of the same manager are equal functions exactly when they
are the same integer.
"""

from __future__ import annotations

from typing import Iterable, Optional

FALSE = 0
TRUE = 1
_TERMINAL_VAR = 1 << 30


class BDD:
    """One manager. All BDDs that are combined must come from the same manager."""

    def __init__(self) -> None:
        self._var: list[int] = [_TERMINAL_VAR, _TERMINAL_VAR]
        self._lo: list[int] = [0, 1]
        self._hi: list[int] = [0, 1]
        self._unique: dict[tuple[int, int, int], int] = {}
        self._ite_cache: dict[tuple[int, int, int], int] = {}

    # -- construction -------------------------------------------------------
    def mk(self, v: int, lo: int, hi: int) -> int:
        """The node (v, lo, hi), reduced: equal children give the child."""
        if lo == hi:
            return lo
        key = (v, lo, hi)
        n = self._unique.get(key)
        if n is None:
            n = len(self._var)
            self._var.append(v)
            self._lo.append(lo)
            self._hi.append(hi)
            self._unique[key] = n
        return n

    def var(self, v: int) -> int:
        """The BDD of the single variable v."""
        return self.mk(v, FALSE, TRUE)

    def top(self, f: int) -> int:
        return self._var[f]

    def low(self, f: int) -> int:
        return self._lo[f]

    def high(self, f: int) -> int:
        return self._hi[f]

    def _cof(self, f: int, v: int, b: int) -> int:
        if self._var[f] != v:
            return f
        return self._hi[f] if b else self._lo[f]

    def ite(self, f: int, g: int, h: int) -> int:
        """If f then g else h, by Shannon expansion on the top variable."""
        if f == TRUE:
            return g
        if f == FALSE:
            return h
        if g == h:
            return g
        if g == TRUE and h == FALSE:
            return f
        key = (f, g, h)
        r = self._ite_cache.get(key)
        if r is not None:
            return r
        v = min(self._var[f], self._var[g], self._var[h])
        lo = self.ite(self._cof(f, v, 0), self._cof(g, v, 0), self._cof(h, v, 0))
        hi = self.ite(self._cof(f, v, 1), self._cof(g, v, 1), self._cof(h, v, 1))
        r = self.mk(v, lo, hi)
        self._ite_cache[key] = r
        return r

    def neg(self, f: int) -> int:
        return self.ite(f, FALSE, TRUE)

    def conj(self, f: int, g: int) -> int:
        return self.ite(f, g, FALSE)

    def disj(self, f: int, g: int) -> int:
        return self.ite(f, TRUE, g)

    def xor(self, f: int, g: int) -> int:
        return self.ite(f, self.neg(g), g)

    def xnor(self, f: int, g: int) -> int:
        return self.ite(f, g, self.neg(g))

    def restrict(self, f: int, v: int, b: int) -> int:
        """f with the variable v set to the constant b."""
        memo: dict[int, int] = {}

        def go(n: int) -> int:
            if n <= 1 or self._var[n] > v:
                return n
            if n in memo:
                return memo[n]
            if self._var[n] == v:
                r = self._hi[n] if b else self._lo[n]
            else:
                r = self.mk(self._var[n], go(self._lo[n]), go(self._hi[n]))
            memo[n] = r
            return r

        return go(f)

    def exists(self, f: int, vs: Iterable[int]) -> int:
        """Existential quantification of the variables vs."""
        for v in sorted(set(vs), reverse=True):
            f = self.disj(self.restrict(f, v, 0), self.restrict(f, v, 1))
        return f

    # -- queries ------------------------------------------------------------
    def evaluate(self, f: int, assignment: dict[int, int]) -> int:
        """The value of f at a point; a missing variable counts as 0."""
        while f > 1:
            f = self._hi[f] if assignment.get(self._var[f], 0) else self._lo[f]
        return f

    def size(self, f: int) -> int:
        """The number of nodes of f, terminals included."""
        seen: set[int] = set()
        stack = [f]
        while stack:
            n = stack.pop()
            if n in seen:
                continue
            seen.add(n)
            if n > 1:
                stack.append(self._lo[n])
                stack.append(self._hi[n])
        return len(seen)

    def support(self, f: int) -> set[int]:
        out: set[int] = set()
        seen: set[int] = set()
        stack = [f]
        while stack:
            n = stack.pop()
            if n <= 1 or n in seen:
                continue
            seen.add(n)
            out.add(self._var[n])
            stack.append(self._lo[n])
            stack.append(self._hi[n])
        return out

    def sat_one(self, f: int) -> Optional[dict[int, int]]:
        """One point where f is 1 (variables not on the path are left out), or None."""
        if f == FALSE:
            return None
        out: dict[int, int] = {}
        while f > 1:
            if self._lo[f] != FALSE:
                out[self._var[f]] = 0
                f = self._lo[f]
            else:
                out[self._var[f]] = 1
                f = self._hi[f]
        return out
symbolic_simulation.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symbolic-simulation/. The authors are listed in prov/HYGZ61.jsonl.
"""Symbolic simulation of a synchronous gate-level circuit with BDDs.

Each primary input gets a fresh Boolean variable in each cycle, and each latch
starts from a constant or from a fresh variable. One pass over the gates in
topological order per cycle gives every node a BDD over these variables, so the
BDD of an output in cycle t is the function that maps every input sequence (and
every initial state) to the value of that output in cycle t.

Precondition: the gates are listed in topological order, every gate input is a
primary input, a latch or an earlier gate, and the circuit has no combinational
cycle. Cost: one BDD operation per gate and cycle, each O(|f| |g|) for operand
sizes |f| and |g|; the sizes can grow exponentially in the number of variables.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional

from bdd import BDD, FALSE, TRUE

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


@dataclass(frozen=True)
class Circuit:
    """A synchronous circuit with one clock.

    latches holds (name, next_state_node, init) with init 0, 1 or None; None
    means that the initial value is unknown and gets its own variable.
    gates holds (name, op, fanins) in topological order.
    """

    inputs: tuple[str, ...]
    latches: tuple[tuple[str, str, Optional[int]], ...]
    gates: tuple[tuple[str, str, tuple[str, ...]], ...]
    outputs: tuple[str, ...]


@dataclass
class Trace:
    mgr: BDD
    outputs: list[dict[str, int]]          # outputs[t][o] is the BDD of o in cycle t
    states: list[dict[str, int]]           # states[t][s] is the BDD of latch s at the start of cycle t
    variables: dict[tuple, int] = field(default_factory=dict)  # ("init", s) or ("in", x, t) -> variable


def apply_gate(mgr: BDD, op: str, args: list[int]) -> int:
    """The BDD of one gate applied to the BDDs of its fanins."""
    if op == "BUF":
        return args[0]
    if op == "NOT":
        return mgr.neg(args[0])
    if op in ("AND", "NAND"):
        r = TRUE
        for a in args:
            r = mgr.conj(r, a)
        return mgr.neg(r) if op == "NAND" else r
    if op in ("OR", "NOR"):
        r = FALSE
        for a in args:
            r = mgr.disj(r, a)
        return mgr.neg(r) if op == "NOR" else r
    if op in ("XOR", "XNOR"):
        r = FALSE
        for a in args:
            r = mgr.xor(r, a)
        return mgr.neg(r) if op == "XNOR" else r
    raise ValueError(f"unknown gate type {op}")


def symbolic_simulation(c: Circuit, k: int, mgr: Optional[BDD] = None) -> Trace:
    """Simulate c for k cycles with symbolic inputs and return the BDDs.

    The variable order is: the unknown initial latch values in latch order, then
    the inputs of cycle 0, cycle 1, and so on.
    """
    mgr = mgr or BDD()
    variables: dict[tuple, int] = {}
    nxt = 0
    state: dict[str, int] = {}
    for s, _, init in c.latches:                               # @line L1
        if init is None:
            variables[("init", s)] = nxt
            state[s] = mgr.var(nxt)
            nxt += 1
        else:
            state[s] = TRUE if init else FALSE
    outputs: list[dict[str, int]] = []
    states: list[dict[str, int]] = []
    for t in range(k):                                          # @line L2
        value: dict[str, int] = {}
        for x in c.inputs:                                      # @line L3
            variables[("in", x, t)] = nxt
            value[x] = mgr.var(nxt)
            nxt += 1
        states.append(dict(state))
        for s, _, _ in c.latches:                               # @line L4
            value[s] = state[s]
        for name, op, fanins in c.gates:                        # @line L5
            value[name] = apply_gate(mgr, op, [value[f] for f in fanins])
        outputs.append({o: value[o] for o in c.outputs})        # @line L6
        state = {s: value[n] for s, n, _ in c.latches}          # @line L7
    return Trace(mgr, outputs, states, variables)               # @line L8


def instance(trace: Trace, init: dict[str, int], seq: list[dict[str, int]]) -> dict[int, int]:
    """The variable assignment for one concrete run (unknown initial values and inputs)."""
    a: dict[int, int] = {}
    for key, v in trace.variables.items():
        if key[0] == "init":
            a[v] = init[key[1]]
        else:
            a[v] = seq[key[2]][key[1]]
    return a
test_symbolic_simulation.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symbolic-simulation/. The authors are listed in prov/HYGZ61.jsonl.

import itertools
import random

from bdd import FALSE, TRUE, BDD
from symbolic_simulation import OPS, Circuit, instance, symbolic_simulation

# The circuit of the page: latch r (reset to 0), n = r XOR a, z = r AND a.
PAGE = Circuit(
    inputs=("a",),
    latches=(("r", "n", 0),),
    gates=(("n", "XOR", ("r", "a")), ("z", "AND", ("r", "a"))),
    outputs=("z",),
)


def concrete(c: Circuit, init: dict[str, int], seq: list[dict[str, int]]) -> list[dict[str, int]]:
    """Plain two-valued simulation of one run: the oracle."""
    state = {s: (init[s] if v is None else v) for s, _, v in c.latches}
    out = []
    for vec in seq:
        val = dict(vec)
        val.update(state)
        for name, op, fi in c.gates:
            xs = [val[f] for f in fi]
            if op == "BUF":
                r = xs[0]
            elif op == "NOT":
                r = 1 - xs[0]
            elif op in ("AND", "NAND"):
                r = int(all(xs)) ^ (op == "NAND")
            elif op in ("OR", "NOR"):
                r = int(any(xs)) ^ (op == "NOR")
            else:
                r = (sum(xs) % 2) ^ (op == "XNOR")
            val[name] = r
        out.append({o: val[o] for o in c.outputs})
        state = {s: val[n] for s, n, _ in c.latches}
    return out


def all_runs(c: Circuit, k: int):
    unknown = [s for s, _, v in c.latches if v is None]
    for bits in itertools.product((0, 1), repeat=len(unknown) + k * len(c.inputs)):
        init = dict(zip(unknown, bits))
        rest = bits[len(unknown):]
        seq = [dict(zip(c.inputs, rest[t * len(c.inputs):(t + 1) * len(c.inputs)])) for t in range(k)]
        yield init, seq


def check_against_concrete(c: Circuit, k: int) -> int:
    tr = symbolic_simulation(c, k)
    runs = 0
    for init, seq in all_runs(c, k):
        a = instance(tr, init, seq)
        want = concrete(c, init, seq)
        for t in range(k):
            for o in c.outputs:
                assert tr.mgr.evaluate(tr.outputs[t][o], a) == want[t][o]
        runs += 1
    return runs


def test_page_example():
    tr = symbolic_simulation(PAGE, 3)
    m = tr.mgr
    a0, a1, a2 = (m.var(tr.variables[("in", "a", t)]) for t in range(3))
    assert tr.outputs[0]["z"] == FALSE
    assert tr.outputs[1]["z"] == m.conj(a0, a1)
    assert tr.outputs[2]["z"] == m.conj(m.xor(a0, a1), a2)
    assert tr.states[2]["r"] == m.xor(a0, a1)
    # BDD sizes, terminals included, as in the table of the page.
    assert [m.size(tr.outputs[t]["z"]) for t in range(3)] == [1, 4, 6]
    assert check_against_concrete(PAGE, 3) == 8
    # The property of the page: z is never 1 in two cycles in a row.
    assert m.conj(tr.outputs[1]["z"], tr.outputs[2]["z"]) == FALSE


def test_unknown_initial_state():
    c = Circuit(PAGE.inputs, (("r", "n", None),), PAGE.gates, PAGE.outputs)
    tr = symbolic_simulation(c, 3)
    m = tr.mgr
    s = m.var(tr.variables[("init", "r")])
    a = [m.var(tr.variables[("in", "a", t)]) for t in range(3)]
    assert tr.outputs[0]["z"] == m.conj(s, a[0])
    assert tr.states[2]["r"] == m.xor(m.xor(s, a[0]), a[1])
    assert check_against_concrete(c, 3) == 16


def test_one_bdd_per_function():
    # Two different circuits for the same function give the same node: the check
    # of equivalence is one comparison of integers.
    c1 = Circuit(("x", "y"), (), (("o", "XOR", ("x", "y")),), ("o",))
    c2 = Circuit(
        ("x", "y"),
        (),
        (("p", "NAND", ("x", "y")), ("q", "OR", ("x", "y")), ("o", "AND", ("p", "q"))),
        ("o",),
    )
    m = BDD()
    t1 = symbolic_simulation(c1, 1, m)
    t2 = symbolic_simulation(c2, 1, m)
    assert t1.outputs[0]["o"] == t2.outputs[0]["o"]


def test_constant_and_zero_cycles():
    c = Circuit(("x",), (), (("nx", "NOT", ("x",)), ("o", "AND", ("x", "nx"))), ("o",))
    tr = symbolic_simulation(c, 2)
    assert tr.outputs[0]["o"] == FALSE and tr.outputs[1]["o"] == FALSE
    assert symbolic_simulation(c, 0).outputs == []
    c1 = Circuit(("x",), (), (("o", "XNOR", ("x", "x")),), ("o",))
    assert symbolic_simulation(c1, 1).outputs[0]["o"] == TRUE


def random_circuit(rng: random.Random) -> tuple[Circuit, int]:
    n_in = rng.randint(1, 2)
    n_latch = rng.randint(0, 2)
    k = rng.randint(1, 3)
    inputs = tuple(f"x{i}" for i in range(n_in))
    lat_names = [f"s{i}" for i in range(n_latch)]
    inits = [rng.choice((0, 1, None)) for _ in lat_names]
    while sum(v is None for v in inits) + k * n_in > 8:
        k -= 1
    nodes = list(inputs) + lat_names
    gates = []
    for g in range(rng.randint(1, 7)):
        op = rng.choice(OPS)
        ar = 1 if op in ("BUF", "NOT") else rng.randint(2, 3)
        gates.append((f"g{g}", op, tuple(rng.choice(nodes) for _ in range(ar))))
        nodes.append(f"g{g}")
    latches = tuple((s, rng.choice(nodes), v) for s, v in zip(lat_names, inits))
    outputs = tuple(sorted(set(rng.choice(nodes) for _ in range(2))))
    return Circuit(inputs, latches, tuple(gates), outputs), k


def test_random_circuits_against_every_run():
    rng = random.Random(20261114)
    runs = 0
    for _ in range(600):
        c, k = random_circuit(rng)
        runs += check_against_concrete(c, k)
    assert runs > 5000

History

Carter, Joyner and Brand at IBM (DAC 1979) simulated a machine description with symbols for the inputs and for the initial contents of the registers, and compared the results with a specification. The symbolic expressions were hard to compare, and the work stopped for some years. Bryant's BDDs (1986) gave a canonical form in which a comparison is one test. The COSMOS simulator of Bryant, Beatty, Brace, Cho and Sheffler (DAC 1987) turned MOS transistor networks into Boolean equations, and its symbolic mode ran them with BDD values. Bryant surveyed the techniques and uses in 1990, and in 1991 he showed that multipliers have no small BDD under any order, which marks the limit of the method.

References

  1. W. C. Carter, W. H. Joyner and D. Brand, Symbolic simulation for correct machine design, DAC 1979, 280 to 286, symbolic values for the inputs and the initial register contents of a machine description, and the comparison of the symbolic results with a specification
  2. R. E. Bryant, Graph-based algorithms for Boolean function manipulation, IEEE Transactions on Computers C-35(8), 677 to 691, 1986, the reduced ordered BDD, its canonical form under a fixed variable order, and the Apply operation with its cost of O(|f| |g|)
  3. R. E. Bryant, D. L. Beatty, K. S. Brace, K. Cho and T. J. Sheffler, COSMOS, a compiled simulator for MOS circuits, DAC 1987, 9 to 16, the switch-level network turned into Boolean equations by the symbolic analyzer ANAMOS, which is the base of the symbolic mode
  4. R. E. Bryant, Symbolic simulation, techniques and applications, Proceedings of the 27th Design Automation Conference, 517 to 521, 1990, the survey of symbolic simulation with BDDs, the encoding of inputs and initial states by variables, and its use for circuit verification
  5. R. E. Bryant, On the complexity of VLSI implementations and graph representations of Boolean functions with application to integer multiplication, IEEE Transactions on Computers 40(2), 205 to 213, 1991, the exponential lower bound on the BDD of the middle output bit of a multiplier under every variable order

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