Algorithm Search⌘K

Algorithmadvanced

Timing simulation

Also called MOTIS timing simulation, event-driven timing simulation.

Chawla, Gummel and Kozak's fast transistor simulation that updates node voltages one at a time with simple models and events, skipping the full Newton solve.

Time
O(s (N + T)) worstO(s N + T) best
Space
O(N + T) extra
Where
N = the number of circuit nodes; T = the number of transistors; s = the number of time steps
Properties
deterministicnot exactiterative
Origin
B. R. Chawla, H. K. Gummel, P. Kozak, 1975

Timing simulation computes the node voltages of a large MOS circuit over time, like a circuit simulator, but at a much lower cost per time step. A circuit simulator solves the whole nonlinear system of the circuit at each time point by Newton's method, with a sparse LU factorization at each iteration. MOTIS (Chawla, Gummel and Kozak, 1975) does not. At each time step it visits the nodes one at a time in a fixed order and moves each node voltage by one Newton step on that node's own equation, using the newest voltages of the other nodes. A node whose surroundings did not move is skipped. This page is in the circuit simulation half of logic and circuit simulation, at its fast end: it integrates the node equations of transient circuit analysis with backward Euler, and borrows selective trace from event-driven logic simulation. There is no delay model as on the logic pages. Delays come out of the integration, from the transistor currents and the node capacitances.

In plain words

Picture a chain of logic gates. Each wire between gates holds some charge, and the transistors pour current into it or drain it away. A full circuit simulator works out every wire at once at each tick of the clock, which is accurate but slow.

A timing simulator takes the wires one at a time, from the inputs toward the outputs. For each wire it asks how much current flows in now, and how fast that current would change if the wire's voltage moved. From these two numbers it takes one careful step for the wire, then goes to the next wire, which already sees the new value.

Wires far from any activity hardly move. The simulator notices that and leaves them alone until a neighbour moves again.

The problem

The circuit has NN nodes. Node ii has a capacitance CiC_i to ground, and its current Ii(v)I_i(v) is the sum of the currents flowing into it through the channels of the transistors that touch it. Inputs are voltage sources with given waveforms. The node voltages obey Ci dvi/dt=Ii(v)C_i \, dv_i/dt = I_i(v) for every ii, a stiff system of ordinary differential equations. Backward Euler with step hh asks, at each time point, for the solution vn+1v^{n+1} of

Cih(vin+1−vin)−Ii(vn+1)=0for all i.\frac{C_i}{h}\left(v_i^{n+1} - v_i^n\right) - I_i(v^{n+1}) = 0 \quad \text{for all } i.

In the language of companion models, each capacitor becomes a conductance Ci/hC_i/h with a current source Civin/hC_i v_i^n / h, and the system is the resistive network of modified nodal analysis with only grounded elements. The transistors follow the square-law Shichman-Hodges model: with overdrive VovV_{ov} and channel voltage VDSV_{DS}, the current is 0 in cutoff, k(VovVDS−VDS2/2)k(V_{ov} V_{DS} - V_{DS}^2/2) in the linear region and kVov2/2k V_{ov}^2/2 in saturation. MOTIS itself used tables of the transistor characteristic.

The algorithm

  1. MOTIS(circuit, init, h, t_end, ε)
  2. 1v ← the initial node voltages and the input voltages at time 0; every node is awake
  3. 2for t = h, 2h, ..., t_end
  4. 3set each input to its value at t; wake the nodes that a moved input feeds
  5. 4for each node i in the fixed order
  6. 5if i is asleep: skip it, its voltage stays
  7. 6(I, D) ← the current into i and its derivative in v_i, at the newest voltages
  8. 7v_i ← v_i + h I / (C_i − h D)
  9. 8if v_i moved by more than ε: wake i and the nodes it feeds, later in this step and in the next
  10. 9the awake nodes of the next step are those woken in this step
  11. 10record the voltages at t
  12. 11return the waveforms

Line L7 is one Newton step on the backward Euler equation of node ii alone, started from its old voltage vinv_i^n. With g(x)=Ci(x−vin)/h−Ii(…,x,…)g(x) = C_i (x - v_i^n)/h - I_i(\ldots, x, \ldots), the step x1=vin−g(vin)/g′(vin)x_1 = v_i^n - g(v_i^n)/g'(v_i^n) is exactly vin+hI/(Ci−hD)v_i^n + h I / (C_i - h D). The nodes that come earlier in the order already have their values at tt, and the later ones still have their values at t−ht - h. So one time step is one sweep of nonlinear Gauss-Seidel iteration with one Newton step per node.

The order matters. MOTIS orders the nodes from the inputs toward the outputs, so that a gate sees its input voltage at the new time. When the current into each node depends only on its own voltage and on nodes earlier in the order, as in a chain of gates with grounded capacitors, the backward Euler system is lower triangular, and a sweep that solves each node equation exactly gives the backward Euler solution itself.

With ε=0\varepsilon = 0 every node is updated at every step. With ε>0\varepsilon > 0, a node sleeps once its voltage moves by no more than ε\varepsilon in a step, until a node or input that it reads moves by more than ε\varepsilon.

Example

A chain of four CMOS inverters with VDD=1.8V_{DD} = 1.8 V, threshold 0.5 V, k=200 μA/V2k = 200\ \mu\mathrm{A/V^2} for both transistor types and C=10C = 10 fF on each output. The input rises from 0 to 1.8 V between 0.10 and 0.15 ns, and h=1h = 1 ps. When y1y_1 is still at 1.8 V and the input has reached 1.8 V, the n transistor is saturated and the p transistor is off, so I=−0.5⋅200⋅1.32=−169 μI = -0.5 \cdot 200 \cdot 1.3^2 = -169\ \muA and D=0D = 0, and line L7 moves y1y_1 by hI/C=−16.9hI/C = -16.9 mV. The waveforms (volts):

t (ns) y1y_1 y2y_2 y3y_3 y4y_4
0.10 1.800 0.000 1.800 0.000
0.14 1.719 0.000 1.800 0.000
0.16 1.420 0.000 1.800 0.000
0.18 1.084 0.002 1.800 0.000
0.20 0.777 0.031 1.800 0.000
0.25 0.273 0.370 1.800 0.000
0.30 0.082 1.007 1.769 0.000

The outputs cross 0.9 V at 0.1916, 0.2920, 0.3944 and 0.4969 ns. A classical Runge-Kutta reference with a step of 0.05 ps gives 0.1921, 0.2926, 0.3952 and 0.4979 ns, so each crossing is within 1 ps, and the largest voltage difference on any node is 13 mV.

Correctness

The proof in proofs/correctness.md shows three facts exactly.

  1. If no transistor touching node ii has its gate on node ii, then ∂Ii/∂vi≤0\partial I_i / \partial v_i \le 0 for the square-law model. So g′(x)≥Ci/h>0g'(x) \ge C_i/h > 0: the node equation has exactly one solution, and the denominator of line L7 is at least CiC_i for every step size.
  2. If the order makes the system lower triangular, a sweep that solves each node equation exactly gives the backward Euler solution, with no further iteration.
  3. One Newton step from vinv_i^n lands within Lh3I2/(2Ci3)L h^3 I^2 / (2 C_i^3) of the exact solution of the node equation (with the other voltages fixed), where II is the current at the start of the step and LL, at most the sum of the kk of the transistors at the node, bounds how fast ∂Ii/∂vi\partial I_i/\partial v_i can change.

The rest is measured, not proved. The tests compare with a full backward Euler solve with Newton's method on the whole system and with a Runge-Kutta reference at a step 20 times finer:

  • The sweep with exact node solves agrees with the full backward Euler Newton solution to 1.2⋅10−121.2 \cdot 10^{-12} V on the inverter chain (the test asks for 10−910^{-9}).
  • One Newton step per node stays within 1.2 mV of full backward Euler at h=2h = 2 ps.
  • Against the reference, the largest error is 13 mV at h=1h = 1 ps on the chain and 12 mV on a NAND gate whose internal stack node couples both ways, and every 0.9 V crossing is within 1.5 ps (the stated tolerances are 20 mV and 1.5 ps).
  • The error falls by factors of 2.08, 1.98, 2.03 and 2.01 as hh halves from 8 ps to 0.5 ps: first order, as backward Euler is.

Whether the Gauss-Seidel sweep converges, or how large its error is, when nodes couple both ways through floating capacitors or pass transistors, depends on the circuit; MOTIS gives no bound, and iterated timing analysis repeats the sweep until it converges.

Proof: The node equations of backward Euler have unique solutions, a triangular order gives backward Euler in one sweep, and one Newton step is accurate to third order in hpartial

Setting. Node ii has capacitance Ci>0C_i > 0 and current Ii(v)I_i(v), the sum over the transistors whose channel touches ii of the current flowing into ii. The transistors follow the square-law model of the page with parameter k>0k > 0 and threshold VTV_T. Backward Euler with step hh asks for vn+1v^{n+1} with Gi(vn+1)=0G_i(v^{n+1}) = 0 for all ii, where Gi(v)=Ci(vi−vin)/h−Ii(v)G_i(v) = C_i (v_i - v_i^n)/h - I_i(v). For fixed values of the other nodes, write g(x)=Gi(…,x,…)g(x) = G_i(\ldots, x, \ldots) for the node equation of ii. Lines L1 to L11 refer to the pseudocode of the page.

Lemma 1 (the device). For one transistor, the current into a channel terminal ii is a continuously differentiable function of the terminal voltages. Its derivative in viv_i is at most 0, and it is Lipschitz in viv_i with constant kk, as long as the gate of the transistor is not node ii.

Proof. Take an n transistor; the p case is the same with all voltages negated. Let Vov=vg−vs−VTV_{ov} = v_g - v_s - V_T and VDS=vd−vs≥0V_{DS} = v_d - v_s \ge 0, where the source ss is the lower channel terminal. The current from drain to source is f=0f = 0 for Vov≤0V_{ov} \le 0, f=k(VovVDS−VDS2/2)f = k(V_{ov} V_{DS} - V_{DS}^2/2) for 0≤VDS≤Vov0 \le V_{DS} \le V_{ov} and f=kVov2/2f = k V_{ov}^2/2 for VDS≥Vov≥0V_{DS} \ge V_{ov} \ge 0. On the boundaries the pieces and their first derivatives agree: at VDS=VovV_{DS} = V_{ov} both give kVov2/2k V_{ov}^2/2, ∂f/∂Vov=kVov\partial f/\partial V_{ov} = k V_{ov} and ∂f/∂VDS=0\partial f/\partial V_{DS} = 0; at Vov=0V_{ov} = 0 all are 0. Write gm=∂f/∂Vov≥0g_m = \partial f / \partial V_{ov} \ge 0 and gds=∂f/∂VDS≥0g_{ds} = \partial f / \partial V_{DS} \ge 0. If ii is the drain, the current into ii is −f-f and its derivative in viv_i is −gds≤0-g_{ds} \le 0. If ii is the source, the current into ii is ff and its derivative is −(gm+gds)≤0-(g_m + g_{ds}) \le 0. At vd=vsv_d = v_s the two roles meet, and both derivatives equal −kmax⁡(Vov,0)-k \max(V_{ov}, 0), so the derivative is continuous there. In each region, gdsg_{ds} and gm+gdsg_m + g_{ds} are 0, kVovk V_{ov} or k(Vov−VDS)k(V_{ov} - V_{DS}), and as functions of viv_i alone they are piecewise linear with slopes in {0,k,−k}\{0, k, -k\} when ii is not the gate. A continuous piecewise linear function with slopes of size at most kk is Lipschitz with constant kk. □\square

Theorem 1 (one solution per node). If no transistor at node ii has its gate on ii, then for all values of the other nodes, g′(x)≥Ci/hg'(x) \ge C_i/h, and gg has exactly one root. The denominator Ci−hDC_i - hD of line L7 is at least CiC_i.

Proof. g′(x)=Ci/h−∂Ii/∂vig'(x) = C_i/h - \partial I_i / \partial v_i, and ∂Ii/∂vi=D≤0\partial I_i / \partial v_i = D \le 0 by Lemma 1, summed over the transistors at ii. So gg is continuous and strictly increasing with slope at least Ci/hC_i/h. It tends to −∞-\infty and +∞+\infty at the two ends, so it has exactly one root. Ci−hD=hg′(x)≥CiC_i - hD = h g'(x) \ge C_i. □\square

Theorem 2 (triangular order). Suppose that, in the order of line L4, each IiI_i depends only on viv_i, on the inputs and on nodes earlier in the order, and that Theorem 1 applies to every node. Then the backward Euler system has exactly one solution vn+1v^{n+1}, and the sweep that solves each node equation exactly, with the newest values of the earlier nodes, returns it.

Proof. Induction along the order. Node 1 depends only on itself and the inputs at tn+1t^{n+1}, so its equation, alone, has one root, and every solution of the system must take this value. Suppose nodes 1,…,i−11, \ldots, i-1 have the unique values that every solution must take, and that the sweep has computed them. Then the equation of node ii involves only these values, the inputs and viv_i, so it has one root by Theorem 1, every solution takes it, and the sweep computes it. □\square

Theorem 3 (one Newton step). Let Theorem 1 apply to node ii, fix the other voltages, let x0=vinx_0 = v_i^n, let x∗x^* be the root of gg, and let x1=x0−g(x0)/g′(x0)x_1 = x_0 - g(x_0)/g'(x_0) be the result of line L7. Let I=IiI = I_i at x0x_0 and let LL be the sum of kk over the transistors at node ii. Then

∣x0−x∗∣≤h∣I∣Ci,∣x1−x∗∣≤Lh3I22Ci3.|x_0 - x^*| \le \frac{h |I|}{C_i}, \qquad |x_1 - x^*| \le \frac{L h^3 I^2}{2 C_i^3}.

Proof. g(x0)=−Ig(x_0) = -I, and g′≥m=Ci/hg' \ge m = C_i / h, so ∣g(x0)∣=∣g(x0)−g(x∗)∣≥m∣x0−x∗∣|g(x_0)| = |g(x_0) - g(x^*)| \ge m |x_0 - x^*|, which is the first bound. By Lemma 1, g′=Ci/h−∂Ii/∂vig' = C_i/h - \partial I_i/\partial v_i is Lipschitz with constant LL. Then

x1−x∗=g′(x0)(x0−x∗)−(g(x0)−g(x∗))g′(x0)=1g′(x0)∫x∗x0(g′(x0)−g′(ξ))dξ,x_1 - x^* = \frac{g'(x_0)(x_0 - x^*) - (g(x_0) - g(x^*))}{g'(x_0)} = \frac{1}{g'(x_0)} \int_{x^*}^{x_0} \left(g'(x_0) - g'(\xi)\right) d\xi,

and the integrand is at most L∣x0−ξ∣L|x_0 - \xi| in size, so the integral is at most L∣x0−x∗∣2/2L |x_0 - x^*|^2 / 2. Dividing by g′(x0)≥mg'(x_0) \ge m and using the first bound gives the second. □\square

For the example of the page, L=400 μA/V2L = 400\ \mu\mathrm{A/V^2}, Ci=10C_i = 10 fF, h=10−3h = 10^{-3} ns and ∣I∣≤169 μ|I| \le 169\ \muA give a bound of about 5.7 μ5.7\ \muV per node and step.

What is not proved here. Theorem 3 bounds the gap between one Newton step and the exact node solve in one step, with the other voltages fixed. Adding these gaps over the steps, and showing that the backward Euler map does not amplify them, would show that one Newton step per node keeps the first-order accuracy of backward Euler on a triangular circuit; that argument is not given here, and the tests measure it instead (a gap of 1.2 mV to full backward Euler at h=2h = 2 ps, and error ratios near 2 when hh halves). For circuits with two-way coupling, the single Gauss-Seidel sweep is not exact even with exact node solves, and its error depends on the circuit; Newton and Sangiovanni-Vincentelli (1984) analyze the convergence of the repeated sweep, which this page cites and does not prove.

Complexity

Each node update reads the transistors at the node, so a sweep costs O(N+T)O(N + T), and ss steps cost O(s(N+T))O(s(N + T)). No matrix is built or factored. A full circuit simulator pays for a sparse LU factorization at each Newton iteration, which grows faster than linearly in NN for most circuits, and for several iterations per time point. With event skipping, a sleeping node costs only the test of line L5, so the cost of a quiet step is O(N)O(N), and an implementation that keeps the awake nodes in a queue makes it proportional to the activity. On a chain of eight inverters with h=1h = 1 ps over 1 ns, ε=10−4\varepsilon = 10^{-4} V cut the node updates from 8000 to 3319, with a largest change of 3.9 mV from the unskipped run. These numbers are measured.

Properties

  • No matrix. Each step costs a sweep over the nodes. Memory is linear in the circuit size.
  • Implicit per node. The step size is not limited by the stiffness of a single node, since the update is backward Euler for that node.
  • First order. The accuracy is that of backward Euler, and the step size must be small against the transition times.
  • Order dependent. Feedback and two-way coupling are taken with a delay of one step for the nodes that come later in the order.
  • Event driven. Inactive parts of the circuit cost almost nothing, which is where most of the speed on large digital circuits comes from.

Variants and improvements

  • Iterated timing analysis. SPLICE repeats the Gauss-Seidel sweep at each time point until the voltages converge, which removes the error from two-way coupling; see iterated timing analysis.
  • Waveform relaxation. Solve each subcircuit for a whole time window, then exchange waveforms and repeat. It lets each subcircuit use its own step size.
  • Table models. MOTIS and its successors precompute transistor currents in tables to avoid evaluating the model.
  • Mixed mode. Simulate parts of the circuit at timing level and the rest at gate level, as in mixed-mode simulation.
  • Fast SPICE. Later commercial simulators combine partitioning, table models, event skipping and per-partition time steps on the same ideas.

When to use it

Use timing simulation for large digital MOS circuits where gate-level delays are not accurate enough and a full circuit simulator is too slow: memory arrays, custom datapaths, clock trees, checks of the waveforms and delays of whole blocks. Do not use it where strong two-way coupling decides the behavior, as in sense amplifiers, analog circuits and oscillators of coupled nodes, or where accuracy must be guaranteed; use a full transient circuit simulation there.

Pitfalls

  • Too large a skip threshold. A node is put to sleep when it moves slowly, and nothing may wake it again. In the tests, ε=0.01\varepsilon = 0.01 V on the inverter chain froze the first output at 0.46 V after the input ramp ended, and the edge never reached the end of the chain.
  • A bad order. If a gate comes before its input node, it sees the input one step late, and with feedback the delay adds up.
  • Two-way coupling. Floating capacitors and pass transistors couple nodes in both directions. One sweep does not resolve them, so the waveforms can be wrong by much more than the step error.
  • Too large a step. The update is defined for every step size, but backward Euler damps fast edges and shifts delays when hh is not small against the transition time.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

timing_simulation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/timing-simulation/. The authors are listed in prov/F3Y8TC.jsonl.
"""Timing simulation of MOS circuits in the style of MOTIS.

Every circuit node has a capacitance to ground. Transistors follow the
square-law (Shichman-Hodges, level 1) model with no body effect and no
channel-length modulation. The node equations C_i dv_i/dt = I_i(v) are
discretized by backward Euler. Instead of solving the whole nonlinear
system by Newton's method, each time step visits the nodes in a fixed order,
Gauss-Seidel style, and does one Newton step on each node's own equation,
with the newest voltages of the other nodes. Nodes whose neighbours did not
move by more than eps are skipped (event skipping).

Units: volts, nanoseconds, femtofarads and microamperes, which agree:
1 fF * 1 V / 1 ns = 1 uA.
"""

from __future__ import annotations

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


class Circuit:
    """Nodes with grounded capacitors, fixed nodes with voltage waveforms, and MOSFETs."""

    def __init__(self, vdd: float = 1.8, vt: float = 0.5) -> None:
        self.vdd = vdd
        self.vt = vt
        self.fixed: Dict[str, Callable[[float], float]] = {"vdd": lambda t: vdd, "gnd": lambda t: 0.0}
        self.order: List[str] = []
        self.cap: Dict[str, float] = {}
        self.trans: List[Tuple[str, str, str, str, float]] = []  # (kind, gate, a, b, k)

    def add_input(self, name: str, wave: Callable[[float], float]) -> None:
        self.fixed[name] = wave

    def add_node(self, name: str, cap: float) -> None:
        self.order.append(name)
        self.cap[name] = cap

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

    def at_node(self) -> Dict[str, List[int]]:
        """Transistors whose channel touches each node."""
        out: Dict[str, List[int]] = {n: [] for n in self.order}
        for i, (kind, g, a, b, k) in enumerate(self.trans):
            for n in {a, b}:
                if n in out:
                    out[n].append(i)
        return out

    def fanout(self) -> Dict[str, List[str]]:
        """For each node or input, the nodes whose current depends on its voltage."""
        out: Dict[str, set] = {n: set() for n in list(self.order) + list(self.fixed)}
        for kind, g, a, b, k in self.trans:
            for n in (a, b):
                if n in self.cap:
                    out[g].add(n)
                    out[a].add(n)
                    out[b].add(n)
        return {n: sorted(s, key=self.order.index) for n, s in out.items()}


def ramp(t0: float, t1: float, v0: float, v1: float) -> Callable[[float], float]:
    """A piecewise-linear waveform: v0 until t0, a straight line to v1 at t1, then v1."""
    def wave(t: float) -> float:
        if t <= t0:
            return v0
        if t >= t1:
            return v1
        return v0 + (v1 - v0) * (t - t0) / (t1 - t0)
    return wave


def mos(kind: str, k: float, vt: float, vg: float, va: float, vb: float) -> Tuple[float, float, float, float]:
    """Channel current from terminal a to terminal b, and its derivatives in va, vb and vg."""
    if kind == "n":
        if va >= vb:
            sign, vd, vs = 1.0, va, vb
        else:
            sign, vd, vs = -1.0, vb, va
        vov, vds = vg - vs - vt, vd - vs
    else:
        if va >= vb:
            sign, vs, vd = 1.0, va, vb
        else:
            sign, vs, vd = -1.0, vb, va
        vov, vds = vs - vg - vt, vs - vd
    if vov <= 0.0:
        return 0.0, 0.0, 0.0, 0.0
    if vds < vov:
        cur = k * (vov * vds - 0.5 * vds * vds)
        gm, gds = k * vds, k * (vov - vds)
    else:
        cur = 0.5 * k * vov * vov
        gm, gds = k * vov, 0.0
    # Derivatives of cur in the gate, the higher and the lower channel terminal.
    if kind == "n":
        d_g, d_hi, d_lo = gm, gds, -gm - gds
    else:
        d_g, d_hi, d_lo = -gm, gm + gds, -gds
    if sign > 0:
        return cur, d_hi, d_lo, d_g
    return -cur, -d_lo, -d_hi, -d_g


def node_current(c: Circuit, at: Sequence[int], node: str, v: Dict[str, float]) -> Tuple[float, float]:
    """Current into the node through the channels at it, and its derivative in the node voltage."""
    total = deriv = 0.0
    for i in at:
        kind, g, a, b, k = c.trans[i]
        i_ab, d_a, d_b, d_g = mos(kind, k, c.vt, v[g], v[a], v[b])
        sign = -1.0 if node == a else 1.0  # current a -> b leaves a and enters b
        total += sign * i_ab
        deriv += sign * ((d_a if node == a else 0.0) + (d_b if node == b else 0.0) + (d_g if node == g else 0.0))
    return total, deriv


def motis(c: Circuit, init: Dict[str, float], t_end: float, h: float, eps: float = 0.0,
          exact: bool = False) -> Tuple[List[float], Dict[str, List[float]], int]:
    """Timing simulation. Returns (time points, waveform of every node, node updates).

    With exact=True each node equation is solved to convergence instead of one Newton step.
    """
    at = c.at_node()
    fan = c.fanout()
    v = {n: f(0.0) for n, f in c.fixed.items()}  # @line L1
    v.update({n: init[n] for n in c.order})
    active = set(c.order)
    times, waves, evals = [0.0], {n: [v[n]] for n in c.order}, 0
    steps = int(round(t_end / h))
    for s in range(1, steps + 1):  # @line L2
        t = s * h
        for n, f in c.fixed.items():  # @line L3
            new = f(t)
            if abs(new - v[n]) > eps or eps <= 0.0:
                active.update(fan[n])
            v[n] = new
        woken = set()
        for n in c.order:  # @line L4
            if n not in active and eps > 0.0:  # @line L5
                continue
            evals += 1
            old = v[n]
            cur, d = node_current(c, at[n], n, v)  # @line L6
            v[n] = old + h * cur / (c.cap[n] - h * d)  # @line L7
            if exact:
                v[n] = _solve_node(c, at[n], n, v, old, h)
            if abs(v[n] - old) > eps:  # @line L8
                woken.add(n)
                woken.update(fan[n])
                active.update(fan[n])
        active = woken  # @line L9
        times.append(t)  # @line L10
        for n in c.order:
            waves[n].append(v[n])
    return times, waves, evals  # @line L11


def _solve_node(c: Circuit, at: Sequence[int], n: str, v: Dict[str, float], old: float, h: float) -> float:
    """Solve C (x - old) / h = I(x) for the voltage x of node n, others fixed.

    The left side minus the right side increases in x when the gates at the node are
    other nodes, so the root is unique. Newton steps, kept inside a bracket.
    """
    def g(x: float) -> Tuple[float, float]:
        v[n] = x
        cur, d = node_current(c, at, n, v)
        return c.cap[n] * (x - old) / h - cur, c.cap[n] / h - d

    lo, hi = -10.0 * c.vdd - 10.0, 10.0 * c.vdd + 10.0
    x = v[n]
    for _ in range(200):
        gx, dx = g(x)
        if gx > 0:
            hi = min(hi, x)
        else:
            lo = max(lo, x)
        step = gx / dx
        nxt = x - step
        if not lo < nxt < hi:
            nxt = 0.5 * (lo + hi)
        if abs(nxt - x) < 1e-13:
            x = nxt
            break
        x = nxt
    v[n] = x
    return x


def crossing(times: Sequence[float], wave: Sequence[float], level: float) -> Optional[float]:
    """First time at which the waveform crosses the level, by linear interpolation."""
    for i in range(1, len(wave)):
        a, b = wave[i - 1] - level, wave[i] - level
        if a == 0.0:
            return times[i - 1]
        if a * b < 0.0:
            return times[i - 1] + (times[i] - times[i - 1]) * a / (a - b)
    return None
test_timing_simulation.py 244 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/timing-simulation/. The authors are listed in prov/F3Y8TC.jsonl.
"""Tests for MOTIS-style timing simulation against a fine-step RK4 reference and a full
backward Euler Newton solve."""

import random

from timing_simulation import Circuit, crossing, mos, motis, node_current, ramp

VDD = 1.8
T_END = 1.0       # ns
H = 0.001         # ns, 1 ps
H_REF = 0.00005   # ns, 0.05 ps for the RK4 reference


def chain(stages=4, cap=10.0, k=200.0):
    c = Circuit(vdd=VDD)
    c.add_input("in", ramp(0.1, 0.15, 0.0, VDD))
    prev = "in"
    init = {}
    for s in range(stages):
        y = f"y{s + 1}"
        c.add_node(y, cap)
        c.add_transistor("p", prev, "vdd", y, k)
        c.add_transistor("n", prev, y, "gnd", k)
        init[y] = VDD if s % 2 == 0 else 0.0
        prev = y
    return c, init


def nand_stack():
    """A NAND gate with the internal node m of its n stack, driving an inverter."""
    c = Circuit(vdd=VDD)
    c.add_input("a", ramp(0.1, 0.15, 0.0, VDD))
    c.add_input("b", lambda t: VDD)
    c.add_node("out", 10.0)
    c.add_node("m", 3.0)
    c.add_node("z", 10.0)
    c.add_transistor("p", "a", "vdd", "out", 200.0)
    c.add_transistor("p", "b", "vdd", "out", 200.0)
    c.add_transistor("n", "a", "out", "m", 200.0)
    c.add_transistor("n", "b", "m", "gnd", 200.0)
    c.add_transistor("p", "out", "vdd", "z", 200.0)
    c.add_transistor("n", "out", "z", "gnd", 200.0)
    return c, {"out": VDD, "m": 0.0, "z": 0.0}


# ---------------------------------------------------------------- references

def rk4(c, init, t_end, h):
    """Classical Runge-Kutta on C dv/dt = I(v) with a fine step: the reference."""
    at = c.at_node()
    v = dict(init)

    def f(t, vals):
        full = {n: w(t) for n, w in c.fixed.items()}
        full.update(vals)
        return {n: node_current(c, at[n], n, full)[0] / c.cap[n] for n in c.order}

    times, waves = [0.0], {n: [v[n]] for n in c.order}
    for s in range(int(round(t_end / h))):
        t = s * h
        k1 = f(t, v)
        k2 = f(t + h / 2, {n: v[n] + h / 2 * k1[n] for n in v})
        k3 = f(t + h / 2, {n: v[n] + h / 2 * k2[n] for n in v})
        k4 = f(t + h, {n: v[n] + h * k3[n] for n in v})
        v = {n: v[n] + h / 6 * (k1[n] + 2 * k2[n] + 2 * k3[n] + k4[n]) for n in v}
        times.append(t + h)
        for n in c.order:
            waves[n].append(v[n])
    return times, waves


def solve_linear(a, b):
    """Gaussian elimination with partial pivoting."""
    n = len(b)
    m = [row[:] + [b[i]] for i, row in enumerate(a)]
    for col in range(n):
        p = max(range(col, n), key=lambda r: abs(m[r][col]))
        m[col], m[p] = m[p], m[col]
        for r in range(col + 1, n):
            f = m[r][col] / m[col][col]
            for j in range(col, n + 1):
                m[r][j] -= f * m[col][j]
    x = [0.0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (m[r][n] - sum(m[r][j] * x[j] for j in range(r + 1, n))) / m[r][r]
    return x


def backward_euler_newton(c, init, t_end, h):
    """Backward Euler with the full nonlinear system solved by Newton's method to 1e-13."""
    at = c.at_node()
    names = c.order
    v = {n: w(0.0) for n, w in c.fixed.items()}
    v.update(init)
    times, waves = [0.0], {n: [v[n]] for n in names}
    for s in range(1, int(round(t_end / h)) + 1):
        t = s * h
        for n, w in c.fixed.items():
            v[n] = w(t)
        old = {n: v[n] for n in names}
        for _ in range(100):
            res, jac = [], []
            for n in names:
                cur, _ = node_current(c, at[n], n, v)
                res.append(c.cap[n] * (v[n] - old[n]) / h - cur)
                row = []
                for m in names:   # derivative of the residual of n in v[m], by central differences
                    e = 1e-7
                    keep = v[m]
                    v[m] = keep + e
                    cp, _ = node_current(c, at[n], n, v)
                    v[m] = keep - e
                    cm, _ = node_current(c, at[n], n, v)
                    v[m] = keep
                    row.append((c.cap[n] / h if m == n else 0.0) - (cp - cm) / (2 * e))
                jac.append(row)
            dx = solve_linear(jac, [-r for r in res])
            for n, d in zip(names, dx):
                v[n] += d
            if max(abs(d) for d in dx) < 1e-13:
                break
        times.append(t)
        for n in names:
            waves[n].append(v[n])
    return times, waves


def max_error(a, b, stride=1):
    """Largest difference between waveforms a (coarse) and b (fine, stride points per coarse step)."""
    return max(abs(x - b[i * stride]) for i, x in enumerate(a))


# ---------------------------------------------------------------- the device model

def test_mos_regions_and_symmetry():
    k, vt = 200.0, 0.5
    assert mos("n", k, vt, 0.4, 1.0, 0.0)[0] == 0.0                     # cutoff
    assert abs(mos("n", k, vt, 1.8, 1.8, 0.0)[0] - 0.5 * k * 1.3 ** 2) < 1e-9   # saturation
    assert abs(mos("n", k, vt, 1.8, 0.2, 0.0)[0] - k * (1.3 * 0.2 - 0.02)) < 1e-9  # linear
    assert abs(mos("p", k, vt, 0.0, 1.8, 0.0)[0] - 0.5 * k * 1.3 ** 2) < 1e-9
    rng = random.Random(7)
    for _ in range(500):
        kind = rng.choice("np")
        vg, va, vb = (rng.uniform(-0.2, 2.0) for _ in range(3))
        assert abs(mos(kind, k, vt, vg, va, vb)[0] + mos(kind, k, vt, vg, vb, va)[0]) < 1e-12


def test_mos_derivatives():
    rng = random.Random(8)
    e = 1e-6
    for _ in range(500):
        kind = rng.choice("np")
        vg, va, vb = (rng.uniform(-0.2, 2.0) for _ in range(3))
        cur, da, db, dg = mos(kind, 200.0, 0.5, vg, va, vb)
        for idx, d in ((1, da), (2, db), (0, dg)):
            p = [vg, va, vb]
            q = [vg, va, vb]
            p[idx] += e
            q[idx] -= e
            num = (mos(kind, 200.0, 0.5, *p)[0] - mos(kind, 200.0, 0.5, *q)[0]) / (2 * e)
            assert abs(num - d) < 1e-3 * (1 + abs(d))


# ---------------------------------------------------------------- the solver

def test_exact_node_solves_equal_full_newton_on_feed_forward_chain():
    c, init = chain(4)
    h = 0.002
    _, w_exact, _ = motis(c, init, T_END, h, exact=True)
    _, w_full = backward_euler_newton(c, init, T_END, h)
    for n in c.order:
        assert max_error(w_exact[n], w_full[n]) < 1e-9


def test_one_newton_step_stays_near_full_backward_euler():
    c, init = chain(4)
    h = 0.002
    _, w_one, _ = motis(c, init, T_END, h)
    _, w_full = backward_euler_newton(c, init, T_END, h)
    assert max(max_error(w_one[n], w_full[n]) for n in c.order) < 0.005


def test_chain_against_fine_rk4_reference():
    c, init = chain(4)
    _, w_ref = rk4(c, init, T_END, H_REF)
    stride = int(round(H / H_REF))
    times, w, _ = motis(c, init, T_END, H)
    ref_times = [i * H_REF for i in range(len(w_ref["y1"]))]
    for n in c.order:
        assert max_error(w[n], w_ref[n], stride) < 0.02                # volts, stated tolerance
        t_sim = crossing(times, w[n], VDD / 2)
        t_ref = crossing(ref_times, w_ref[n], VDD / 2)
        assert abs(t_sim - t_ref) < 0.0015                               # 1.5 ps, stated tolerance
    assert w["y4"][-1] > VDD - 1e-3                                      # the edge went through


def test_first_order_error_ratio():
    c, init = chain(2)
    _, w_ref = rk4(c, init, 0.6, H_REF)
    errors = []
    for h in (0.004, 0.002, 0.001):
        _, w, _ = motis(c, init, 0.6, h)
        stride = int(round(h / H_REF))
        errors.append(max(max_error(w[n], w_ref[n], stride) for n in c.order))
    for e1, e2 in zip(errors, errors[1:]):
        assert 1.6 < e1 / e2 < 2.5


def test_event_skipping_saves_work():
    c, init = chain(8)
    _, w_full, n_full = motis(c, init, T_END, H)
    _, w_skip, n_skip = motis(c, init, T_END, H, eps=1e-4)
    assert n_skip < 0.5 * n_full
    assert max(max_error(w_skip[n], w_full[n]) for n in c.order) < 0.01


def test_bidirectional_stack_against_reference():
    c, init = nand_stack()
    _, w_ref = rk4(c, init, T_END, H_REF)
    stride = int(round(H / H_REF))
    _, w, _ = motis(c, init, T_END, H)
    for n in c.order:
        assert max_error(w[n], w_ref[n], stride) < 0.02
    assert w["out"][-1] < 1e-3 and w["z"][-1] > VDD - 1e-3


def test_too_large_skip_threshold_loses_the_edge():
    # Once the input ramp ends, nothing wakes y1 again. When its change per step falls
    # below 0.01 V, it is put to sleep for good and freezes between the rails.
    c, init = chain(8)
    _, w, _ = motis(c, init, T_END, H, eps=1e-2)
    assert 0.3 < w["y1"][-1] < 0.6
    _, good, _ = motis(c, init, T_END, H)
    assert good["y1"][-1] < 1e-3


def test_quiet_circuit_is_skipped():
    c, init = chain(4)
    c.fixed["in"] = lambda t: 0.0
    _, w, evals = motis(c, init, T_END, H, eps=1e-6)
    assert evals <= 4 * 2                                                # settles at once
    assert all(w[n][-1] == init[n] for n in c.order)

History

Chawla, Gummel and Kozak at Bell Laboratories built MOTIS and described it in 1975, at the Design Automation Conference and in the IEEE Transactions on Circuits and Systems. It brought transistor-level timing to circuits far larger than a circuit simulator of the time could handle. Newton's SPLICE (1979) combined timing and logic simulation with events, and Newton and Sangiovanni-Vincentelli (1984) explained timing simulation as one sweep of a nonlinear relaxation method, which led to iterated timing analysis and waveform relaxation. The fast SPICE simulators of the 1990s and later build on these methods.

References

  1. B. R. Chawla, H. K. Gummel and P. Kozak, MOTIS, an MOS timing simulator, IEEE Transactions on Circuits and Systems CAS-22(12), 901 to 910, 1975, the node-by-node backward difference update with one Newton step per node, the table models of MOS transistors and the skipping of inactive nodes
  2. P. Kozak, H. K. Gummel and B. R. Chawla, Operational features of an MOS timing simulator, Proceedings of the 12th Design Automation Conference, 95 to 101, 1975, the use of MOTIS on large MOS circuits
  3. A. R. Newton and A. L. Sangiovanni-Vincentelli, Relaxation-based electrical simulation, IEEE Transactions on Computer-Aided Design 3(4), 308 to 331, 1984, the analysis of timing simulation as one sweep of nonlinear Gauss-Seidel relaxation, and its relation to iterated timing analysis and waveform relaxation

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 correctness
  • 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