Algorithm Search⌘K

Algorithmcore

Cycle-based simulation

Also called cycle simulation.

Simulates a synchronous design one clock cycle at a time, evaluating the logic between registers once per cycle in levelized order, with no timing inside the cycle.

Time
O(N + P + T (G + P)) worst · best
Space
O(N + P) extra
Where
G = the number of gates; N = the number of nets; P = the number of gate input pins; T = the number of clock cycles
Properties
deterministicexactiterative

Cycle-based simulation runs a synchronous design one clock cycle at a time. The registers cut every loop, so the logic between them has no loops and can be put in levelized order once. In each cycle the simulator evaluates every gate once, in that order, from the primary inputs of the cycle and the register values, and then all registers take the values at their data inputs together, as at a clock edge. This page is in the logic simulation half of logic and circuit simulation. The delay model is zero delay inside the cycle: the clock edge is the only time, and nothing is computed about when a signal settles. That is enough when static timing analysis has already shown that every path meets the setup constraint, and it lets the simulator drop the event queue and run the logic as compiled code.

In plain words

In a synchronous design all registers change at the clock edge. Between two edges the gates do their work, and if the design is timed right, every signal has its final value before the next edge.

So the simulator does not track time inside the cycle. For each cycle it sets the inputs, runs through the gates once in an order where each gate comes after the gates it reads, and copies the new values into the registers. One cycle costs one evaluation per gate, whatever the delays are.

What it cannot show is anything that happens between the edges: glitches, races, or a path that is too slow.

The problem

The input is a synchronous design with one clock: primary inputs, D flip-flops rr with an output qrq_r, a data input drd_r and an initial value, gates, and a list of primary outputs. Every loop of gates must pass through a register. The design is a Mealy machine: the state ss is the vector of register values, and for an input vector xx the logic gives the next state δ(s,x)\delta(s, x), the values of the drd_r, and the outputs λ(s,x)\lambda(s, x). Given s0s_0 and inputs x1,…,xTx_1, \ldots, x_T, the output is λ(sk−1,xk)\lambda(s_{k-1}, x_k) for each cycle kk, where sk=δ(sk−1,xk)s_k = \delta(s_{k-1}, x_k).

The algorithm

  1. CYCLE-SIM(design, s0, x_1, ..., x_T)
  2. 1cut every register r: q_r becomes an input of the logic L and d_r an output of L
  3. 2levelize the gates of L by Kahn's algorithm; stop with "loop" if a loop of gates is not cut by a register
  4. 3s ← s0
  5. 4for k = 1 to T do
  6. 5evaluate every gate of L once, in level order, on the inputs x_k and the register values s
  7. 6record the values of the primary outputs for cycle k
  8. 7s ← the values of d_r for all registers r, all at once
  9. 8return the recorded outputs and s

Line L7 must take all new register values from the values computed in L5 before it writes any of them. Writing the registers one by one, so that a later register reads the new value of an earlier one, is the classic bug of a shift register simulated in the wrong order.

Line L5 can be the bit-parallel program of compiled-code simulation. Then each lane of a word runs its own copy of the design, for example with a different random seed of the test bench.

Example

A serial adder adds two numbers given least significant bit first. It has inputs aa and bb, one register cc for the carry, initial value 0, and the gates x1=a⊕bx_1 = a \oplus b, s=x1⊕cs = x_1 \oplus c, g1=abg_1 = ab, g2=x1cg_2 = x_1 c and c′=g1+g2c' = g_1 + g_2, which is the data input of cc. Add 6=011026 = 0110_2 and 7=011127 = 0111_2, so a=0,1,1,0,0a = 0, 1, 1, 0, 0 and b=1,1,1,0,0b = 1, 1, 1, 0, 0 in cycles 1 to 5.

cycle aa bb cc x1x_1 ss g1g_1 g2g_2 c′c'
1 0 1 0 1 1 0 0 0
2 1 1 0 0 0 1 0 1
3 1 1 1 0 1 1 0 1
4 0 0 1 0 1 0 0 0
5 0 0 0 0 0 0 0 0

The sum bits are 1,0,1,1,01, 0, 1, 1, 0, which is 011012=1301101_2 = 13. Each cycle evaluates five gates in the order x1,g1x_1, g_1 (level 1), s,g2s, g_2 (level 2) and c′c' (level 3), so 25 gate evaluations for the whole run.

The tests also show what the method gives up. In a design where q′=NOT(NOT(NOT(q)))q' = \mathrm{NOT}(\mathrm{NOT}(\mathrm{NOT}(q))), the logic has depth 3. A unit-delay simulation with a clock period of 4 time units samples settled values and agrees with the cycle-based run. With a period of 2 it samples values that have not settled, and the two runs differ. The cycle-based run cannot see this setup violation.

Correctness

The proof in proofs/correctness.md shows two things. First, line L5 computes δ(s,xk)\delta(s, x_k) and λ(s,xk)\lambda(s, x_k) exactly, by the argument of compiled-code simulation on the loop-free logic, so by induction on kk the run gives the outputs and states of the Mealy machine. Second, it relates the result to timed behavior: if every gate has delay 1 and the clock period is larger than the depth DD of the logic, a net of level ℓ\ell has its final value from ℓ\ell time units after the edge, so the values sampled just before the next edge are the values of the cycle-based run. The tests check the first claim against an explicit next-state table built by direct evaluation of every pair of state and input, and the second against a unit-delay step simulation with period D+1D + 1, on random designs.

Proof: Cycle-based simulation computes the Mealy machine of the design, and agrees with unit-delay timing when the period exceeds the depthfull

Let the design have primary inputs, registers rr with outputs qrq_r, data inputs drd_r and initial values, and gates. After the cut of line L1, the logic LL has inputs xx (the primary inputs) and qq (the register outputs), and every loop of gates of the design passes through a register, so LL has no loop. For values ss of the registers and xx of the inputs, every net nn of LL has a unique value Ln(s,x)L_n(s, x), defined by induction on the level. Put δ(s,x)=(Ldr(s,x))r\delta(s, x) = (L_{d_r}(s, x))_r and λ(s,x)=(Lo(s,x))o\lambda(s, x) = (L_o(s, x))_o for the primary outputs oo. Lines L1 to L8 refer to the pseudocode of the page.

Theorem 1 (the Mealy machine). For inputs x1,…,xTx_1, \ldots, x_T, let sk=δ(sk−1,xk)s_k = \delta(s_{k-1}, x_k). In cycle kk, line L6 records λ(sk−1,xk)\lambda(s_{k-1}, x_k), and after line L7 of cycle kk, s=sks = s_k.

Proof. Line L2 succeeds, since LL has no loop (Kahn's algorithm levelizes every loop-free netlist; see the proof of compiled-code simulation). By induction on kk: before cycle kk, s=sk−1s = s_{k-1} (true for k=1k = 1 by L3). Line L5 evaluates the gates in an order where every gate follows the drivers of its inputs, so by induction along the order, every net nn gets the value Ln(sk−1,xk)L_n(s_{k-1}, x_k). Line L6 records λ(sk−1,xk)\lambda(s_{k-1}, x_k). Line L7 reads all values Ldr(sk−1,xk)L_{d_r}(s_{k-1}, x_k) before it writes any register, so s=δ(sk−1,xk)=sks = \delta(s_{k-1}, x_k) = s_k. □\square

Timed model. Give every gate delay 1, and let the clock have period pp. In cycle kk the primary inputs hold xkx_k and the registers hold sk−1′s'_{k-1} during the time steps (k−1)p,…,kp−1(k-1)p, \ldots, kp - 1. A gate output at step tt is the gate function of the values at step t−1t - 1; before the first step the gate outputs have arbitrary values. At the end of cycle kk the registers take sk′s'_k, the values of the drd_r at step kp−1kp - 1, and the outputs are sampled at the same step. Let DD be the depth of LL, the largest level of a net.

Theorem 2 (agreement with timing). If p≥D+1p \ge D + 1, then sk′=sks'_k = s_k for every kk, and the outputs sampled at step kp−1kp - 1 are λ(sk−1,xk)\lambda(s_{k-1}, x_k).

Proof. Induction on kk, with s0′=s0s'_0 = s_0. In cycle kk, the inputs and registers are xkx_k and sk−1′=sk−1s'_{k-1} = s_{k-1} at all steps of the cycle. Claim: a net of level ℓ\ell has the value Ln(sk−1,xk)L_n(s_{k-1}, x_k) at every step tt with (k−1)p+ℓ≤t≤kp−1(k-1)p + \ell \le t \le kp - 1. For ℓ=0\ell = 0 the net is an input or a register output, constant over the cycle. For a gate output of level ℓ≥1\ell \ge 1 and a step t≥(k−1)p+ℓt \ge (k-1)p + \ell, its value is the gate function of the values at step t−1≥(k−1)p+ℓ−1t - 1 \ge (k-1)p + \ell - 1, where every input of the gate, of level at most ℓ−1\ell - 1, already has its final value by induction. So the gate output has the value Ln(sk−1,xk)L_n(s_{k-1}, x_k). Since ℓ≤D≤p−1\ell \le D \le p - 1, step kp−1kp - 1 lies in the range for every net, so the sampled outputs are λ(sk−1,xk)\lambda(s_{k-1}, x_k) and sk′=δ(sk−1,xk)=sks'_k = \delta(s_{k-1}, x_k) = s_k. □\square

The bound is tight for some designs. If p≤Dp \le D, a net of level DD whose value changes in a cycle can be sampled before it settles; the tests show a design with D=3D = 3 where p=2p = 2 gives a different run. Real delays are not unit, and the condition p≥D+1p \ge D + 1 becomes the setup constraint of static timing analysis, with the delay of each path in place of its length.

Complexity

Levelization costs O(N+P)O(N + P) once. Each cycle evaluates each gate once and reads each input pin once, so it costs O(G+P)O(G + P), and TT cycles cost O(T(G+P))O(T(G + P)). The memory is the netlist and one value per net, O(N+P)O(N + P). With bit-parallel words of WW bits, WW independent runs cost the same as one.

An event-driven simulator of the same design spends work only on the nets that change, but pays for the queue and for every glitch inside the cycle. In designs where a large part of the logic is active in every cycle, cycle-based simulation is faster, by a factor that depends on the activity and on the glitches it avoids; this page does not measure it.

Properties

  • Exact at the clock edges for designs that meet their timing, and blind between them.
  • Deterministic order. Races between registers cannot appear, since all registers update together at L7. A real circuit with clock skew or a hold violation can still have such a race.
  • No initialization by time. The initial state is given. With unknown initial state the values must be X, which needs multi-valued logic and brings X pessimism.

Variants and improvements

  • Multiple clocks. With several clocks of fixed ratio, the simulator steps through the clock edges in time order and at each edge evaluates the logic that feeds the registers of that clock.
  • Event-driven cycles. Evaluate only the cones whose inputs changed since the last cycle. This saves work when most of the design is idle, at the cost of a little bookkeeping.
  • Latches. Two-phase latch designs can be simulated by evaluating the logic once per phase.
  • Hardware engines and emulators. Special machines such as the Yorktown Simulation Engine run the same once-per-cycle evaluation in parallel hardware.
  • Unrolling for analysis. The same cut at the registers gives the time-frame expansion used in sequential test generation and bounded model checking.

When to use it

Use cycle-based simulation for long functional runs of synchronous designs: processor regressions, software running on a hardware model, and checks where only the values at the clock edges matter. Use event-driven simulation when the design has asynchronous parts, combinational loops, latches with transparency that matters, several unrelated clocks, or when glitches and delays are the point of the run. Use static timing analysis, not simulation, to check that the cycle-based assumption holds.

Pitfalls

  • Updating registers one at a time. A shift register q1←dq_1 \leftarrow d, q2←q1q_2 \leftarrow q_1 then shifts the input two places in one cycle. Compute all new values, then write them.
  • Loops not cut by a register. A cross-coupled latch made of gates has no levelized order. The implementation rejects it.
  • Assuming the timing is fine. A cycle-based run passes even when a path is longer than the clock period. The match with real timing holds only after static timing analysis.
  • Gated and derived clocks. A clock that goes through logic makes registers update at times the simple model does not know. Such designs need care in the order of edges, or event-driven simulation.
  • Asynchronous resets. A reset that acts without a clock edge is outside the model and must be handled as a special case.

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.

cycle_based_simulation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cycle-based-simulation/. The authors are listed in prov/BBKYW7.jsonl.
"""Cycle-based simulation of a synchronous design with one clock.

The registers cut every loop. The logic between them is levelized once and
then evaluated once per clock cycle with zero delay, and all registers take
their new values together at the clock edge. There is no time inside a cycle.
"""

from __future__ import annotations

from typing import Dict, List, Sequence, Tuple

from logicnet import Circuit, eval2


class CombinationalLoop(ValueError):
    """A loop of gates that no register cuts."""


class SyncDesign:
    """inputs: primary inputs. regs: (q, d, initial value) for each D flip-flop.

    gates: (out, op, ins) of the logic. outputs: nets observed each cycle.
    """

    def __init__(self, inputs: Sequence[str], regs: Sequence[Tuple[str, str, int]],
                 gates: Sequence[Tuple[str, str, Sequence[str]]], outputs: Sequence[str]):
        self.inputs = list(inputs)
        self.regs = [(q, d, v) for q, d, v in regs]
        # The register outputs become inputs of the logic and the D nets its outputs.
        self.logic = Circuit(self.inputs + [q for q, _, _ in self.regs], gates, list(outputs) + [d for _, d, _ in self.regs])  # @line L1
        self.outputs = list(outputs)


def levelize(c: Circuit) -> List[int]:
    """Kahn's algorithm on the gate graph of the logic."""
    waiting = [len({n for n in ins if n in c.driver}) for _, _, ins in c.gates]
    order = [i for i in range(len(c.gates)) if waiting[i] == 0]
    head = 0
    while head < len(order):
        out = c.gates[order[head]][0]
        head += 1
        for h in c.fanout[out]:
            waiting[h] -= 1
            if waiting[h] == 0:
                order.append(h)
    if len(order) != len(c.gates):
        raise CombinationalLoop("a loop of gates is not cut by a register")
    return order


def simulate(design: SyncDesign, stimulus: Sequence[Dict[str, int]]) -> Tuple[List[Dict[str, int]], Dict[str, int]]:
    """Run one cycle per entry of stimulus. Returns the outputs of each cycle and the final state."""
    c = design.logic
    order = levelize(c)  # @line L2
    state = {q: v for q, _, v in design.regs}  # @line L3
    trace: List[Dict[str, int]] = []
    for x in stimulus:  # @line L4
        val = dict(x)
        val.update(state)
        for g in order:  # @line L5
            out, op, ins = c.gates[g]
            val[out] = eval2(op, [val[n] for n in ins])
        trace.append({o: val[o] for o in design.outputs})  # @line L6
        state = {q: val[d] for q, d, _ in design.regs}  # @line L7
    return trace, state  # @line L8
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_cycle_based_simulation.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cycle-based-simulation/. The authors are listed in prov/BBKYW7.jsonl.

import itertools
import random

import pytest

from cycle_based_simulation import CombinationalLoop, SyncDesign, simulate
from logicnet import eval2, random_circuit

# The page example: a serial adder with one carry register.
ADDER = SyncDesign(
    ["a", "b"],
    [("c", "cn", 0)],
    [("x1", "XOR", ["a", "b"]), ("s", "XOR", ["x1", "c"]), ("g1", "AND", ["a", "b"]),
     ("g2", "AND", ["x1", "c"]), ("cn", "OR", ["g1", "g2"])],
    ["s"],
)


def random_design(rng):
    n_in, n_reg = rng.randint(1, 3), rng.randint(1, 4)
    c = random_circuit(rng, n_in + n_reg, rng.randint(2, 20), n_outputs=2)
    qs = c.inputs[n_in:]
    regs = [(q, rng.choice([g[0] for g in c.gates] + qs), rng.randint(0, 1)) for q in qs]
    return SyncDesign(c.inputs[:n_in], regs, c.gates, c.outputs)


def fsm_table(design):
    """The explicit next-state and output table, from direct evaluation of every (state, input) pair."""
    qs = [q for q, _, _ in design.regs]
    table = {}
    for s in itertools.product((0, 1), repeat=len(qs)):
        for x in itertools.product((0, 1), repeat=len(design.inputs)):
            full = design.logic.direct_eval(dict(zip(qs + design.inputs, s + x)))
            table[s, x] = (tuple(full[d] for _, d, _ in design.regs), {o: full[o] for o in design.outputs})
    return table


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 clocked_step_reference(design, stimulus, period):
    """Unit delay per gate. Inputs change at the clock edge; registers sample the D nets just before the next edge."""
    c = design.logic
    state = {q: v for q, _, v in design.regs}
    prev = {n: 0 for n in c.nets}
    prev.update(state)
    trace = []
    for x in stimulus:
        for _ in range(period):
            cur = dict(x)
            cur.update(state)
            for out, op, ins in c.gates:
                cur[out] = eval2(op, [prev[n] for n in ins])
            prev = cur
        trace.append({o: prev[o] for o in design.outputs})
        state = {q: prev[d] for q, d, _ in design.regs}
    return trace, state


def test_serial_adder():
    a, b = [0, 1, 1, 0, 0], [1, 1, 1, 0, 0]  # 6 and 7, least significant bit first
    trace, state = simulate(ADDER, [{"a": p, "b": q} for p, q in zip(a, b)])
    assert [t["s"] for t in trace] == [1, 0, 1, 1, 0]  # 13
    assert state == {"c": 0}


@pytest.mark.parametrize("seed", range(15))
def test_matches_explicit_fsm_table(seed):
    rng = random.Random(seed)
    d = random_design(rng)
    table = fsm_table(d)
    stim = [{n: rng.randint(0, 1) for n in d.inputs} for _ in range(60)]
    trace, state = simulate(d, stim)
    s = tuple(v for _, _, v in d.regs)
    for x, out in zip(stim, trace):
        s, want = table[s, tuple(x[n] for n in d.inputs)]
        assert out == want
    assert tuple(state[q] for q, _, _ in d.regs) == s


@pytest.mark.parametrize("seed", range(15))
def test_matches_unit_delay_reference_when_the_period_exceeds_the_depth(seed):
    rng = random.Random(100 + seed)
    d = random_design(rng)
    stim = [{n: rng.randint(0, 1) for n in d.inputs} for _ in range(30)]
    period = depth(d.logic) + 1
    assert clocked_step_reference(d, stim, period) == simulate(d, stim)


def test_short_period_breaks_the_match():
    # q' = NOT(NOT(NOT(q))) has depth 3, so a period of 2 samples a value that has not settled.
    d = SyncDesign([], [("q", "n3", 0)], [("n1", "NOT", ["q"]), ("n2", "NOT", ["n1"]), ("n3", "NOT", ["n2"])], ["q"])
    stim = [{}] * 8
    assert clocked_step_reference(d, stim, 4) == simulate(d, stim)
    assert clocked_step_reference(d, stim, 2) != simulate(d, stim)


def test_loop_not_cut_by_a_register_is_rejected():
    d = SyncDesign(["s", "r"], [], [("q", "NOR", ["r", "qn"]), ("qn", "NOR", ["s", "q"])], ["q"])
    with pytest.raises(CombinationalLoop):
        simulate(d, [{"s": 0, "r": 0}])

History

Cycle simulation grew with design styles that make every loop pass through a register. IBM's level-sensitive scan design rules (scan design) are one such style, and IBM built engines on this assumption: the Yorktown Simulation Engine (Pfister, 1982) evaluated the whole logic once per machine cycle in special hardware, and HSS (Barzilai, Carter, Rosen and Rutledge, 1987) ran the loop-free logic between latches as compiled code on 16 or 32 patterns at a time. Cycle-based software simulators and hardware emulators then became the usual tools for long functional runs of large synchronous designs, next to event-driven simulators of VHDL and Verilog.

References

  1. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter Logic Simulation (compiled simulation of synchronous circuits, levelization, and the comparison with event-driven simulation)
  2. Zeev Barzilai, J. Lawrence Carter, Barry K. Rosen and Joseph D. Rutledge, HSS, a high-speed simulator, IEEE Transactions on Computer-Aided Design 6(4), 601 to 617, 1987, the simulation of the cycle-free logic between latches as compiled code, once per clock
  3. G. F. Pfister, The Yorktown Simulation Engine, introduction, Proceedings of the 19th Design Automation Conference, 51 to 54, 1982, a hardware engine that evaluates the whole logic of a synchronous design once per machine cycle from a fixed program

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
  • History with a source
  • a scene preset for the example