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.
- Solves
- Logic simulation
- 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
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with nets, gate input pins and gates that each have a Boolean function , an output net and an integer delay . Each net has an initial value in , 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 to , given as the list of changes.
The meaning of the delays is the transport model. Let be the value that the gate function asks for. Then the output follows it after the delay: for , 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
EVENT-SIM(C, d, v0, input events, T_end)- 1
val ← v0; proj ← v0 (proj is the last value scheduled on a net) - 2
W ← a time wheel that holds the input events; do one pass of L7 to L10 at time 0 with G = all gates - 3
while W has events at a time t ≤ T_end, with t the earliest such time, do - 4
U ← the events of time t, taken out of W; a later event on a net replaces an earlier one - 5
A ← the nets n in U with U[n] ≠ val[n]; set val[n] ← U[n] for each n in A - 6
G ← the gates with an input in A (selective trace) - 7
for each gate g in G do - 8
v ← f_g(val of the inputs of g) - 9
if v ≠ proj[out(g)] then - 10
proj[out(g)] ← v; schedule (t + d(g), out(g), v) in W - 11
return val and the list of changes made at L5
The time wheel is Ulrich's time mapping. It is an array of slots, where is one more than the largest gate delay, and slot holds the events of time . The input events that lie more than 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 . 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 , line L10 puts the event into the slot of the present time . The loop at L3 then finds time 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 with gates , , and . Let , so for both values of . Every gate has delay 1. At the start , so , , and , and 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 | , | and at 11 | |
| 11 | , | , | at 12; at 12 |
| 12 | , | at 13 | |
| 13 | none | none |
The output has a glitch: is 0 for one time unit from 12 to 13, because the path through is one gate longer than the path through . 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 , then and , then and , then . So even with zero delay, shows a pulse of zero width at time 10, which a VHDL or Verilog process that waits on 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 equal those of a unit-time step simulation with for every integer , on any circuit, with or without loops. The key invariant is that, after time , the events pending on an output describe exactly the values for , and the projected value is . A gate that L6 does not select has the same inputs as at the previous time, so its 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 passes, where 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 , 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 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 be a gate-level circuit. Each gate has a function , an output net and an integer delay . Every net has an initial value in , and the inputs change only by the given input events. For a time let be the values of all nets at time in the model, and let . Lines L1 to L11 refer to the pseudocode of the page.
Transport model. For integer delays , is defined by induction on : an input net has the value of its last input event at a time (or ), and if and otherwise. This is well defined, because depends only on values at earlier times. To make the statements uniform, put for .
For a gate output and a time after the present time, let be the value of the last pending event on at a time , or 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 . For every integer , after the algorithm has handled time (or has skipped it because had no event at ), . This holds on any circuit, with or without loops.
Proof. We prove by induction on the invariant : after time is handled,
- (for , read this as );
- for every gate with and : , and for all with ;
- no pending event has a time .
Base, . L1 sets , and only input events are pending. For we have , and .
Step from to . By part 3 of , the events taken at L4 are exactly the pending events of time . For an input net, they are the input events of time , and the last one wins, as in . For a gate output , the last event at time , or no event, gives the new value by part 2. So after L5, , which is part 1. Since all delays are at least 1, the events scheduled at time have times , so there is one pass at time and part 3 holds.
Now take a gate with . If no input of is in the set of L5, then the inputs of have the same values at and (at every gate is evaluated, so this case does not occur there). So , and nothing is scheduled. The window gains the point , and , because no event on lies at time : an event at would have been scheduled at time . If is evaluated, L8 computes , because . Two cases.
- . Nothing is scheduled, and the same argument as above gives part 2.
- . L10 sets and schedules at . All other pending events on lie at times , so this event is the last one at or before , and . For , nothing changed, and by .
If the algorithm skips time because no event is pending at , then no net changes at , so (by part 2, every gate output keeps ), every , and the argument of the unselected case gives .
Inertial model. Here if has the same value at all integer times , and otherwise (with the initial value for ). In the algorithm, L10 cancels all pending events of and schedules at only if .
Theorem 2 (inertial delay, delays at least 1). With the inertial rule, after time , for every and every circuit.
Proof. Replace part 2 of the invariant by: , and has at most one live pending event. It exists exactly when , and then it has the value and the time , where is the last time at which changed (that is, ). The step is as before. A gate whose does not change at gives , so nothing happens. A gate whose changes at gives , so the old event is cancelled, and a new one at is made exactly when . So changes at time exactly when changed at to a value and did not change at . This is the rule of the model: if is constant on and changed at , then , and if it is constant there but did not change at , then it was constant on , so already has that value.
Theorem 3 (zero delay, acyclic circuit). Let every and let have no loops, with depth (the largest number of gates on a path). At each time that has events, the delta passes stop after at most passes, and then equals the direct evaluation of on the inputs of time .
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 . A gate evaluated in pass has an input that changed in pass ; if all changes in pass are on nets of level , then each evaluated gate has level , and its event, applied in pass , is on a net of level . By induction, the changes in pass are on nets of level . No net has a level above , so pass has no events, and there are at most passes.
When the passes stop, no event is pending at time , and with zero delays no event is pending at any later time either. For each gate output , is the value of the last event scheduled on , and that event has been applied, so . After each pass, for every gate: it held after was last evaluated, and the inputs of have not changed since, because every change of an input puts into the set of L6. So 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.
Corollary (unit delay, acyclic circuit). With every , if the last input event is at time , then does not change after , and it then equals the direct evaluation of on the final inputs.
Proof. By Theorem 1, is the unit-delay model. A net of level has a value at time that depends only on the inputs at times , which are the final inputs: by induction on , , and the inputs of have level , so their values at are already the direct values.
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 gates, and each evaluation at L8 reads at most inputs. Each scheduled event costs in the wheel. Moving to the next event time costs at most slot checks. So the time is , where is the number of applied changes and is the number of distinct event times. The space is for the netlist, the values and the projected values, plus the pending events, of which there are at most .
The cost follows the activity , not the circuit size times the time. This is the point of the method. The activity can be large, though. A stage in which the buffer has delay turns each change of its input into two changes of its output. One input change then makes changes at the end of a chain of stages, which has gates. A script with the implementation of this page counted 2, 4, 8, ..., 128 output changes for . With unit delays and no loops this cannot happen: a net changes at most 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 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 and then schedules only if . A pulse at the gate function that is shorter than 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 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.
# 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
- 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
- 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
- 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.
| 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 V1JG2T Edit this page History Report an error Markdown