---
title: Gate simulation lab
heading: Evaluating netlists, finding the critical path and catching glitches, in Python
eyebrow: C7 · Lesson 24 · Gate simulation lab
xp: 50
---

::: hook
A logic simulator is a program that knows only two things about a circuit: what each gate computes and when its output changes. From that it finds every output, the slowest path through the logic, and the glitches lessons 16 to 20 described. In this lab you'll write one: a netlist as a Python dictionary, an evaluator, a depth and timing analysis, an event-driven simulator that reproduces the hazard glitch of $AB + \bar AC$, and a generator for ripple-carry adders that the evaluator then checks against ordinary addition.

::: play
- The circuit is the hazard of lesson 19: $f = AB + \bar AC$ with B = C = 1. Step A from 1 to 0 and watch the waveforms.
- f should stay 1, but $\bar A$ arrives one gate delay late, and f dips to 0 briefly.
- The consensus term BC, added as g, holds the output steady. Step 5 of the lab reproduces the dip in software.
:::
:::

```sim logic
input A, B, C
output f, g
set B = 1
set C = 1
assign NA = ~A
assign T1 = A & B
assign T2 = NA & C
assign T3 = B & C
assign f = T1 | T2
assign g = T1 | T2 | T3
stim A 1@0 0@10
wave: A, NA, T1, T2, f, g
time: 24
```

::: predict
## A netlist has inputs at depth 0, and each gate's depth is one more than its deepest input. A 4-bit ripple-carry adder built from two-input gates has its carry pass through two gates per bit. About how deep is its carry-out?

- [ ] 2
- [ ] 4
- [x] About 9: a gate or two to start, then two per bit
- [ ] 16

::: reveal
About 9. The first carry takes the generate and propagate gates, and every later bit adds two more levels as the carry passes its AND and OR. Depth grows linearly with the width, which is the whole problem lookahead adders solve. The evaluator in step 2 measures it exactly.
:::
:::

::: nameit
## A netlist in Python

A dictionary maps each gate's output name to an operation and a list of input names: `{'t1': ('and', ['A', 'B']), 'f': ('or', ['t1', 't2'])}`. Inputs are names that no gate drives. Evaluating a node means evaluating its inputs first, a recursive walk with memoization, which is a topological order in disguise.

## Depth and timing

A node's **depth** is one more than its deepest input's; inputs have depth 0. With a delay for each kind of gate, the **arrival time** of a node is its gate's delay plus the latest arrival among its inputs, and the largest arrival over the outputs is the **critical path** delay, the limit on the clock.

## Event-driven simulation

Instead of evaluating everything at every instant, an event-driven simulator keeps a queue of (time, node, value) changes. When a node changes, every gate it feeds is re-evaluated and, if its output would change, a new event is scheduled one gate delay later. Only activity costs time, and the order of events reproduces glitches: a gate whose two inputs change at different times briefly sees an inconsistent pair.
:::

::: example
## Evaluate $f = AB + \bar AC$ as a netlist for A = 0, B = 1, C = 1, and find its depth.

::: solution
1. **Write the netlist.** `na = not A`, `t1 = and(A, B)`, `t2 = and(na, C)`, `f = or(t1, t2)`.
2. **Evaluate.** With A = 0: na = 1, t1 = 0, t2 = 1, so f = 1.
3. **Find the depths.** na and t1 are 1, t2 is 2 (it waits for na), and f is 3.
4. **Where the glitch comes from.** The inverter makes one path longer than the other, which is exactly where the glitch comes from.

**Answer:** f = 1, and the netlist is 3 levels deep.
:::
:::

::: example
## With 1 unit of delay per gate, B = C = 1, and A falling from 1 to 0 at time 0, trace the events.

::: solution
1. **At t = 0.** A falls.
2. **At t = 1.** t1 falls (A is now 0) and na rises.
3. **At t = 2.** f is re-evaluated after t1's fall: t2 hasn't risen yet, so f falls to 0; and t2 rises after na.
4. **At t = 3.** f is re-evaluated after t2's rise and returns to 1.
5. **Read the waveform.** The output is 1, then 0 from t = 2 to 3, then 1: a one-unit glitch, from a function that never changes value.

**Answer:** f drops to 0 at t = 2 and returns to 1 at t = 3, a one-unit glitch.
:::
:::

::: example
## Build a 4-bit ripple-carry adder netlist from two-input gates and check it against Python's `+` for all 256 input pairs.

::: solution
1. **One bit's gates.** Each bit uses $p = a \oplus b$, $s = p \oplus c$ and $c' = ab + pc$: two XORs, two ANDs and an OR.
2. **Generate the netlist.** The generator names the nets by bit (`p0`, `c1`, ...) and chains the carries.
3. **Check every pair.** The evaluator computes the sum bits for every pair of 4-bit numbers, and all 256 sums match.
4. **Find the depth.** The carry-out's depth comes to 9, two levels per bit after the first.

**Answer:** all 256 sums match Python's `+`, and the carry-out is 9 levels deep.
:::
:::

::: check
kind: python

## Step 1. Write `evaluate(gates, inputs)` returning a dictionary with the value of every node: inputs from the `inputs` dictionary, gates from their operation ('and', 'or', 'xor', 'not', 'nand', 'nor') applied to their inputs.

```python starter
def evaluate(gates, inputs):
    return dict(inputs)

g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
print(evaluate(g, {'A': 0, 'B': 1, 'C': 1}))
```

```python solution
from functools import reduce

OPS = {
    'and': lambda v: int(all(v)), 'or': lambda v: int(any(v)),
    'xor': lambda v: reduce(lambda a, b: a ^ b, v), 'not': lambda v: 1 - v[0],
    'nand': lambda v: 1 - int(all(v)), 'nor': lambda v: 1 - int(any(v)),
}

def evaluate(gates, inputs):
    val = dict(inputs)
    def get(n):
        if n not in val:
            op, ins = gates[n]
            val[n] = OPS[op]([get(i) for i in ins])
        return val[n]
    for n in gates:
        get(n)
    return val

g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
print(evaluate(g, {'A': 0, 'B': 1, 'C': 1}))
```

```python tests
g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
for v in range(8):
    A, B, C = (v >> 2) & 1, (v >> 1) & 1, v & 1
    assert evaluate(g, {'A': A, 'B': B, 'C': C})['f'] == ((A & B) | ((1 - A) & C)), f"Wrong f for {A}{B}{C}"
assert evaluate({'y': ('nand', ['a', 'b'])}, {'a': 1, 'b': 1})['y'] == 0, "NAND of 1 and 1 is 0."
```

::: right
Right. Memoized recursion visits each gate once, in an order that respects every dependency.
:::
:::

::: check
kind: python

## Step 2. Write `depth(gates)` returning a dictionary of every gate's depth (inputs are 0, each gate one more than its deepest input).

```python starter
def depth(gates):
    return {n: 1 for n in gates}

g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
print(depth(g))
```

```python solution
def depth(gates):
    d = {}
    def get(n):
        if n not in gates:
            return 0
        if n not in d:
            d[n] = 1 + max(get(i) for i in gates[n][1])
        return d[n]
    for n in gates:
        get(n)
    return d

g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
print(depth(g))
```

```python tests
g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
assert depth(g) == {'na': 1, 't1': 1, 't2': 2, 'f': 3}, f"Expected depths 1, 1, 2, 3; got {depth(g)}"
```

::: right
Right. The same recursion as evaluation, with max in place of the gate's function.
:::
:::

::: check
kind: python

## Step 3. Write `critical_path(gates, delay)` returning the latest arrival time over all gates, where `delay` maps each operation to its delay and inputs arrive at time 0.

```python starter
def critical_path(gates, delay):
    return max(delay[op] for op, ins in gates.values())

g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
print(critical_path(g, {'not': 10, 'and': 20, 'or': 25}))
```

```python solution
def critical_path(gates, delay):
    t = {}
    def get(n):
        if n not in gates:
            return 0
        if n not in t:
            op, ins = gates[n]
            t[n] = delay[op] + max(get(i) for i in ins)
        return t[n]
    return max(get(n) for n in gates)

g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
print(critical_path(g, {'not': 10, 'and': 20, 'or': 25}))
```

```python tests
g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
assert critical_path(g, {'not': 10, 'and': 20, 'or': 25}) == 55, "not + and + or = 55 ps."
assert critical_path(g, {'not': 1, 'and': 1, 'or': 1}) == 3, "With unit delays, the depth."
```

::: right
Right. Static timing analysis is this, on millions of gates, with delays that depend on the loads.
:::
:::

::: check
kind: python

## Step 4. Write `simulate(gates, inputs, changes, t_end)`: an event-driven simulator with one unit of delay per gate. Start from the settled values for `inputs`, apply the input changes in `changes` (a list of (time, node, value)), and return the waveform of every node as a dictionary of lists of (time, value), starting with its value at time 0. Your `evaluate` from step 1 is available.

```python starter
from functools import reduce
OPS = {'and': lambda v: int(all(v)), 'or': lambda v: int(any(v)), 'xor': lambda v: reduce(lambda a, b: a ^ b, v), 'not': lambda v: 1 - v[0], 'nand': lambda v: 1 - int(all(v)), 'nor': lambda v: 1 - int(any(v))}

def evaluate(gates, inputs):
    val = dict(inputs)
    def get(n):
        if n not in val:
            op, ins = gates[n]
            val[n] = OPS[op]([get(i) for i in ins])
        return val[n]
    for n in gates:
        get(n)
    return val

def simulate(gates, inputs, changes, t_end):
    final = dict(inputs)
    for t, n, v in changes:
        final[n] = v
    end = evaluate(gates, final)
    return {n: [(0, v)] for n, v in end.items()}

g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
print(simulate(g, {'A': 1, 'B': 1, 'C': 1}, [(0, 'A', 0)], 10)['f'])
```

```python solution
from functools import reduce
OPS = {'and': lambda v: int(all(v)), 'or': lambda v: int(any(v)), 'xor': lambda v: reduce(lambda a, b: a ^ b, v), 'not': lambda v: 1 - v[0], 'nand': lambda v: 1 - int(all(v)), 'nor': lambda v: 1 - int(any(v))}

def evaluate(gates, inputs):
    val = dict(inputs)
    def get(n):
        if n not in val:
            op, ins = gates[n]
            val[n] = OPS[op]([get(i) for i in ins])
        return val[n]
    for n in gates:
        get(n)
    return val

def simulate(gates, inputs, changes, t_end):
    val = evaluate(gates, inputs)
    wave = {n: [(0, v)] for n, v in val.items()}
    fanout = {}
    for g, (op, ins) in gates.items():
        for i in ins:
            fanout.setdefault(i, []).append(g)
    events = {}
    for t, n, v in changes:
        events.setdefault(t, []).append((n, v))
    for t in range(0, t_end + 1):
        changed = []
        for n, v in events.pop(t, []):
            if val[n] != v:
                val[n] = v
                changed.append(n)
                if wave[n][-1][0] == t:
                    wave[n][-1] = (t, v)
                else:
                    wave[n].append((t, v))
        for n in changed:
            for g in fanout.get(n, []):
                op, ins = gates[g]
                events.setdefault(t + 1, []).append((g, OPS[op]([val[i] for i in ins])))
    return wave

g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
print(simulate(g, {'A': 1, 'B': 1, 'C': 1}, [(0, 'A', 0)], 10)['f'])
```

```python tests
g = {'na': ('not', ['A']), 't1': ('and', ['A', 'B']), 't2': ('and', ['na', 'C']), 'f': ('or', ['t1', 't2'])}
w = simulate(g, {'A': 1, 'B': 1, 'C': 1}, [(0, 'A', 0)], 10)
assert w['f'] == [(0, 1), (2, 0), (3, 1)], f"f should glitch low from t = 2 to 3; got {w['f']}"
g2 = dict(g); g2['t3'] = ('and', ['B', 'C']); g2['f'] = ('or', ['t1', 't2', 't3'])
w2 = simulate(g2, {'A': 1, 'B': 1, 'C': 1}, [(0, 'A', 0)], 10)
assert w2['f'] == [(0, 1)], "With the consensus term, f never moves."
```

::: right
Right. The glitch appears because the two paths into the OR have different depths.
:::
:::

::: check
kind: python

## Step 5. Write `ripple_adder(n)` returning a netlist for an n-bit ripple-carry adder with inputs a0 to a(n−1), b0 to b(n−1) and cin, sum outputs s0 to s(n−1) and carry out `cout`. Each bit: p = a ⊕ b, s = p ⊕ c, carry = ab + pc. Your `evaluate` and `depth` are available.

```python starter
from functools import reduce
OPS = {'and': lambda v: int(all(v)), 'or': lambda v: int(any(v)), 'xor': lambda v: reduce(lambda a, b: a ^ b, v), 'not': lambda v: 1 - v[0], 'nand': lambda v: 1 - int(all(v)), 'nor': lambda v: 1 - int(any(v))}

def evaluate(gates, inputs):
    val = dict(inputs)
    def get(n):
        if n not in val:
            op, ins = gates[n]
            val[n] = OPS[op]([get(i) for i in ins])
        return val[n]
    for n in gates:
        get(n)
    return val

def depth(gates):
    d = {}
    def get(n):
        if n not in gates:
            return 0
        if n not in d:
            d[n] = 1 + max(get(i) for i in gates[n][1])
        return d[n]
    for n in gates:
        get(n)
    return d

def ripple_adder(n):
    g = {}
    for i in range(n):
        g[f's{i}'] = ('xor', [f'a{i}', f'b{i}'])
    g['cout'] = ('and', [f'a{n - 1}', f'b{n - 1}'])
    return g

print(len(ripple_adder(4)))
```

```python solution
from functools import reduce
OPS = {'and': lambda v: int(all(v)), 'or': lambda v: int(any(v)), 'xor': lambda v: reduce(lambda a, b: a ^ b, v), 'not': lambda v: 1 - v[0], 'nand': lambda v: 1 - int(all(v)), 'nor': lambda v: 1 - int(any(v))}

def evaluate(gates, inputs):
    val = dict(inputs)
    def get(n):
        if n not in val:
            op, ins = gates[n]
            val[n] = OPS[op]([get(i) for i in ins])
        return val[n]
    for n in gates:
        get(n)
    return val

def depth(gates):
    d = {}
    def get(n):
        if n not in gates:
            return 0
        if n not in d:
            d[n] = 1 + max(get(i) for i in gates[n][1])
        return d[n]
    for n in gates:
        get(n)
    return d

def ripple_adder(n):
    g = {}
    c = 'cin'
    for i in range(n):
        g[f'p{i}'] = ('xor', [f'a{i}', f'b{i}'])
        g[f's{i}'] = ('xor', [f'p{i}', c])
        g[f'g{i}'] = ('and', [f'a{i}', f'b{i}'])
        g[f'q{i}'] = ('and', [f'p{i}', c])
        nxt = 'cout' if i == n - 1 else f'c{i + 1}'
        g[nxt] = ('or', [f'g{i}', f'q{i}'])
        c = nxt
    return g

print(len(ripple_adder(4)))
```

```python tests
g = ripple_adder(4)
for a in range(16):
    for b in range(16):
        ins = {f'a{i}': (a >> i) & 1 for i in range(4)}
        ins.update({f'b{i}': (b >> i) & 1 for i in range(4)})
        ins['cin'] = 0
        v = evaluate(g, ins)
        total = sum(v[f's{i}'] << i for i in range(4)) + (v['cout'] << 4)
        assert total == a + b, f"{a} + {b} gave {total}"
assert depth(g)['cout'] == 9, f"The carry-out is 9 levels deep; got {depth(g)['cout']}"
```

::: right
Right. Generating the netlist and checking it exhaustively is how hardware generators are tested.
:::
:::

::: check
given: n = 4 | 8 | 16 | 32
answer: 2*n + 1
tolerance: 0

## In the generated ripple adder, how many gate levels deep is the carry-out of an {n}-bit adder?

::: right
Right: {answer}. Two levels per bit, plus the first bit's propagate gate.
:::

::: misses
- [2*n] The first carry also waits for its propagate XOR.
- [any] Two levels per bit, plus one.
:::
:::

::: explain
## Why does an event-driven simulator reproduce glitches that a simple evaluator misses?

::: model
A simple evaluator computes each node's final value from its inputs' final values, so it only ever sees the settled state; a temporary disagreement between two paths never appears. An event-driven simulator advances in time, changing each gate's output one delay after its inputs change. When two signals feeding the same gate travel through paths of different depth, the gate sees the first change before the second, computes an output from that inconsistent pair, and schedules it. That brief wrong output is exactly the glitch a real circuit produces, with the same timing.
:::
:::

::: practice

::: check
given: n = 6 | 12 | 64
answer: 2*n + 1
tolerance: 0

## Carry-out depth of an {n}-bit ripple adder from two-input gates?

::: misses
- [any] $2n + 1$.
:::
:::
:::
