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.
- Solves
- Logic 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
- Model
- Word RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , larger than every other strength. Each storage node has a size and a stored value . Each transistor has a type (n or p), a gate node, two channel terminals and a strength . 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 ( for an input, for the charge of a storage node ) and every transistor. Let be the largest strength of a signal that reaches . A path to is dominant when, at every node that it reaches, its strength so far equals . 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 is the least upper bound, in the order , , of the source values of the dominant paths to . 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.
SIMULATE(network, inputs, init)- 1
val ← init; set the inputs, vdd ← 1, gnd ← 0 - 2
split the storage nodes into channel-connected components - 3
queue ← all components - 4
while queue is not empty (one round, one unit of delay) - 5
for each component P in queue: new(P) ← STEADY(P, val) - 6
changed ← the nodes whose new value differs; val ← new - 7
queue ← the components with a changed node or a transistor gated by one - 8
return val STEADY(P, val)- 9
for each transistor of P: state ← 1, 0 or X from the value at its gate - 10
S ← widest-path strengths from all sources, through transistors in state 1 - 11
for b in {0, 1} - 12
reach_b ← widest paths from the sources of value b or X, through transistors in state 1 or X, keeping a signal at node m only if its strength is at least S(m)- 13
for each node n of P: value ← X if both reach_0 and reach_1 get to n, else the one that does - 14
return 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 passes from to its other side. The strengths 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 , no dominant path of value 0 reaches in any choice, so 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 , 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 (precharge off) and e = 1.
| step | bus | c1 | c2 |
|---|---|---|---|
| stored values | 1 | 0 | 0 |
| sizes | 2 | 1 | 1 |
| L10, strengths | 2 | ||
| L12, value 1 from the charge of bus | 2 | 2 | 2 |
| L12, value 0 from c1 and c2 | dropped: | 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.
- The search of line L10 gives , the largest signal strength at , and following its tree gives a dominant path to every node.
- 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.
- 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.
- 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 and the values val of all nodes. Lines L9 to L14 refer to STEADY on the page. Each transistor of has a state in from its gate. Let be the graph of the transistors in state 1 and the graph of the transistors in state 1 or X, so . A source is either the charge of a storage node , with strength and value , entering at , or an input node joined to a storage node by a transistor of strength , giving strength and value at . A path is a source followed by a walk through storage nodes of along transistors. Its prefix strength at a node 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 be the largest prefix strength at over all paths in that end at . A path in a graph is dominant in if its prefix strength at each node it passes is . For binary transistor states , and the steady state is the least upper bound of the values of the sources of the dominant paths that end at .
Lemma 1 (widest paths). The function widest with seeds and an optional floor returns, for each node , the largest prefix strength at over the paths whose prefix strength at every node they pass is at least the floor of , or NONE if there is none. Without a floor this is when run on (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 if , else NONE, does not decrease when grows, and does not either. Claim: when a node is taken from the heap the first time, its label is final. Every node still in the heap or not reached has a label of at most , because the heap gives the largest first. Take any admissible path to and the first node on it that was not yet taken. The prefix strength at is at most the label of , since the predecessor of on the path was taken and relaxed its edge to with a label at least the prefix strength there (by induction on the order of taking), or is the first node of the path and gets its seed. So the prefix strength at is at most , and it can only fall from to . Labels are always prefix strengths of admissible paths, so is the largest.
Lemma 2 (a dominant path to every node). For every node of there is a path in that is dominant in and ends at , 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 .
Theorem 1 (exact for binary switches). If every transistor of is in state 0 or 1, STEADY returns for every node , also when some sources have the value X.
Proof. Now . Every prefix strength at is at most , by the definition of . So the floor test of line L12, prefix strength at least , holds exactly when the prefix strength equals , that is, on dominant paths. By Lemma 1, NONE exactly when a dominant path from a source of value or X ends at . By Lemma 2 at least one dominant path ends at , so at least one of , is set. If only is set, every dominant path comes from a source of value 1, so , 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 .
Theorem 2 (monotone). Let val and val' agree on vdd and gnd and satisfy at every node. Then for every .
Proof. The state of a transistor is monotone in its gate value, so each state under val is its state under val'. A transistor in state 1 under val' is in state 1 under val, because only 1 is below 1. So and, by the definition of as a maximum, . A transistor that is not open under val is not open under val', so . A source of value or X under val has value or X under val'. Now take a path counted in under val: it lies in , its source qualifies under val', and its prefix strength at each is at least . So it is counted in . Let . We have shown , and is not empty: the path of Lemma 2 lies in , has prefix strength at each , and its source has a value 0, 1 or X. Line L13 maps to 0, to 1 and to X, and this map is monotone from sets under inclusion to values under .
Corollary (soundness). Let be a binary completion of val: where val is binary and elsewhere. Then , where is the steady state of the definition under . So a 0 or 1 from STEADY is the steady-state value for every completion.
Proof. Under every transistor is in state 0 or 1, so by Theorem 1, and gives the claim by Theorem 2.
Theorem 3 (rounds). Let map val to the values obtained by applying STEADY to every component with the input nodes fixed. Then SIMULATE computes in round , and when its queue is empty, is a fixed point of . If , the runs and satisfy for all . So if the run from settles in and the run from a binary completion of settles in , then .
Proof. STEADY on reads only the values of the nodes of 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 , every component that is not in the queue satisfies . If was solved in round , then , and nothing it reads changed, so this equals . If was not solved in round , the invariant after round gives , 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 . An empty queue means nothing changed, so . By Theorem 2, is monotone, and induction on gives . If both runs settle, at rounds and , take : .
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 storage nodes and transistors costs three widest-path searches with a binary heap, . A round costs at most for the whole network, and the run costs , where is the number of rounds. On a circuit without feedback, 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 .
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.
# 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
- 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
- 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
- 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.
| 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 Z1Y4FS Edit this page History Report an error Markdown