Algorithm Search⌘K

Algorithmcore

Event-driven logic simulation

Also called selective trace simulation, Ulrich event-driven simulation.

Evaluates only the gates whose inputs changed, taking events in time order from a time wheel and scheduling new events for outputs that change after their delays.

Time
O(E F k + S M) worstO(E F k + S) best
Space
O(N + P) extra
Where
E = the number of applied value changes; F = the largest fanout; M = the number of slots of the time wheel; N = the number of nets; P = the number of gate input pins; S = the number of distinct event times; k = the largest fan-in
Properties
deterministicexactiterative
Origin
Ernst G. Ulrich, 1969

Event-driven logic simulation computes the waveforms of a gate-level circuit by evaluating a gate only when one of its inputs changes. A change of value on a net at a time is an event. The simulator keeps the future events in a time wheel, takes the events of the earliest time, applies them, evaluates the gates that read the changed nets, and schedules a new event for each gate output whose value will change after the delay of the gate. This page is in the logic simulation half of logic and circuit simulation: it works on gates, events and the values 0 and 1, not on nodal equations. The delay model is a fixed integer delay for each gate, with zero delay and unit delay as special cases. Transport delay is the default, and inertial delay is a small change, described under Variants. In typical circuits only a few percent of the gates change at each event time, so this method, also called selective trace, does much less work than evaluating every gate at every time.

In plain words

Most of a large chip is quiet at any moment. Only a few wires change.

So the simulator does not look at every gate at every time step. It keeps a calendar of future changes. It jumps to the next time that has a change, applies the changes, and looks only at the gates that read a changed wire. If such a gate now wants a new output, the simulator writes that new output into the calendar at the current time plus the delay of the gate.

When a gate has no delay, the new change goes into the same moment of the calendar. The simulator then makes another pass at the same time, and it repeats this until nothing more changes at that moment.

The problem

The input is a gate-level circuit CC with NN nets, PP gate input pins and gates gg that each have a Boolean function fgf_g, an output net out(g)\mathrm{out}(g) and an integer delay d(g)≥0d(g) \ge 0. Each net has an initial value in {0,1}\{0, 1\}, and a list gives the changes of the primary inputs as triples (time, net, value). The gates may form loops, as in latches. The output is the value of every net at every time from 00 to TendT_{\text{end}}, given as the list of changes.

The meaning of the delays is the transport model. Let zg(t)=fg(the values of the inputs of g at time t)z_g(t) = f_g(\text{the values of the inputs of } g \text{ at time } t) be the value that the gate function asks for. Then the output follows it after the delay: out(g)(t)=zg(t−d(g))\mathrm{out}(g)(t) = z_g(t - d(g)) for t≥d(g)t \ge d(g), and the initial value before. With zero delays this is a set of equations at each time, and the delta cycles below solve it.

The algorithm

  1. EVENT-SIM(C, d, v0, input events, T_end)
  2. 1val ← v0; proj ← v0 (proj is the last value scheduled on a net)
  3. 2W ← a time wheel that holds the input events; do one pass of L7 to L10 at time 0 with G = all gates
  4. 3while W has events at a time t ≤ T_end, with t the earliest such time, do
  5. 4U ← the events of time t, taken out of W; a later event on a net replaces an earlier one
  6. 5A ← the nets n in U with U[n] ≠ val[n]; set val[n] ← U[n] for each n in A
  7. 6G ← the gates with an input in A (selective trace)
  8. 7for each gate g in G do
  9. 8v ← f_g(val of the inputs of g)
  10. 9if v ≠ proj[out(g)] then
  11. 10proj[out(g)] ← v; schedule (t + d(g), out(g), v) in W
  12. 11return val and the list of changes made at L5

The time wheel is Ulrich's time mapping. It is an array of MM slots, where MM is one more than the largest gate delay, and slot t mod Mt \bmod M holds the events of time tt. The input events that lie more than MM steps ahead wait in an overflow list and move into the wheel when the current time comes near. A gate event always fits, since its time is at most t+M−1t + M - 1. The timing wheel page treats the data structure itself, and a calendar queue or a priority queue can take its place when the delays vary widely.

The test at L9 compares with the projected value, not with the present value. With transport delay an output can have several events pending, and the projected value is the value that the output will have after all of them. If the new value equals it, the event would change nothing.

When d(g)=0d(g) = 0, line L10 puts the event into the slot of the present time tt. The loop at L3 then finds time tt again and makes one more pass, a delta pass, at the same time. A circuit with a loop of zero-delay gates can make delta passes for ever, so the implementation stops after a fixed number of passes and reports an oscillation.

Example

Take y=ab+a′cy = ab + a'c with gates aˉ=NOT(a)\bar a = \mathrm{NOT}(a), p=AND(a,b)p = \mathrm{AND}(a, b), q=AND(aˉ,c)q = \mathrm{AND}(\bar a, c) and y=OR(p,q)y = \mathrm{OR}(p, q). Let b=c=1b = c = 1, so y=1y = 1 for both values of aa. Every gate has delay 1. At the start a=1a = 1, so aˉ=0\bar a = 0, p=1p = 1, q=0q = 0 and y=1y = 1, and aa falls to 0 at time 10.

time changes applied (L5) gates evaluated (L7) events scheduled (L10)
0 none all four, each gives its present value none
10 a=0a = 0 aˉ\bar a, pp aˉ=1\bar a = 1 and p=0p = 0 at 11
11 aˉ=1\bar a = 1, p=0p = 0 qq, yy q=1q = 1 at 12; y=OR(0,0)=0y = \mathrm{OR}(0, 0) = 0 at 12
12 q=1q = 1, y=0y = 0 yy y=OR(0,1)=1y = \mathrm{OR}(0, 1) = 1 at 13
13 y=1y = 1 none none

The output has a glitch: yy is 0 for one time unit from 12 to 13, because the path through aˉ\bar a is one gate longer than the path through pp. This is a static 1-hazard. The run made 9 gate evaluations, 4 of them at time 0. A step-by-step simulator would evaluate 4 gates at each of the 14 time steps from 0 to 13.

With zero delays, the same change at time 10 takes four delta passes at time 10: the changes are aa, then aˉ\bar a and pp, then qq and y=0y = 0, then y=1y = 1. So even with zero delay, yy shows a pulse of zero width at time 10, which a VHDL or Verilog process that waits on yy would see. If the OR gate has an inertial delay of 2, the evaluation at time 12 cancels the pending change to 0 at time 13, and the glitch is gone. With a transport delay of 2 it stays, from 13 to 14.

Correctness

The proof in proofs/correctness.md shows two facts.

First, with all delays at least 1 and transport delay, the values after time tt equal those of a unit-time step simulation with out(g)(t)=zg(t−d(g))\mathrm{out}(g)(t) = z_g(t - d(g)) for every integer tt, on any circuit, with or without loops. The key invariant is that, after time tt, the events pending on an output describe exactly the values zg(s)z_g(s) for t−d(g)<s≤tt - d(g) < s \le t, and the projected value is zg(t)z_g(t). A gate that L6 does not select has the same inputs as at the previous time, so its zgz_g did not change and skipping it is safe. The same proof with the cancel rule gives the inertial version.

Second, with all delays 0 on an acyclic circuit, the delta passes at each time stop after at most D+1D + 1 passes, where DD is the depth of the circuit, and the values then equal the direct evaluation of the circuit on the present inputs. When the passes stop, every gate satisfies val[out(g)]=fg(val[inputs])\mathrm{val}[\mathrm{out}(g)] = f_g(\mathrm{val}[\text{inputs}]), so the values are a fixed point of the circuit equations, and an acyclic circuit has exactly one. With unit delays the values reach the same fixed point at most DD time units after the last input change. So event-driven simulation with zero or unit delays and levelized evaluation give the same settled values on acyclic circuits. They do not give the same waveforms: the glitch above appears only in the event-driven run.

The tests check the first fact against a unit-time step simulation on random circuits with loops and delays from 1 to 3, both for transport and inertial delay, and the second fact against direct evaluation of every input vector of random acyclic circuits.

Proof: Event-driven simulation computes the transport-delay waveforms, and with zero or unit delays it settles to the levelized valuesfull

Let CC be a gate-level circuit. Each gate gg has a function fgf_g, an output net out(g)\mathrm{out}(g) and an integer delay d(g)≥0d(g) \ge 0. Every net has an initial value v0v_0 in {0,1}\{0, 1\}, and the inputs change only by the given input events. For a time tt let ref(t)\mathrm{ref}(t) be the values of all nets at time tt in the model, and let zg(t)=fg(ref(t) on the inputs of g)z_g(t) = f_g(\mathrm{ref}(t) \text{ on the inputs of } g). Lines L1 to L11 refer to the pseudocode of the page.

Transport model. For integer delays d(g)≥1d(g) \ge 1, ref\mathrm{ref} is defined by induction on t=0,1,2,…t = 0, 1, 2, \ldots: an input net has the value of its last input event at a time ≤t\le t (or v0v_0), and out(g)(t)=zg(t−d(g))\mathrm{out}(g)(t) = z_g(t - d(g)) if t≥d(g)t \ge d(g) and v0(out(g))v_0(\mathrm{out}(g)) otherwise. This is well defined, because zg(t−d(g))z_g(t - d(g)) depends only on values at earlier times. To make the statements uniform, put zg(s)=v0(out(g))z_g(s) = v_0(\mathrm{out}(g)) for s<0s < 0.

For a gate output nn and a time uu after the present time, let pendn(u)\mathrm{pend}_n(u) be the value of the last pending event on nn at a time ≤u\le u, or val[n]\mathrm{val}[n] if there is none. Events on one net and one time are ordered by the order in which L10 scheduled them, and L4 keeps the last one.

Theorem 1 (transport delay, delays at least 1). Let every d(g)≥1d(g) \ge 1. For every integer t≥0t \ge 0, after the algorithm has handled time tt (or has skipped it because WW had no event at tt), val=ref(t)\mathrm{val} = \mathrm{ref}(t). This holds on any circuit, with or without loops.

Proof. We prove by induction on t≥−1t \ge -1 the invariant I(t)I(t): after time tt is handled,

  1. val=ref(t)\mathrm{val} = \mathrm{ref}(t) (for t=−1t = -1, read this as val=v0\mathrm{val} = v_0);
  2. for every gate gg with n=out(g)n = \mathrm{out}(g) and d=d(g)d = d(g): proj[n]=zg(t)\mathrm{proj}[n] = z_g(t), and pendn(u)=zg(u−d)\mathrm{pend}_n(u) = z_g(u - d) for all uu with t<u≤t+dt < u \le t + d;
  3. no pending event has a time ≤t\le t.

Base, t=−1t = -1. L1 sets val=proj=v0\mathrm{val} = \mathrm{proj} = v_0, and only input events are pending. For u≤d−1u \le d - 1 we have zg(u−d)=v0(n)=val[n]=pendn(u)z_g(u - d) = v_0(n) = \mathrm{val}[n] = \mathrm{pend}_n(u), and proj[n]=v0(n)=zg(−1)\mathrm{proj}[n] = v_0(n) = z_g(-1).

Step from t−1t - 1 to tt. By part 3 of I(t−1)I(t-1), the events taken at L4 are exactly the pending events of time tt. For an input net, they are the input events of time tt, and the last one wins, as in ref\mathrm{ref}. For a gate output nn, the last event at time tt, or no event, gives the new value pendn(t)=zg(t−d)=ref(t)(n)\mathrm{pend}_n(t) = z_g(t - d) = \mathrm{ref}(t)(n) by part 2. So after L5, val=ref(t)\mathrm{val} = \mathrm{ref}(t), which is part 1. Since all delays are at least 1, the events scheduled at time tt have times >t> t, so there is one pass at time tt and part 3 holds.

Now take a gate gg with n=out(g)n = \mathrm{out}(g). If no input of gg is in the set AA of L5, then the inputs of gg have the same values at t−1t - 1 and tt (at t=0t = 0 every gate is evaluated, so this case does not occur there). So zg(t)=zg(t−1)=proj[n]z_g(t) = z_g(t - 1) = \mathrm{proj}[n], and nothing is scheduled. The window t<u≤t+dt < u \le t + d gains the point u=t+du = t + d, and pendn(t+d)=pendn(t+d−1)=zg(t−1)=zg(t)\mathrm{pend}_n(t + d) = \mathrm{pend}_n(t + d - 1) = z_g(t - 1) = z_g(t), because no event on nn lies at time t+dt + d: an event at t+dt + d would have been scheduled at time tt. If gg is evaluated, L8 computes v=zg(t)v = z_g(t), because val=ref(t)\mathrm{val} = \mathrm{ref}(t). Two cases.

  • v=proj[n]=zg(t−1)v = \mathrm{proj}[n] = z_g(t - 1). Nothing is scheduled, and the same argument as above gives part 2.
  • v≠proj[n]v \ne \mathrm{proj}[n]. L10 sets proj[n]=v=zg(t)\mathrm{proj}[n] = v = z_g(t) and schedules vv at t+dt + d. All other pending events on nn lie at times ≤t−1+d\le t - 1 + d, so this event is the last one at or before t+dt + d, and pendn(t+d)=v=zg(t)\mathrm{pend}_n(t + d) = v = z_g(t). For t<u<t+dt < u < t + d, nothing changed, and pendn(u)=zg(u−d)\mathrm{pend}_n(u) = z_g(u - d) by I(t−1)I(t - 1).

If the algorithm skips time tt because no event is pending at tt, then no net changes at tt, so ref(t)=ref(t−1)\mathrm{ref}(t) = \mathrm{ref}(t - 1) (by part 2, every gate output keeps pendn(t)=val[n]\mathrm{pend}_n(t) = \mathrm{val}[n]), every zg(t)=zg(t−1)z_g(t) = z_g(t - 1), and the argument of the unselected case gives I(t)I(t). □\square

Inertial model. Here out(g)(t)=zg(t−d)\mathrm{out}(g)(t) = z_g(t - d) if zgz_g has the same value at all integer times t−d,…,t−1t - d, \ldots, t - 1, and out(g)(t)=out(g)(t−1)\mathrm{out}(g)(t) = \mathrm{out}(g)(t - 1) otherwise (with the initial value for t<dt < d). In the algorithm, L10 cancels all pending events of nn and schedules vv at t+dt + d only if v≠val[n]v \ne \mathrm{val}[n].

Theorem 2 (inertial delay, delays at least 1). With the inertial rule, val=ref(t)\mathrm{val} = \mathrm{ref}(t) after time tt, for every t≥0t \ge 0 and every circuit.

Proof. Replace part 2 of the invariant by: proj[n]=zg(t)\mathrm{proj}[n] = z_g(t), and nn has at most one live pending event. It exists exactly when zg(t)≠val[n]z_g(t) \ne \mathrm{val}[n], and then it has the value zg(t)z_g(t) and the time s+ds + d, where s≤ts \le t is the last time at which zgz_g changed (that is, zg(s)≠zg(s−1)z_g(s) \ne z_g(s - 1)). The step is as before. A gate whose zgz_g does not change at tt gives v=proj[n]v = \mathrm{proj}[n], so nothing happens. A gate whose zgz_g changes at tt gives v≠proj[n]v \ne \mathrm{proj}[n], so the old event is cancelled, and a new one at t+dt + d is made exactly when v≠val[n]v \ne \mathrm{val}[n]. So val[n]\mathrm{val}[n] changes at time TT exactly when zgz_g changed at T−dT - d to a value v≠val[n]v \ne \mathrm{val}[n] and did not change at T−d+1,…,T−1T - d + 1, \ldots, T - 1. This is the rule of the model: if zgz_g is constant on T−d,…,T−1T - d, \ldots, T - 1 and changed at T−dT - d, then out(T)=zg(T−d)\mathrm{out}(T) = z_g(T - d), and if it is constant there but did not change at T−dT - d, then it was constant on T−d−1,…,T−2T - d - 1, \ldots, T - 2, so out(T−1)\mathrm{out}(T - 1) already has that value. □\square

Theorem 3 (zero delay, acyclic circuit). Let every d(g)=0d(g) = 0 and let CC have no loops, with depth DD (the largest number of gates on a path). At each time tt that has events, the delta passes stop after at most D+1D + 1 passes, and then val\mathrm{val} equals the direct evaluation of CC on the inputs of time tt.

Proof. Let the level of a primary input be 0 and the level of a gate output be one more than the largest level of its inputs. The changes in pass 1 are input events, on nets of level 0, and at time 0 the first pass evaluates all gates, which have level ≥1\ge 1. A gate evaluated in pass kk has an input that changed in pass kk; if all changes in pass kk are on nets of level ≥k−1\ge k - 1, then each evaluated gate has level ≥k\ge k, and its event, applied in pass k+1k + 1, is on a net of level ≥k\ge k. By induction, the changes in pass kk are on nets of level ≥k−1\ge k - 1. No net has a level above DD, so pass D+2D + 2 has no events, and there are at most D+1D + 1 passes.

When the passes stop, no event is pending at time tt, and with zero delays no event is pending at any later time either. For each gate output nn, proj[n]\mathrm{proj}[n] is the value of the last event scheduled on nn, and that event has been applied, so val[n]=proj[n]\mathrm{val}[n] = \mathrm{proj}[n]. After each pass, proj[out(g)]=fg(val on the inputs of g)\mathrm{proj}[\mathrm{out}(g)] = f_g(\mathrm{val} \text{ on the inputs of } g) for every gate: it held after gg was last evaluated, and the inputs of gg have not changed since, because every change of an input puts gg into the set of L6. So val[out(g)]=fg(val[inputs])\mathrm{val}[\mathrm{out}(g)] = f_g(\mathrm{val}[\text{inputs}]) for every gate. The values are a solution of the circuit equations with the given inputs. In an acyclic circuit, induction on the level shows that this solution is unique, and the direct evaluation is a solution. □\square

Corollary (unit delay, acyclic circuit). With every d(g)=1d(g) = 1, if the last input event is at time t0t_0, then val\mathrm{val} does not change after t0+Dt_0 + D, and it then equals the direct evaluation of CC on the final inputs.

Proof. By Theorem 1, ref\mathrm{ref} is the unit-delay model. A net of level ℓ\ell has a value at time t≥t0+ℓt \ge t_0 + \ell that depends only on the inputs at times ≥t0\ge t_0, which are the final inputs: by induction on ℓ\ell, out(g)(t)=fg(ref(t−1))\mathrm{out}(g)(t) = f_g(\mathrm{ref}(t - 1)), and the inputs of gg have level <ℓ< \ell, so their values at t−1≥t0+ℓ−1t - 1 \ge t_0 + \ell - 1 are already the direct values. □\square

So with zero or unit delays, the settled values of event-driven simulation equal the values of levelized evaluation on an acyclic circuit. The waveforms before settling can differ: they can contain glitches and zero-width delta pulses that levelized evaluation never shows.

Complexity

Each change applied at L5 makes L6 select at most FF gates, and each evaluation at L8 reads at most kk inputs. Each scheduled event costs O(1)O(1) in the wheel. Moving to the next event time costs at most MM slot checks. So the time is O(EFk+SM)O(E F k + S M), where EE is the number of applied changes and SS is the number of distinct event times. The space is O(N+P)O(N + P) for the netlist, the values and the projected values, plus the pending events, of which there are at most NMN M.

The cost follows the activity EE, not the circuit size times the time. This is the point of the method. The activity can be large, though. A stage zs=XOR(zs−1,BUF(zs−1))z_s = \mathrm{XOR}(z_{s-1}, \mathrm{BUF}(z_{s-1})) in which the buffer has delay 2s−12^{s-1} turns each change of its input into two changes of its output. One input change then makes 2k2^k changes at the end of a chain of kk stages, which has 2k2k gates. A script with the implementation of this page counted 2, 4, 8, ..., 128 output changes for k=1,…,7k = 1, \ldots, 7. With unit delays and no loops this cannot happen: a net changes at most DD times after one input change.

Properties

  • Exact for its delay model. The waveforms are exactly those of the transport (or inertial) model with the given integer delays. They are not the waveforms of the real circuit, whose delays depend on load, slope and process.
  • Order of evaluation. Within one pass the gates of GG see the values of the same pass, so the result does not depend on the order of L7. Across delta passes the order is fixed by the algorithm.
  • Activity. In typical designs only a few percent of the gates switch at each time, which is why selective trace beats evaluating every gate. In a design with high activity, such as a datapath under random data, the saving is small, and compiled code wins.
  • Glitches. The method shows hazards and glitches that a zero-delay levelized simulation hides. Power estimation tools use this to count glitch power.

Variants and improvements

  • Inertial delay. Line L10 first cancels the pending events of out(g)\mathrm{out}(g) and then schedules vv only if v≠val[out(g)]v \ne \mathrm{val}[\mathrm{out}(g)]. A pulse at the gate function that is shorter than d(g)d(g) never reaches the output. See inertial and transport delay.
  • Rise and fall delays. A gate can have one delay for a change to 1 and another for a change to 0. With transport delay this can put events out of time order on one net, so simulators use the inertial rule or keep the events sorted.
  • Two-pass algorithm. Process all events of a time first, collect the gates to evaluate, and evaluate them in a second pass. The pseudocode already works this way, which stops a gate from being evaluated twice in one pass.
  • More values. With the values 0, 1, X and Z of multi-valued logic simulation, L8 uses the tables of the value system, and the initial values can be X instead of a guess.
  • Fault simulation. Concurrent fault simulation runs the good circuit and many faulty circuits in one event-driven run and keeps only the gates where a faulty circuit differs.
  • Parallel simulation. The conservative method of Chandy, Misra and Bryant and the optimistic Time Warp split the circuit among processors. See parallel discrete-event simulation.
  • Other engines. For synchronous designs where timing inside the clock cycle is not of interest, compiled-code simulation and cycle-based simulation avoid the event queue.

When to use it

Use event-driven simulation when the delays matter, when the circuit has asynchronous parts or latches, or when the activity is low. It is the engine of every VHDL and Verilog simulator, which also need delta cycles to order the processes that run at the same time. For a synchronous design with high activity and no interest in the timing inside a cycle, a levelized compiled-code or cycle-based simulator is usually several times faster.

Pitfalls

  • Comparing with the present value instead of the projected value. With transport delay and pending events, the test v≠val[out(g)]v \ne \mathrm{val}[\mathrm{out}(g)] drops real events. For example, an output at 0 with a pending change to 1 must still get a new event back to 0.
  • Zero-delay loops. A NOT gate that drives itself with delay 0 makes delta passes for ever. A real simulator needs a limit on the delta passes and a clear error message. The tests show this loop, and a NOR latch whose two inputs fall at the same time, which oscillates for ever with equal delays and also with transport delays 1 and 2.
  • Same-time events in the wrong order. Two events on one net at one time must be applied in the order they were scheduled, or the wrong one wins. A heap that is not stable can break this.
  • Initial values. With all nets at 0 at the start, the first pass at time 0 makes events everywhere. Without that first pass, gates whose inputs never change keep a wrong output for the whole run.
  • Reading glitches as real. The glitches come from the delay model. A glitch in a unit-delay simulation may be absent in the real circuit, and the other way round.

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.

event_driven_logic_simulation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/event-driven-logic-simulation/. The authors are listed in prov/V1JG2T.jsonl.
"""Event-driven gate-level logic simulation with a time wheel (Ulrich 1969).

Only the gates with an input that changed are evaluated (selective trace).
Every gate has an integer delay d >= 0. With d = 0, the new event goes into
the same time slot and is handled in the next delta pass. The default delay
model is transport delay: every change of the gate function reaches the
output d time units later. With inertial=True, a new value cancels the
pending events of the output, so pulses shorter than d are removed.
"""

from __future__ import annotations

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

from logicnet import Circuit, eval2

Event = Tuple[str, int, Optional[int]]  # (net, value, generation of a gate event or None)


class Oscillation(RuntimeError):
    """The delta passes at one time did not settle within the limit."""


class TimeWheel:
    """Ulrich's time mapping: slot t mod M holds the events of time t for now <= t < now + M.

    Events further in the future wait in an overflow heap and move into the
    wheel when the wheel reaches them.
    """

    def __init__(self, size: int):
        self.size = size
        self.slots: List[List[Event]] = [[] for _ in range(size)]
        self.far: List[Tuple[int, int, Event]] = []
        self.now = 0
        self.seq = 0

    def schedule(self, time: int, ev: Event) -> None:
        if time < self.now:
            raise ValueError("an event in the past")
        if time < self.now + self.size:
            self.slots[time % self.size].append(ev)
        else:
            self.seq += 1
            heapq.heappush(self.far, (time, self.seq, ev))

    def take(self, time: int) -> List[Event]:
        slot = self.slots[time % self.size]
        self.slots[time % self.size] = []
        return slot

    def has(self, time: int) -> bool:
        return bool(self.slots[time % self.size])

    def next_time(self) -> Optional[int]:
        for t in range(self.now, self.now + self.size):
            if self.slots[t % self.size]:
                return t
        return self.far[0][0] if self.far else None

    def advance(self, time: int) -> None:
        self.now = time
        while self.far and self.far[0][0] < time + self.size:
            t, _, ev = heapq.heappop(self.far)
            self.slots[t % self.size].append(ev)


def simulate(c: Circuit, delay: Dict[str, int], init: Dict[str, int],
             events: Sequence[Tuple[int, str, int]], t_end: int,
             inertial: bool = False, max_delta: int = 1000):
    """Simulate from time 0 to t_end.

    delay maps each gate output net to its delay. init gives a value in {0, 1}
    to every net. events is a list of input changes (time, net, value).
    Returns (val, changes, evals): the values at t_end, the list of applied
    changes (time, net, value) in order, and the number of gate evaluations.
    """
    size = max([delay[g[0]] for g in c.gates] + [0]) + 1
    val = dict(init)  # @line L1
    proj = dict(init)
    gen = {n: 0 for n in c.nets}
    wheel = TimeWheel(size)  # @line L2
    for t, n, v in sorted(events, key=lambda e: e[0]):
        wheel.schedule(t, (n, v, None))
    changes: List[Tuple[int, str, int]] = []
    evals = 0
    t: Optional[int] = 0
    first = True
    while t is not None and t <= t_end:  # @line L3
        wheel.advance(t)
        passes = 0
        while first or wheel.has(t):
            passes += 1
            if passes > max_delta:
                raise Oscillation(f"no settling at time {t} after {max_delta} delta passes")
            batch: Dict[str, int] = {}
            for n, v, g in wheel.take(t):  # @line L4
                if g is None or g == gen[n]:
                    batch[n] = v  # a later event on the same net replaces an earlier one
            active = [n for n, v in batch.items() if v != val[n]]  # @line L5
            for n in active:
                val[n] = batch[n]
                changes.append((t, n, val[n]))
            if first:
                todo = list(range(len(c.gates)))
                first = False
            else:
                todo = sorted({gi for n in active for gi in c.fanout[n]})  # @line L6
            for gi in todo:  # @line L7
                out, op, ins = c.gates[gi]
                v = eval2(op, [val[n] for n in ins])  # @line L8
                evals += 1
                if v != proj[out]:  # @line L9
                    proj[out] = v  # @line L10
                    if inertial:
                        gen[out] += 1  # cancel the pending events of out
                        if v != val[out]:
                            wheel.schedule(t + delay[out], (out, v, gen[out]))
                    else:
                        wheel.schedule(t + delay[out], (out, v, None))
        t = wheel.next_time()
    return val, changes, evals  # @line L11


def waveform(init: Dict[str, int], changes: Sequence[Tuple[int, str, int]], net: str) -> List[Tuple[int, int]]:
    """The (time, value) steps of one net, starting with its initial value at time 0."""
    w = [(0, init[net])]
    for t, n, v in changes:
        if n == net:
            w.append((t, v))
    return w
logicnet.py 173 lines
# SPDX-License-Identifier: MIT
# Shared helper of the sim1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate netlists and gate functions for the logic simulation pages.

A value is 0, 1 or X = 2, where X means "unknown, it can be 0 or 1".
A circuit has named primary inputs, gates (out, op, ins) and named primary
outputs. Every net is a primary input or the output of exactly one gate.
The gates may form loops, but direct_eval needs a circuit without loops.
This module holds no simulation algorithm. It gives the gate functions, the
netlist, a direct recursive evaluation that serves as the reference, random
circuits for tests and the binary completions of a three-valued vector.
"""

from __future__ import annotations

import itertools
import random
from typing import Dict, Iterator, List, Optional, Sequence, Tuple

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


def eval2(op: str, vals: Sequence[int]) -> int:
    """The gate function on values in {0, 1}."""
    if op == "AND":
        return int(all(vals))
    if op == "OR":
        return int(any(vals))
    if op == "NAND":
        return 1 - int(all(vals))
    if op == "NOR":
        return 1 - int(any(vals))
    if op == "XOR":
        return sum(vals) & 1
    if op == "XNOR":
        return 1 - (sum(vals) & 1)
    if op == "NOT":
        return 1 - vals[0]
    if op == "BUF":
        return vals[0]
    raise ValueError(f"unknown gate {op}")


def not3(v: int) -> int:
    return X if v == X else 1 - v


def eval3(op: str, vals: Sequence[int]) -> int:
    """Kleene's strong three-valued gate function on values in {0, 1, X}."""
    if op in ("AND", "NAND"):
        r = 0 if 0 in vals else (X if X in vals else 1)
        return r if op == "AND" else not3(r)
    if op in ("OR", "NOR"):
        r = 1 if 1 in vals else (X if X in vals else 0)
        return r if op == "OR" else not3(r)
    if op in ("XOR", "XNOR"):
        r = X if X in vals else sum(vals) & 1
        return r if op == "XOR" else not3(r)
    if op == "NOT":
        return not3(vals[0])
    if op == "BUF":
        return vals[0]
    raise ValueError(f"unknown gate {op}")


class Circuit:
    """A gate netlist. gates is a list of (output net, op, list of input nets)."""

    def __init__(self, inputs: Sequence[str], gates: Sequence[Tuple[str, str, Sequence[str]]], outputs: Sequence[str]):
        self.inputs: List[str] = list(inputs)
        self.gates: List[Tuple[str, str, List[str]]] = [(out, op, list(ins)) for out, op, ins in gates]
        self.outputs: List[str] = list(outputs)
        self.driver: Dict[str, int] = {}
        for i, (out, op, ins) in enumerate(self.gates):
            if op not in OPS:
                raise ValueError(f"unknown gate {op}")
            if not ins or (op in ONE_INPUT and len(ins) != 1):
                raise ValueError(f"gate {out} has a wrong number of inputs")
            if out in self.driver or out in self.inputs:
                raise ValueError(f"net {out} has two drivers")
            self.driver[out] = i
        self.nets: List[str] = self.inputs + [g[0] for g in self.gates]
        self.fanout: Dict[str, List[int]] = {n: [] for n in self.nets}
        for i, (out, op, ins) in enumerate(self.gates):
            for n in ins:
                if n not in self.fanout:
                    raise ValueError(f"net {n} has no driver")
                if i not in self.fanout[n]:
                    self.fanout[n].append(i)
        for n in self.outputs:
            if n not in self.fanout:
                raise ValueError(f"output {n} has no driver")

    def is_acyclic(self) -> bool:
        """True when no gate depends on its own output (three-colour depth-first search)."""
        colour = [0] * len(self.gates)
        for root in range(len(self.gates)):
            if colour[root]:
                continue
            colour[root] = 1
            stack = [(root, iter(self.gates[root][2]))]
            while stack:
                g, it = stack[-1]
                nxt = None
                for n in it:
                    if n in self.driver:
                        nxt = self.driver[n]
                        break
                if nxt is None:
                    colour[g] = 2
                    stack.pop()
                elif colour[nxt] == 1:
                    return False
                elif colour[nxt] == 0:
                    colour[nxt] = 1
                    stack.append((nxt, iter(self.gates[nxt][2])))
        return True

    def direct_eval(self, vec: Dict[str, int], three: bool = False) -> Dict[str, int]:
        """Value of every net, each computed from its definition with memoization."""
        f = eval3 if three else eval2
        val: Dict[str, int] = {n: vec[n] for n in self.inputs}
        busy = set()

        def get(n: str) -> int:
            if n in val:
                return val[n]
            if n in busy:
                raise ValueError("the circuit has a loop")
            busy.add(n)
            out, op, ins = self.gates[self.driver[n]]
            val[n] = f(op, [get(m) for m in ins])
            return val[n]

        for n in self.nets:
            get(n)
        return val


def random_circuit(rng: random.Random, n_inputs: int, n_gates: int, n_outputs: Optional[int] = None,
                   loops: bool = False, ops: Sequence[str] = OPS) -> Circuit:
    """A random circuit. Without loops, gate k reads only inputs and gates 0..k-1."""
    inputs = [f"i{k}" for k in range(n_inputs)]
    names = [f"g{k}" for k in range(n_gates)]
    gates = []
    for k in range(n_gates):
        op = rng.choice(ops)
        pool = inputs + (names if loops else names[:k])
        arity = 1 if op in ONE_INPUT else rng.randint(2, 3)
        ins = rng.sample(pool, min(arity, len(pool)))
        if op not in ONE_INPUT and len(ins) < 2:
            op = "BUF"
        gates.append((names[k], op, ins))
    if n_outputs is None:
        n_outputs = min(3, n_gates)
    return Circuit(inputs, gates, names[n_gates - n_outputs:])


def all_vectors(names: Sequence[str]) -> Iterator[Dict[str, int]]:
    """Every assignment of 0 and 1 to the names."""
    for bits in itertools.product((0, 1), repeat=len(names)):
        yield dict(zip(names, bits))


def completions(vec: Dict[str, int]) -> Iterator[Dict[str, int]]:
    """Every binary vector that agrees with vec wherever vec is not X."""
    free = [n for n, v in vec.items() if v == X]
    for bits in itertools.product((0, 1), repeat=len(free)):
        out = dict(vec)
        out.update(zip(free, bits))
        yield out
test_event_driven_logic_simulation.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/event-driven-logic-simulation/. The authors are listed in prov/V1JG2T.jsonl.

import random

import pytest

from event_driven_logic_simulation import Oscillation, TimeWheel, simulate, waveform
from logicnet import Circuit, all_vectors, eval2, random_circuit

# The page example: y = ab + a'c, with b = c = 1 and a falling at time 10.
HAZARD = Circuit(
    ["a", "b", "c"],
    [("na", "NOT", ["a"]), ("p", "AND", ["a", "b"]), ("q", "AND", ["na", "c"]), ("y", "OR", ["p", "q"])],
    ["y"],
)
HAZARD_INIT = {"a": 1, "b": 1, "c": 1, "na": 0, "p": 1, "q": 0, "y": 1}


def values_at(init, changes, t):
    val = dict(init)
    for tc, n, v in changes:
        if tc > t:
            break
        val[n] = v
    return val


def step_reference(c, delay, init, events, t_end, inertial=False):
    """Unit-time step simulation. Every delay must be at least 1.

    z(t) is the gate function of the values at time t. With transport delay,
    out(t) = z(t - d). With inertial delay, out(t) = z(t - d) when z kept that
    value on all of t - d, ..., t - 1, and out(t) = out(t - 1) otherwise.
    """
    evs = sorted(events, key=lambda e: e[0])
    hist, zhist = [], []
    for t in range(t_end + 1):
        cur = {n: init[n] for n in c.inputs}
        for te, n, v in evs:
            if te <= t:
                cur[n] = v
        for out, op, ins in c.gates:
            d = delay[out]
            if t < d:
                cur[out] = init[out]
            elif not inertial:
                cur[out] = zhist[t - d][out]
            elif all(zhist[s][out] == zhist[t - d][out] for s in range(t - d, t)):
                cur[out] = zhist[t - d][out]
            else:
                cur[out] = hist[t - 1][out]
        z = {out: eval2(op, [cur[n] for n in ins]) for out, op, ins in c.gates}
        hist.append(cur)
        zhist.append(z)
    return hist


def depth(c):
    memo = {n: 0 for n in c.inputs}

    def lev(n):
        if n not in memo:
            memo[n] = 1 + max(lev(m) for m in c.gates[c.driver[n]][2])
        return memo[n]

    return max([lev(n) for n in c.nets] + [0])


def test_time_wheel_order_and_overflow():
    w = TimeWheel(3)
    for t in (7, 0, 2, 2, 30):
        w.schedule(t, (str(t), 0, None))
    seen = []
    t = w.next_time()
    while t is not None:
        w.advance(t)
        seen += [(t, e[0]) for e in w.take(t)]
        t = w.next_time()
    assert seen == [(0, "0"), (2, "2"), (2, "2"), (7, "7"), (30, "30")]


@pytest.mark.parametrize("seed", range(6))
def test_zero_delay_equals_direct_evaluation(seed):
    rng = random.Random(seed)
    c = random_circuit(rng, rng.randint(2, 6), rng.randint(3, 25))
    zero = {g[0]: 0 for g in c.gates}
    vectors = list(all_vectors(c.inputs))
    init = {n: 0 for n in c.nets}
    events = [(10 * k, n, vec[n]) for k, vec in enumerate(vectors) for n in c.inputs]
    _, changes, _ = simulate(c, zero, init, events, 10 * len(vectors))
    for k, vec in enumerate(vectors):
        assert values_at(init, changes, 10 * k) == c.direct_eval(vec)


@pytest.mark.parametrize("seed", range(6))
def test_unit_delay_settles_to_direct_evaluation_within_depth(seed):
    rng = random.Random(100 + seed)
    c = random_circuit(rng, rng.randint(2, 6), rng.randint(3, 25))
    unit = {g[0]: 1 for g in c.gates}
    dep = depth(c)
    for vec in all_vectors(c.inputs):
        init = c.direct_eval({n: 1 - v for n, v in vec.items()})
        events = [(0, n, vec[n]) for n in c.inputs]
        val, changes, _ = simulate(c, unit, init, events, 1000)
        assert val == c.direct_eval(vec)
        assert all(t <= dep for t, _, _ in changes)


@pytest.mark.parametrize("seed", range(12))
@pytest.mark.parametrize("inertial", [False, True])
def test_integer_delays_match_step_reference(seed, inertial):
    rng = random.Random(200 + seed)
    c = random_circuit(rng, rng.randint(1, 4), rng.randint(2, 14), loops=seed % 2 == 1)
    delay = {g[0]: rng.randint(1, 3) for g in c.gates}
    init = {n: rng.randint(0, 1) for n in c.nets}
    events = [(rng.randint(0, 30), rng.choice(c.inputs), rng.randint(0, 1)) for _ in range(rng.randint(0, 12))]
    _, changes, _ = simulate(c, delay, init, events, 40, inertial=inertial)
    ref = step_reference(c, delay, init, events, 40, inertial=inertial)
    for t in range(41):
        assert values_at(init, changes, t) == ref[t]


def test_zero_delay_loop_oscillates():
    ring = Circuit(["a"], [("y", "NOT", ["y"])], ["y"])
    with pytest.raises(Oscillation):
        simulate(ring, {"y": 0}, {"a": 0, "y": 0}, [], 5, max_delta=50)
    _, changes, _ = simulate(ring, {"y": 1}, {"a": 0, "y": 0}, [], 6)
    assert waveform({"y": 0}, changes, "y") == [(0, 0), (1, 1), (2, 0), (3, 1), (4, 0), (5, 1), (6, 0)]


def test_three_inverter_ring_has_period_six():
    ring = Circuit(["a"], [("x", "NOT", ["z"]), ("y", "NOT", ["x"]), ("z", "NOT", ["y"])], ["z"])
    init = {"a": 0, "x": 1, "y": 0, "z": 1}
    _, changes, _ = simulate(ring, {"x": 1, "y": 1, "z": 1}, init, [], 24)
    w = waveform(init, changes, "z")
    rises = [t for t, v in w[1:] if v == 1]
    assert [b - a for a, b in zip(rises, rises[1:])] == [6] * (len(rises) - 1)


def test_nor_latch_race():
    latch = Circuit(["s", "r"], [("q", "NOR", ["r", "qn"]), ("qn", "NOR", ["s", "q"])], ["q"])
    init = {"s": 1, "r": 1, "q": 0, "qn": 0}
    release = [(5, "s", 0), (5, "r", 0)]
    _, changes, _ = simulate(latch, {"q": 1, "qn": 1}, init, release, 40)
    assert len([1 for t, n, _ in changes if n == "q" and t > 30]) > 0  # equal delays: it keeps toggling
    _, changes, _ = simulate(latch, {"q": 1, "qn": 2}, init, release, 40)
    assert len([1 for t, n, _ in changes if n == "q" and t > 30]) > 0  # transport keeps the pulses alive
    val, changes, _ = simulate(latch, {"q": 1, "qn": 2}, init, release, 40, inertial=True)
    assert (val["q"], val["qn"]) == (1, 0) and max(t for t, _, _ in changes) == 6
    with pytest.raises(Oscillation):
        simulate(latch, {"q": 0, "qn": 0}, init, release, 40, max_delta=50)


def test_page_example_glitch():
    unit = {g[0]: 1 for g in HAZARD.gates}
    _, changes, _ = simulate(HAZARD, unit, HAZARD_INIT, [(10, "a", 0)], 30)
    assert waveform(HAZARD_INIT, changes, "y") == [(0, 1), (12, 0), (13, 1)]
    _, changes, _ = simulate(HAZARD, dict(unit, y=2), HAZARD_INIT, [(10, "a", 0)], 30, inertial=True)
    assert waveform(HAZARD_INIT, changes, "y") == [(0, 1)]
    _, changes, _ = simulate(HAZARD, dict(unit, y=2), HAZARD_INIT, [(10, "a", 0)], 30)
    assert waveform(HAZARD_INIT, changes, "y") == [(0, 1), (13, 0), (14, 1)]
    zero = {g[0]: 0 for g in HAZARD.gates}
    _, changes, _ = simulate(HAZARD, zero, HAZARD_INIT, [(10, "a", 0)], 30)
    assert waveform(HAZARD_INIT, changes, "y") == [(0, 1), (10, 0), (10, 1)]


def test_selective_trace_evaluates_only_the_fanout_cone():
    n = 40
    gates = [(f"x{k}", "NOT", [f"a{k}"]) for k in range(n)]
    c = Circuit([f"a{k}" for k in range(n)], gates, ["x0"])
    init = c.direct_eval({f"a{k}": 0 for k in range(n)})
    _, changes, evals = simulate(c, {f"x{k}": 1 for k in range(n)}, init, [(5, "a7", 1)], 20)
    assert evals == n + 1  # n at time 0, then one gate for the change of a7
    assert changes == [(5, "a7", 1), (6, "x7", 0)]

History

Ernst Ulrich described simulation with circuit delays and the selective trace of active paths in 1965, and the time mapping, the circular list of time slots now called a time wheel, in his 1969 paper in the Communications of the ACM. Event-driven gate-level simulation then became the standard method for logic verification and for fault simulation in the 1970s. The hardware description languages VHDL (IEEE Std 1076, first in 1987) and Verilog (IEEE Std 1364, first in 1995) both define their meaning by an event-driven simulation cycle with delta cycles.

References

  1. E. G. Ulrich, Exclusive simulation of activity in digital networks, Communications of the ACM 12(2), 102 to 110, February 1969, the evaluation of only the active elements, and time mapping, a circular list of time slots for the scheduled events
  2. E. G. Ulrich, Time-sequenced logical simulation based on circuit delay and selective tracing of active network paths, Proceedings of the 20th ACM National Conference, 437 to 448, 1965, selective trace, the evaluation of the fanout of the elements that changed
  3. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter Logic Simulation (event-driven simulation, delay models, time wheel, two-pass algorithm, hazard detection)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.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