Algorithm Search⌘K

Algorithmadvanced

Switch-level simulation

Also called MOSSIM switch-level model, Bryant switch-level simulation.

Bryant's simulation of MOS circuits as networks of switch transistors and charged nodes with discrete strengths, between gate-level and circuit simulation.

Time
O(R (N + T) log N) worstO((N + T) log N) best
Space
O(N + T) extra
Where
N = the number of storage nodes; R = the number of rounds until the network settles; T = the number of transistors
Properties
deterministicnot exactiterative
Origin
Randal E. Bryant, 1981

Switch-level simulation models a MOS circuit as a network of switches. Each transistor is a switch that is open or closed by the value on its gate. Each node holds a charge, and the value of a node comes from the strongest signals that reach it through closed switches. Node sizes and transistor strengths are small integers that order the signals: a supply beats any transistor path, a strong transistor beats a weak one, and any driven path beats a stored charge. With these discrete strengths the model handles what a gate-level model cannot: pass transistors, bidirectional switches, buses with several drivers, ratioed nMOS logic, charge storage and charge sharing. It needs no voltages and no equations. This page is in the logic simulation half of logic and circuit simulation: the values are 0, 1 and X, and the work is graph search, not numerical analysis. Its delay model is unit delay per channel-connected component: in each round every component whose inputs changed goes to its new steady state, computed from the values of the round before. Within a component the response is instantaneous.

In plain words

Think of the chip as wires joined by switches. A transistor closes or opens depending on the value at its gate. Power and ground push 1 and 0 into the wires through closed switches. A wire that is cut off from both keeps its last value, like a small bucket of charge.

When two pushes meet, the stronger one wins. A wide transistor pushes harder than a narrow one, and a big wire holds more charge than a small one. If two equal pushes disagree, the result is X, unknown.

The simulator splits the circuit into groups of wires joined by switch channels. It solves each group by itself, then wakes up the groups whose switches changed, and repeats until nothing changes.

The problem

A switch network has input nodes and storage nodes. The input nodes are vdd (value 1), gnd (value 0) and the primary inputs. They have the strength ω\omega, larger than every other strength. Each storage node nn has a size κ(n)\kappa(n) and a stored value v(n)∈{0,1,X}v(n) \in \{0, 1, X\}. Each transistor has a type (n or p), a gate node, two channel terminals and a strength γ\gamma. All sizes are smaller than all strengths. An n-type transistor is in state 1 (closed) when its gate is 1, a p-type one when its gate is 0, and in state X when its gate is X. Otherwise it is open.

A signal on a path through closed transistors has the strength of the weakest element on it: the source (ω\omega for an input, κ(m)\kappa(m) for the charge of a storage node mm) and every transistor. Let S(n)S(n) be the largest strength of a signal that reaches nn. A path to nn is dominant when, at every node mm that it reaches, its strength so far equals S(m)S(m). A path that reaches a node with a stronger signal from elsewhere is blocked there. With every transistor in state 0 or 1, the steady-state value of nn is the least upper bound, in the order 0⊑X0 \sqsubseteq X, 1⊑X1 \sqsubseteq X, of the source values of the dominant paths to nn. Two dominant paths with values 0 and 1 give X, as in a bus fight.

When some transistors are in state X, the exact steady-state value is the least upper bound over all ways to make each of them open or closed. That can take time exponential in the number of X transistors, so the simulator computes a sound approximation.

The algorithm

The network is split once into channel-connected components: storage nodes joined through transistor channels, with the input nodes left out. A component reads the gates of its transistors and the input nodes on its edge, so it can be solved alone.

  1. SIMULATE(network, inputs, init)
  2. 1val ← init; set the inputs, vdd ← 1, gnd ← 0
  3. 2split the storage nodes into channel-connected components
  4. 3queue ← all components
  5. 4while queue is not empty (one round, one unit of delay)
  6. 5for each component P in queue: new(P) ← STEADY(P, val)
  7. 6changed ← the nodes whose new value differs; val ← new
  8. 7queue ← the components with a changed node or a transistor gated by one
  9. 8return val
  10. STEADY(P, val)
  11. 9for each transistor of P: state ← 1, 0 or X from the value at its gate
  12. 10S ← widest-path strengths from all sources, through transistors in state 1
  13. 11for b in {0, 1}
  14. 12reach_b ← widest paths from the sources of value b or X, through transistors in
  15. state 1 or X, keeping a signal at node m only if its strength is at least S(m)
  16. 13for each node n of P: value ← X if both reach_0 and reach_1 get to n, else the one that does
  17. 14return the values

Line L10 is a widest-path search, run like Dijkstra's algorithm with the largest strength first: a node starts with its own size, or the strength of a closed transistor to an input node, and a transistor of strength γ\gamma passes min⁡(S(u),γ)\min(S(u), \gamma) from uu to its other side. The strengths SS use only the transistors that are certainly closed, so they are the definite strengths: no choice for the X transistors can make a node weaker. Line L12 runs the same search over the potential paths, which may use X transistors, but drops a signal at any node where it is weaker than the definite strength there. Such a signal is blocked in every choice for the X transistors. If no surviving signal of value 0 reaches nn, no dominant path of value 0 reaches nn in any choice, so nn is 1. This is in the spirit of the definite and potential paths of MOSSIM II, though not a copy of its equations.

When all transistors are in state 0 or 1, the two kinds of path are the same, and the floor test of line L12 keeps exactly the dominant paths, so STEADY computes the steady state of the definition. Sources with value X take part in both searches and give X.

Example

A precharged bus: node bus (size 2) is precharged to 1 through a p transistor gated by ϕ\phi, and two small nodes c1 and c2 (size 1, value 0) hang on it through n transistors gated by e. All transistors have strength 10. Take ϕ=1\phi = 1 (precharge off) and e = 1.

step bus c1 c2
stored values 1 0 0
sizes 2 1 1
L10, strengths SS 2 min⁡(2,10)=2\min(2, 10) = 2 min⁡(2,10,10)=2\min(2, 10, 10) = 2
L12, value 1 from the charge of bus 2 2 2
L12, value 0 from c1 and c2 dropped: 1<S=21 < S = 2 dropped dropped
L13, new values 1 1 1

The large node wins the charge sharing. With all three sizes equal, both searches reach every node and the result is X: the final voltage depends on the capacitances, and the model does not claim to know it.

For the CMOS NAND gate with inputs a and b, where the output out reaches gnd through n transistors in series with an internal node m between them, a = 1 and b = 0 give out = 1 through the p transistor of b, and m joins out through the closed n transistor of a, so m = 1 with strength 10. With a = 0 and b = X, out still gets 1: the definite strength of out is 10 through the p transistor of a, and every 0 signal (the small charges of out and m) is dropped at line L12. With a = 1 and b = X, out = X, which is correct, since b = 0 and b = 1 give different outputs.

Correctness

The proof in proofs/correctness.md shows the following, all exactly.

  1. The search of line L10 gives S(n)S(n), the largest signal strength at nn, and following its tree gives a dominant path to every node.
  2. With every transistor in state 0 or 1, STEADY returns exactly the least upper bound of the source values of the dominant paths, which is the definition of the steady state.
  3. STEADY is monotone: if every value in val is replaced by a value at least as high in the information order, every result goes up or stays. With 2, this gives soundness: each 0 or 1 that STEADY gives is the value for every binary completion of the X values on the gates, inputs and stored charges.
  4. STEADY of a component reads only its own nodes, the gates of its transistors and the input nodes. A component that is not queued has none of these changed, so solving only the queued components gives the same rounds as solving all of them in every round. When the queue is empty, the values are a fixed point of one round. The rounds of SIMULATE from a three-valued start bound, round by round, the rounds from every binary completion of the start.

The tests compare STEADY on random networks with a brute force that lists every simple path and applies the definition, check soundness against all completions, check monotonicity and the bound on whole runs, and check hand-worked networks: CMOS inverter, NAND and NOR gates with their internal nodes, a ratioed nMOS inverter, a dynamic latch that keeps its charge, charge sharing by size, a bus fight, a blocked weak path, a latch of two inverters and a ring of three inverters that never settles.

Proof: The steady state of a component is exact for binary switches and monotone with X, and the rounds bound every binary runfull

Setting. Fix a component PP and the values val of all nodes. Lines L9 to L14 refer to STEADY on the page. Each transistor of PP has a state in {0,1,X}\{0, 1, X\} from its gate. Let GDG_D be the graph of the transistors in state 1 and GPG_P the graph of the transistors in state 1 or X, so GD⊆GPG_D \subseteq G_P. A source is either the charge of a storage node mm, with strength κ(m)\kappa(m) and value val(m)\mathrm{val}(m), entering at mm, or an input node uu joined to a storage node ww by a transistor of strength γ\gamma, giving strength min⁡(ω,γ)=γ\min(\omega, \gamma) = \gamma and value val(u)\mathrm{val}(u) at ww. A path is a source followed by a walk through storage nodes of PP along transistors. Its prefix strength at a node mm on it is the least of the source strength and the strengths of the transistors passed so far. Prefix strengths do not increase along a path.

Let S(n)S(n) be the largest prefix strength at nn over all paths in GDG_D that end at nn. A path in a graph GG is dominant in GG if its prefix strength at each node mm it passes is SG(m)S_G(m). For binary transistor states GD=GPG_D = G_P, and the steady state σ(n)\sigma(n) is the least upper bound of the values of the sources of the dominant paths that end at nn.

Lemma 1 (widest paths). The function widest with seeds and an optional floor returns, for each node ww, the largest prefix strength at ww over the paths whose prefix strength at every node mm they pass is at least the floor of mm, or NONE if there is none. Without a floor this is SS when run on GDG_D (line L10).

Proof. This is Dijkstra's algorithm in the order "largest first" for the path value "least strength so far", filtered by the floor. The filter p↦pp \mapsto p if p≥floor(w)p \ge \mathrm{floor}(w), else NONE, does not decrease when pp grows, and min⁡(⋅,γ)\min(\cdot, \gamma) does not either. Claim: when a node uu is taken from the heap the first time, its label B(u)B(u) is final. Every node still in the heap or not reached has a label of at most B(u)B(u), because the heap gives the largest first. Take any admissible path to uu and the first node xx on it that was not yet taken. The prefix strength at xx is at most the label of xx, since the predecessor of xx on the path was taken and relaxed its edge to xx with a label at least the prefix strength there (by induction on the order of taking), or xx is the first node of the path and gets its seed. So the prefix strength at xx is at most B(u)B(u), and it can only fall from xx to uu. Labels are always prefix strengths of admissible paths, so B(u)B(u) is the largest. □\square

Lemma 2 (a dominant path to every node). For every node nn of PP there is a path in GDG_D that is dominant in GDG_D and ends at nn, and its source is in the seeds of line L10.

Proof. Follow the predecessor that set the final label of each node in the search of line L10 back to a seed. Along this chain the label of each node equals the least of the label of its predecessor and the transistor strength between them, so the prefix strength at each node is its final label S(m)S(m). □\square

Theorem 1 (exact for binary switches). If every transistor of PP is in state 0 or 1, STEADY returns σ(n)\sigma(n) for every node nn, also when some sources have the value X.

Proof. Now GP=GDG_P = G_D. Every prefix strength at mm is at most S(m)S(m), by the definition of SS. So the floor test of line L12, prefix strength at least S(m)S(m), holds exactly when the prefix strength equals S(m)S(m), that is, on dominant paths. By Lemma 1, reachb(n)≠\mathrm{reach}_b(n) \ne NONE exactly when a dominant path from a source of value bb or X ends at nn. By Lemma 2 at least one dominant path ends at nn, so at least one of reach0(n)\mathrm{reach}_0(n), reach1(n)\mathrm{reach}_1(n) is set. If only reach1(n)\mathrm{reach}_1(n) is set, every dominant path comes from a source of value 1, so σ(n)=1\sigma(n) = 1, which line L13 returns. The case of 0 is the same. If both are set, either two dominant paths have values 0 and 1, or one has value X, and in both cases σ(n)=X\sigma(n) = X. □\square

Theorem 2 (monotone). Let val and val' agree on vdd and gnd and satisfy val⊑val′\mathrm{val} \sqsubseteq \mathrm{val'} at every node. Then STEADY(P,val)(n)⊑STEADY(P,val′)(n)\mathrm{STEADY}(P, \mathrm{val})(n) \sqsubseteq \mathrm{STEADY}(P, \mathrm{val'})(n) for every nn.

Proof. The state of a transistor is monotone in its gate value, so each state under val is ⊑\sqsubseteq its state under val'. A transistor in state 1 under val' is in state 1 under val, because only 1 is below 1. So GD′⊆GDG'_D \subseteq G_D and, by the definition of SS as a maximum, S′≤SS' \le S. A transistor that is not open under val is not open under val', so GP⊆GP′G_P \subseteq G'_P. A source of value bb or X under val has value bb or X under val'. Now take a path counted in reachb(n)\mathrm{reach}_b(n) under val: it lies in GP⊆GP′G_P \subseteq G'_P, its source qualifies under val', and its prefix strength at each mm is at least S(m)≥S′(m)S(m) \ge S'(m). So it is counted in reachb′(n)\mathrm{reach}'_b(n). Let R(n)={b:reachb(n)≠NONE}R(n) = \{b : \mathrm{reach}_b(n) \ne \mathrm{NONE}\}. We have shown R(n)⊆R′(n)R(n) \subseteq R'(n), and R(n)R(n) is not empty: the path of Lemma 2 lies in GD⊆GPG_D \subseteq G_P, has prefix strength S(m)S(m) at each mm, and its source has a value 0, 1 or X. Line L13 maps {0}\{0\} to 0, {1}\{1\} to 1 and {0,1}\{0, 1\} to X, and this map is monotone from sets under inclusion to values under ⊑\sqsubseteq. □\square

Corollary (soundness). Let cc be a binary completion of val: c(m)=val(m)c(m) = \mathrm{val}(m) where val is binary and c(m)∈{0,1}c(m) \in \{0, 1\} elsewhere. Then σc(n)⊑STEADY(P,val)(n)\sigma_c(n) \sqsubseteq \mathrm{STEADY}(P, \mathrm{val})(n), where σc\sigma_c is the steady state of the definition under cc. So a 0 or 1 from STEADY is the steady-state value for every completion.

Proof. Under cc every transistor is in state 0 or 1, so σc=STEADY(P,c)\sigma_c = \mathrm{STEADY}(P, c) by Theorem 1, and c⊑valc \sqsubseteq \mathrm{val} gives the claim by Theorem 2. □\square

Theorem 3 (rounds). Let Φ\Phi map val to the values obtained by applying STEADY to every component with the input nodes fixed. Then SIMULATE computes valr=Φ(valr−1)\mathrm{val}_r = \Phi(\mathrm{val}_{r-1}) in round rr, and when its queue is empty, valr\mathrm{val}_r is a fixed point of Φ\Phi. If c0⊑v0c_0 \sqsubseteq v_0, the runs cr=Φ(cr−1)c_r = \Phi(c_{r-1}) and vr=Φ(vr−1)v_r = \Phi(v_{r-1}) satisfy cr⊑vrc_r \sqsubseteq v_r for all rr. So if the run from v0v_0 settles in TT and the run from a binary completion c0c_0 of v0v_0 settles in BB, then B⊑TB \sqsubseteq T.

Proof. STEADY on PP reads only the values of the nodes of PP and of the gates of its transistors, and the fixed input nodes. Line L7 queues every component with such a value changed in the round before. Invariant: after round rr, every component QQ that is not in the queue satisfies STEADY(Q,valr)=valr∣Q\mathrm{STEADY}(Q, \mathrm{val}_r) = \mathrm{val}_r|_Q. If QQ was solved in round rr, then valr∣Q=STEADY(Q,valr−1)\mathrm{val}_r|_Q = \mathrm{STEADY}(Q, \mathrm{val}_{r-1}), and nothing it reads changed, so this equals STEADY(Q,valr)\mathrm{STEADY}(Q, \mathrm{val}_r). If QQ was not solved in round rr, the invariant after round r−1r-1 gives STEADY(Q,valr−1)=valr−1∣Q=valr∣Q\mathrm{STEADY}(Q, \mathrm{val}_{r-1}) = \mathrm{val}_{r-1}|_Q = \mathrm{val}_r|_Q, and again nothing it reads changed. Round 1 solves every component. So in every round the components left out would return their present values, and the round equals Φ\Phi. An empty queue means nothing changed, so Φ(valr)=valr\Phi(\mathrm{val}_r) = \mathrm{val}_r. By Theorem 2, Φ\Phi is monotone, and induction on rr gives cr⊑vrc_r \sqsubseteq v_r. If both runs settle, at rounds kk and k′k', take r≥max⁡(k,k′)r \ge \max(k, k'): B=cr⊑vr=TB = c_r \sqsubseteq v_r = T. □\square

Theorem 3 compares runs of the same unit-delay model. It does not say that a real circuit, with its own delays, behaves like any of these runs; inside a component the model takes every change as instant. The X pessimism shown on the page (an n and a p transistor in parallel, both gated by X) is a case where the inclusion of the Corollary is strict.

Complexity

A component with nn storage nodes and tt transistors costs three widest-path searches with a binary heap, O((n+t)log⁡n)O((n + t) \log n). A round costs at most O((N+T)log⁡N)O((N + T) \log N) for the whole network, and the run costs O(R(N+T)log⁡N)O(R (N + T) \log N), where RR is the number of rounds. On a circuit without feedback, RR is at most one more than the number of components on the longest chain of gate connections. With feedback, the run may not settle at all, as in a ring oscillator, and the implementation stops after a fixed number of rounds. The space is O(N+T)O(N + T).

These are proved bounds on the work per round. How much work the queue saves in practice is measured, not proved: on a chain of 20 inverters, settling from all X takes 59 component solves.

Properties

  • Exact for binary transistor states. With no X on any transistor gate, the result is the steady state of the definition.
  • Sound with X. A node that gets 0 or 1 has that value for every completion of the X values. In the tests, 393 of 407 random component nodes got exactly the least upper bound over all completions; the others got X where a completion analysis gives a binary value.
  • X pessimism. Take an n transistor and a p transistor in parallel from vdd to a node that stores 0, both gated by s. With s = 0 or s = 1, one of them conducts and the node is 1. With s = X, neither is definite, the stored 0 survives the floor test, and the result is X. The model treats the two transistors as independent, as ternary gate simulation treats the two branches of reconvergent fanout.
  • Bidirectional. Signals flow either way through a transistor channel. No direction is assigned in advance.
  • Unit delay per component. Delays inside a component are zero, so a race inside one component is not visible.

Variants and improvements

  • MOSSIM II. Bryant's simulator of 1984 uses the same sizes and strengths and solves each component by a relaxation over a discrete algebra with definite and potential strengths.
  • Symbolic and fault simulation. COSMOS compiles each component into Boolean equations and simulates them as code, MOSSIM can run many faulty copies at once (FMOSSIM), and symbolic trajectory evaluation runs the switch-level model over symbolic values.
  • Delays. Switch-level timing simulators attach RC delays to the switches, as in Elmore delay estimates on RC trees, and move toward timing simulation.
  • Gate recognition. A tool can recognize standard gates in the components and simulate them at gate level, keeping the switch model only for pass transistors and buses.

When to use it

Use switch-level simulation to check a full-custom or transistor-level design, extracted from layout by circuit extraction, when it uses pass transistors, dynamic nodes, precharged buses or ratioed logic that a gate model cannot express. It runs much faster than timing simulation or a full circuit simulator, since it computes no voltages. Do not use it for analog behavior, timing margins or charge sharing whose result depends on exact capacitances; it gives X there.

Pitfalls

  • Sizes not below strengths. The model needs every node size below every transistor strength. Otherwise a charge could beat a driven path.
  • Reading X as a circuit fault. An X can come from X pessimism, from equal fights that a real circuit would resolve by ratio, or from charge sharing between equal nodes. Check the cause before changing the design.
  • Forgetting the internal nodes. Internal nodes of series stacks hold charge and take part in charge sharing. Leaving them out hides real bugs.
  • Treating oscillation as an error of the simulator. A ring of inverters has no steady state. The rounds keep changing, and the limit on rounds stops the run.

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.

switch_level_simulation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/switch-level-simulation/. The authors are listed in prov/Z1Y4FS.jsonl.
"""Switch-level simulation of MOS transistor networks with Bryant's strength model.

A transistor is a switch: an n-type one conducts when its gate is 1, a
p-type one when its gate is 0, and its state is X when its gate is X.
Input nodes (vdd, gnd and the primary inputs) are sources of strength OMEGA.
A storage node keeps its charge, a signal whose strength is the node size.
Each transistor has a strength. All sizes are below all transistor strengths,
and OMEGA is above them. A signal on a path has the least strength on the
path. A path is dominant when the signal on it, at every node it passes, is
as strong as the strongest signal at that node. The value of a node is the
least upper bound of the source values of its dominant paths.

With X transistors the steady state uses definite strengths (transistors in
state 1 only) and potential paths (transistors in state 1 or X). The result
is sound: each 0 or 1 holds for every binary choice of the X values.

The storage nodes are split into channel-connected components. A round solves
every component whose transistor gates or own nodes changed, from the values
of the round before. This is a unit-delay model with one delay per component.
"""

from __future__ import annotations

import heapq
from typing import Dict, List, Optional, Sequence, Tuple

X = 2
OMEGA = 10 ** 9
NONE = -1  # no signal


class Oscillation(RuntimeError):
    """The rounds did not reach a steady state within the limit."""


class Network:
    """Storage nodes with sizes, input nodes, and transistors (kind, gate, a, b, strength)."""

    def __init__(self) -> None:
        self.inputs: List[str] = ["vdd", "gnd"]
        self.size: Dict[str, int] = {}
        self.trans: List[Tuple[str, str, str, str, int]] = []

    def add_input(self, name: str) -> None:
        self.inputs.append(name)

    def add_node(self, name: str, size: int = 1) -> None:
        self.size[name] = size

    def add_transistor(self, kind: str, gate: str, a: str, b: str, strength: int = 10) -> None:
        if kind not in ("n", "p"):
            raise ValueError("a transistor is of type n or p")
        self.trans.append((kind, gate, a, b, strength))

    def is_input(self, n: str) -> bool:
        return n in self.inputs

    def check(self) -> None:
        """Every terminal is a node, and every size is below every transistor strength."""
        known = set(self.inputs) | set(self.size)
        for kind, g, a, b, s in self.trans:
            if not {g, a, b} <= known:
                raise ValueError("a transistor terminal is not a node")
            if self.size and s <= max(self.size.values()):
                raise ValueError("every transistor strength must be above every node size")


def channel_connected_components(net: Network) -> List[Tuple[List[str], List[int]]]:
    """Storage nodes joined by source-drain connections, input nodes left out.

    Returns a list of (storage nodes, indices of the transistors with a storage terminal in it).
    """
    parent = {n: n for n in net.size}

    def find(x: str) -> str:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    for kind, g, a, b, s in net.trans:
        if a in parent and b in parent:
            parent[find(a)] = find(b)
    groups: Dict[str, Tuple[List[str], List[int]]] = {}
    for n in net.size:
        groups.setdefault(find(n), ([], []))[0].append(n)
    for i, (kind, g, a, b, s) in enumerate(net.trans):
        end = a if a in parent else (b if b in parent else None)
        if end is not None:
            groups[find(end)][1].append(i)
    return list(groups.values())


def switch_state(kind: str, gate_value: int) -> int:
    """1 = conducting, 0 = open, X = unknown."""
    if gate_value == X:
        return X
    return gate_value if kind == "n" else 1 - gate_value


def widest(nodes: Sequence[str], seeds: Dict[str, int], adj: Dict[str, List[Tuple[str, int]]],
           floor: Optional[Dict[str, int]] = None) -> Dict[str, int]:
    """Strongest signal at each node: max over paths of the least strength on the path.

    seeds gives the strength that enters each node directly. With floor, a signal
    enters node w only when its strength is at least floor[w].
    """
    best = {n: NONE for n in nodes}
    for n, s in seeds.items():
        if floor is None or s >= floor[n]:
            best[n] = max(best[n], s)
    heap = [(-s, n) for n, s in best.items() if s != NONE]
    heapq.heapify(heap)
    done = set()
    while heap:
        s, u = heapq.heappop(heap)
        if u in done:
            continue
        done.add(u)
        for w, gamma in adj[u]:
            c = min(best[u], gamma)
            if c > best[w] and (floor is None or c >= floor[w]):
                best[w] = c
                heapq.heappush(heap, (-c, w))
    return best


def steady_state(net: Network, nodes: Sequence[str], trans: Sequence[int],
                 val: Dict[str, int]) -> Tuple[Dict[str, int], Dict[str, int]]:
    """Steady state of one component for the transistor states and charges in val.

    Returns (new values, definite strengths) of the storage nodes of the component.
    """
    on: Dict[str, List[Tuple[str, int]]] = {n: [] for n in nodes}
    maybe: Dict[str, List[Tuple[str, int]]] = {n: [] for n in nodes}
    feed_on: List[Tuple[str, str, int]] = []  # (storage node, input node, strength)
    feed_maybe: List[Tuple[str, str, int]] = []
    for i in trans:  # @line L9
        kind, g, a, b, gamma = net.trans[i]
        state = switch_state(kind, val[g])
        if state == 0:
            continue
        for u, w in ((a, b), (b, a)):
            if w not in on:
                continue
            if net.is_input(u):
                feed_maybe.append((w, u, gamma))
                if state == 1:
                    feed_on.append((w, u, gamma))
            else:
                maybe[w].append((u, gamma))
                if state == 1:
                    on[w].append((u, gamma))
    seeds = {n: net.size[n] for n in nodes}  # @line L10
    for w, u, gamma in feed_on:
        seeds[w] = max(seeds[w], gamma)
    strength = widest(nodes, seeds, on)
    reach: Dict[int, Dict[str, int]] = {}
    for b in (0, 1):  # @line L11
        seeds_b: Dict[str, int] = {n: net.size[n] for n in nodes if val[n] in (b, X)}  # @line L12
        for w, u, gamma in feed_maybe:
            if val[u] in (b, X):
                seeds_b[w] = max(seeds_b.get(w, NONE), gamma)
        reach[b] = widest(nodes, seeds_b, maybe, floor=strength)
    new: Dict[str, int] = {}
    for n in nodes:  # @line L13
        r0, r1 = reach[0][n] != NONE, reach[1][n] != NONE
        new[n] = X if (r0 and r1) else (1 if r1 else 0)
    return new, strength  # @line L14


def simulate(net: Network, inputs: Dict[str, int], init: Dict[str, int],
             max_rounds: int = 200) -> Tuple[Dict[str, int], int]:
    """Settle the network for fixed input values from the stored values init.

    Returns (values of all nodes, number of component solves).
    """
    net.check()
    val = {n: init.get(n, X) for n in net.size}  # @line L1
    val.update(inputs)
    val["vdd"], val["gnd"] = 1, 0
    comps = channel_connected_components(net)  # @line L2
    readers: Dict[str, List[int]] = {}  # components whose solve reads the node
    for ci, (nodes, trans) in enumerate(comps):
        for n in nodes:
            readers.setdefault(n, []).append(ci)
        for i in trans:
            readers.setdefault(net.trans[i][1], []).append(ci)
    queue = list(range(len(comps)))  # @line L3
    rounds = solves = 0
    while queue:  # @line L4
        rounds += 1
        if rounds > max_rounds:
            raise Oscillation(f"no steady state after {max_rounds} rounds")
        new: Dict[str, int] = {}
        for ci in queue:  # @line L5
            new.update(steady_state(net, comps[ci][0], comps[ci][1], val)[0])
            solves += 1
        changed = [n for n, v in new.items() if v != val[n]]  # @line L6
        val.update(new)
        queue = sorted({ci for n in changed for ci in readers.get(n, [])})  # @line L7
    return val, solves  # @line L8
test_switch_level_simulation.py 423 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/switch-level-simulation/. The authors are listed in prov/Z1Y4FS.jsonl.
"""Tests for switch-level simulation: hand-worked transistor networks, the path
definition of the steady state by brute force, and soundness of X results."""

import itertools
import random

import pytest

from switch_level_simulation import (
    NONE, OMEGA, X, Network, Oscillation, channel_connected_components, simulate,
    steady_state, switch_state,
)


def lub(u, v):
    return u if u == v else X


def leq(u, v):
    return u == v or v == X


# ---------------------------------------------------------------- networks

def inverter(net, a, out, strength=10):
    net.add_transistor("p", a, "vdd", out, strength)
    net.add_transistor("n", a, out, "gnd", strength)


def nand2():
    net = Network()
    net.add_input("a")
    net.add_input("b")
    net.add_node("out")
    net.add_node("m")
    net.add_transistor("p", "a", "vdd", "out")
    net.add_transistor("p", "b", "vdd", "out")
    net.add_transistor("n", "a", "out", "m")
    net.add_transistor("n", "b", "m", "gnd")
    return net


def nor2():
    net = Network()
    net.add_input("a")
    net.add_input("b")
    net.add_node("out")
    net.add_node("m")
    net.add_transistor("p", "a", "vdd", "m")
    net.add_transistor("p", "b", "m", "out")
    net.add_transistor("n", "a", "out", "gnd")
    net.add_transistor("n", "b", "out", "gnd")
    return net


def run(net, inputs, init=None):
    return simulate(net, inputs, init or {})[0]


# ---------------------------------------------------------------- hand-worked networks

def test_switch_states():
    assert [switch_state("n", v) for v in (0, 1, X)] == [0, 1, X]
    assert [switch_state("p", v) for v in (0, 1, X)] == [1, 0, X]


def test_cmos_inverter():
    net = Network()
    net.add_input("a")
    net.add_node("y")
    inverter(net, "a", "y")
    assert run(net, {"a": 0})["y"] == 1
    assert run(net, {"a": 1})["y"] == 0
    assert run(net, {"a": X})["y"] == X


def test_nand2_with_internal_node():
    net = nand2()
    expect = {(0, 0): 1, (0, 1): 1, (1, 0): 1, (1, 1): 0}
    for (a, b), y in expect.items():
        assert run(net, {"a": a, "b": b}, {"m": 0})["out"] == y
    # internal node m, worked by hand
    assert run(net, {"a": 0, "b": 1}, {"m": 1})["m"] == 0      # pulled down by n_b
    assert run(net, {"a": 1, "b": 0}, {"m": 0})["m"] == 1      # joined to out through n_a
    assert run(net, {"a": 0, "b": 0}, {"m": 1})["m"] == 1      # isolated: keeps its charge
    assert run(net, {"a": 0, "b": 0}, {"m": 0})["m"] == 0


def test_nand2_x_input():
    net = nand2()
    # a = 0 holds out at 1 through p_a, whatever b is.
    assert run(net, {"a": 0, "b": X}, {"m": 0})["out"] == 1
    assert run(net, {"a": X, "b": 0}, {"m": 0})["out"] == 1
    # a = 1, b = X: out can be 0 or 1.
    assert run(net, {"a": 1, "b": X}, {"m": 0})["out"] == X


def test_nor2():
    net = nor2()
    expect = {(0, 0): 1, (0, 1): 0, (1, 0): 0, (1, 1): 0}
    for (a, b), y in expect.items():
        assert run(net, {"a": a, "b": b}, {"m": 0})["out"] == y
    assert run(net, {"a": 1, "b": X}, {"m": 0})["out"] == 0


def test_ratioed_nmos_inverter():
    net = Network()
    net.add_input("a")
    net.add_node("y")
    net.add_transistor("n", "vdd", "vdd", "y", 4)   # load, always on, weak
    net.add_transistor("n", "a", "y", "gnd", 8)     # pull-down, strong
    assert run(net, {"a": 0})["y"] == 1
    assert run(net, {"a": 1})["y"] == 0
    assert run(net, {"a": X})["y"] == X


def test_dynamic_latch_keeps_charge():
    net = Network()
    net.add_input("d")
    net.add_input("phi")
    net.add_node("s")
    net.add_node("q")
    net.add_transistor("n", "phi", "d", "s")
    inverter(net, "s", "q")
    v = run(net, {"d": 1, "phi": 1})
    assert (v["s"], v["q"]) == (1, 0)
    v = run(net, {"d": 0, "phi": 0}, {"s": v["s"], "q": v["q"]})
    assert (v["s"], v["q"]) == (1, 0)                   # stored, d is cut off
    v = run(net, {"d": 0, "phi": 1}, {"s": v["s"], "q": v["q"]})
    assert (v["s"], v["q"]) == (0, 1)


def charge_pair(size_a, size_b):
    net = Network()
    net.add_input("e")
    net.add_node("a", size_a)
    net.add_node("b", size_b)
    net.add_transistor("n", "e", "a", "b")
    return net


def test_charge_sharing_by_size():
    v = run(charge_pair(2, 1), {"e": 1}, {"a": 1, "b": 0})
    assert (v["a"], v["b"]) == (1, 1)                   # the larger node wins
    v = run(charge_pair(1, 2), {"e": 1}, {"a": 1, "b": 0})
    assert (v["a"], v["b"]) == (0, 0)
    v = run(charge_pair(1, 1), {"e": 1}, {"a": 1, "b": 0})
    assert (v["a"], v["b"]) == (X, X)                   # equal sizes: unknown
    v = run(charge_pair(1, 1), {"e": 0}, {"a": 1, "b": 0})
    assert (v["a"], v["b"]) == (1, 0)                   # switch open: both keep
    v = run(charge_pair(2, 1), {"e": X}, {"a": 1, "b": 0})
    assert (v["a"], v["b"]) == (1, X)


def bus(sa, sb):
    net = Network()
    net.add_input("a")
    net.add_input("b")
    net.add_node("bus")
    net.add_transistor("n", "a", "vdd", "bus", sa)
    net.add_transistor("n", "b", "bus", "gnd", sb)
    return net


def test_bus_fight():
    assert run(bus(10, 10), {"a": 1, "b": 1})["bus"] == X
    assert run(bus(10, 6), {"a": 1, "b": 1})["bus"] == 1
    assert run(bus(6, 10), {"a": 1, "b": 1})["bus"] == 0
    assert run(bus(10, 10), {"a": 1, "b": 0})["bus"] == 1
    assert run(bus(10, 10), {"a": 0, "b": 0}, {"bus": 0})["bus"] == 0
    assert run(bus(10, 6), {"a": 1, "b": X})["bus"] == 1     # the stronger side is on
    assert run(bus(10, 6), {"a": X, "b": 1})["bus"] == X


def test_strongest_signal_blocks_weaker_path():
    # vdd -5- m, gnd -10- m, m -5- n: the vdd signal is blocked at m.
    net = Network()
    net.add_node("m")
    net.add_node("n")
    net.add_transistor("n", "vdd", "vdd", "m", 5)
    net.add_transistor("n", "vdd", "gnd", "m", 10)
    net.add_transistor("n", "vdd", "m", "n", 5)
    v = run(net, {}, {"m": 1, "n": 1})
    assert (v["m"], v["n"]) == (0, 0)


def test_documented_x_pessimism():
    # Two transistors in parallel from vdd, one n-type and one p-type, both gated by s.
    # For s = 0 or s = 1 one of them conducts, so out = 1. With s = X both are in
    # state X, no path is definite, and the stored 0 may survive: the result is X.
    net = Network()
    net.add_input("s")
    net.add_node("out")
    net.add_transistor("n", "s", "vdd", "out")
    net.add_transistor("p", "s", "vdd", "out")
    assert run(net, {"s": 0}, {"out": 0})["out"] == 1
    assert run(net, {"s": 1}, {"out": 0})["out"] == 1
    assert run(net, {"s": X}, {"out": 0})["out"] == X
    assert run(net, {"s": X}, {"out": 1})["out"] == 1


def test_ring_oscillator_never_settles():
    net = Network()
    for k in range(3):
        net.add_node(f"n{k}")
    for k in range(3):
        inverter(net, f"n{k}", f"n{(k + 1) % 3}")
    with pytest.raises(Oscillation):
        simulate(net, {}, {"n0": 0, "n1": 1, "n2": 0}, max_rounds=50)
    v, _ = simulate(net, {}, {})                         # all X is a fixed point
    assert [v[f"n{k}"] for k in range(3)] == [X, X, X]


def test_cross_coupled_inverters_hold():
    net = Network()
    net.add_node("q")
    net.add_node("qb")
    inverter(net, "q", "qb")
    inverter(net, "qb", "q")
    v = run(net, {}, {"q": 1, "qb": 0})
    assert (v["q"], v["qb"]) == (1, 0)
    v = run(net, {}, {"q": 0, "qb": 1})
    assert (v["q"], v["qb"]) == (0, 1)


def test_channel_connected_components():
    net = nand2()
    comps = channel_connected_components(net)
    assert sorted(sorted(c[0]) for c in comps) == [["m", "out"]]
    chain = Network()
    chain.add_input("a")
    names = ["a"] + [f"y{k}" for k in range(4)]
    for k in range(4):
        chain.add_node(names[k + 1])
        inverter(chain, names[k], names[k + 1])
    assert len(channel_connected_components(chain)) == 4
    tg = Network()
    tg.add_input("s")
    tg.add_input("sb")
    for n in ("u", "w"):
        tg.add_node(n)
    tg.add_transistor("n", "s", "u", "w")
    tg.add_transistor("p", "sb", "u", "w")
    assert sorted(sorted(c[0]) for c in channel_connected_components(tg)) == [["u", "w"]]


def test_check_rejects_sizes_above_strengths():
    net = Network()
    net.add_node("y", 5)
    net.add_transistor("n", "vdd", "vdd", "y", 3)
    with pytest.raises(ValueError):
        simulate(net, {}, {})


# ---------------------------------------------------------------- brute force

def random_network(rng, k):
    net = Network()
    for name in ("i0", "i1"):
        net.add_input(name)
    for j in range(k):
        net.add_node(f"s{j}", rng.choice((1, 2)))
    storage = [f"s{j}" for j in range(k)]
    for _ in range(rng.randint(k, k + 4)):
        a = rng.choice(storage)
        b = rng.choice([n for n in storage + net.inputs if n != a])
        g = rng.choice(storage + ["i0", "i1"])
        net.add_transistor(rng.choice("np"), g, a, b, rng.choice((3, 4, 5)))
    return net


def brute_steady(net, nodes, trans, val):
    """The path definition, by enumeration of simple paths. Transistor gates must be binary."""
    adj = {n: [] for n in nodes}
    starts = [(m, net.size[m], val[m]) for m in nodes]
    for i in trans:
        kind, g, a, b, gamma = net.trans[i]
        assert val[g] != X
        if switch_state(kind, val[g]) == 0:
            continue
        for u, w in ((a, b), (b, a)):
            if w in adj:
                if net.is_input(u):
                    starts.append((w, gamma, val[u]))
                else:
                    adj[w].append((u, gamma))
    paths = []  # (list of (node, prefix strength), source value)

    def extend(path, value):
        paths.append((list(path), value))
        node, p = path[-1]
        on_path = {m for m, _ in path}
        for w, gamma in adj[node]:
            if w not in on_path:
                path.append((w, min(p, gamma)))
                extend(path, value)
                path.pop()

    for m, s, v in starts:
        extend([(m, s)], v)
    strength = {n: max(p for path, _ in paths for m, p in path if m == n) for n in nodes}
    value = {}
    for path, v in paths:
        if all(p == strength[m] for m, p in path):
            n = path[-1][0]
            value[n] = v if n not in value else lub(value[n], v)
    return value, strength


def relevant(net, nodes, trans):
    names = set(nodes)
    for i in trans:
        kind, g, a, b, s = net.trans[i]
        names |= {g, a, b}
    return sorted(names - {"vdd", "gnd"})


def random_val(rng, net, p_x):
    val = {n: (X if rng.random() < p_x else rng.randint(0, 1)) for n in list(net.size) + ["i0", "i1"]}
    val["vdd"], val["gnd"] = 1, 0
    return val


def test_binary_steady_state_matches_path_definition():
    rng = random.Random(41)
    checked = 0
    for _ in range(300):
        net = random_network(rng, rng.randint(1, 5))
        val = random_val(rng, net, 0.0)
        for nodes, trans in channel_connected_components(net):
            got, strength = steady_state(net, nodes, trans, val)
            want, want_strength = brute_steady(net, nodes, trans, val)
            assert strength == want_strength
            assert got == want
            checked += len(nodes)
    assert checked > 500


def test_x_charges_with_binary_gates_match_path_definition():
    rng = random.Random(42)
    for _ in range(200):
        net = random_network(rng, rng.randint(1, 5))
        val = random_val(rng, net, 0.3)
        for n in ("i0", "i1"):
            val[n] = rng.randint(0, 1)
        for nodes, trans in channel_connected_components(net):
            if any(val[net.trans[i][1]] == X for i in trans):
                continue
            assert steady_state(net, nodes, trans, val)[0] == brute_steady(net, nodes, trans, val)[0]


def completions(val, names):
    free = [n for n in names if val[n] == X]
    for bits in itertools.product((0, 1), repeat=len(free)):
        c = dict(val)
        c.update(zip(free, bits))
        yield c


def test_ternary_steady_state_is_sound():
    rng = random.Random(43)
    exact = total = 0
    for _ in range(150):
        net = random_network(rng, rng.randint(1, 4))
        val = random_val(rng, net, 0.35)
        for nodes, trans in channel_connected_components(net):
            got, _ = steady_state(net, nodes, trans, val)
            best = {}
            for c in completions(val, relevant(net, nodes, trans)):
                want, _ = brute_steady(net, nodes, trans, c)
                for n in nodes:
                    best[n] = want[n] if n not in best else lub(best[n], want[n])
            for n in nodes:
                assert leq(best[n], got[n])
                total += 1
                exact += best[n] == got[n]
    assert total > 200 and exact > total // 2


def test_steady_state_is_monotone():
    rng = random.Random(44)
    for _ in range(300):
        net = random_network(rng, rng.randint(1, 5))
        val = random_val(rng, net, 0.2)
        up = {n: (X if rng.random() < 0.3 and n not in ("vdd", "gnd") else v) for n, v in val.items()}
        for nodes, trans in channel_connected_components(net):
            lo, _ = steady_state(net, nodes, trans, val)
            hi, _ = steady_state(net, nodes, trans, up)
            assert all(leq(lo[n], hi[n]) for n in nodes)


def test_simulate_is_sound_against_binary_runs():
    rng = random.Random(45)
    settled = compared = 0
    for _ in range(120):
        net = random_network(rng, rng.randint(2, 5))
        inputs = {"i0": rng.choice((0, 1, X)), "i1": rng.choice((0, 1, X))}
        init = {n: rng.choice((0, 1, X)) for n in net.size}
        try:
            top, _ = simulate(net, inputs, init, max_rounds=60)
        except Oscillation:
            continue
        settled += 1
        start = dict(init)
        start.update(inputs)
        names = [n for n in start if start[n] == X][:6]
        for c in completions(start, names):
            for n in start:
                if c[n] == X:
                    c[n] = 0
            try:
                low, _ = simulate(net, {k: c[k] for k in inputs}, {k: c[k] for k in init}, max_rounds=60)
            except Oscillation:
                continue
            compared += 1
            assert all(leq(low[n], top[n]) for n in net.size)
    assert settled > 60 and compared > 200


def test_constants():
    assert NONE < 0 < X < OMEGA

History

Randal Bryant presented MOSSIM at the Design Automation Conference in 1981. His 1984 paper in the IEEE Transactions on Computers gave the formal model with node sizes, transistor strengths and the steady-state response, and the algorithm of MOSSIM II. Switch-level simulators of this type were used in industry in the 1980s to check microprocessors at the transistor level. Bryant and his students later added compiled simulation (COSMOS) and symbolic simulation, which led to symbolic trajectory evaluation with Seger.

References

  1. R. E. Bryant, A switch-level model and simulator for MOS digital systems, IEEE Transactions on Computers C-33(2), 160 to 177, 1984, the switch graph, node sizes and transistor strengths, the steady-state response with definite and potential paths, the partition into components and the simulation algorithm of MOSSIM II
  2. R. E. Bryant, MOSSIM, a switch-level simulator for MOS LSI, Proceedings of the 18th Design Automation Conference, 786 to 790, 1981, the first switch-level simulator, with node states 0, 1 and X and transistor states open, closed and unknown
  3. M. Abramovici, M. A. Breuer and A. D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter on logic simulation, the part on switch-level models

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.best
  • 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