---
title: State machine lab
heading: Running, building, minimizing and comparing state machines, in Python
eyebrow: C7 · Lesson 42 · State machine lab
xp: 50
---

::: hook
Lessons 37 to 41 drew state machines as diagrams and tables. A table is data, and data is what programs handle well. In this lab you'll store a machine as two lists, a transition table and an output table, then write the tools a designer leans on: a simulator, a generator that builds any sequence detector from its pattern, a minimizer that merges states that can't be told apart, a reachability check that finds dead states, and an equivalence checker that proves two machines behave identically on every input.

::: play
- The circuit is the 101 detector of lesson 39, running on a stream of bits. Its output rises one clock after each completed 101, overlaps included.
- The lab's `detector('101')` builds the same machine from the pattern alone.
- Step 5's equivalence checker can prove that the hand-built machine and the generated one agree on every possible input.
:::
:::

```sim logic
input X
output Z
clock CLK 10
always @(posedge CLK) begin
  Q1 <= Q0 & ~X | Q1 & ~Q0 & X;
  Q0 <= X;
end
assign Z = Q1 & Q0
stim X 0@0 1@10 0@20 1@30 1@40 0@50 1@60 0@70
wave: CLK, X, Q1, Q0, Z
time: 90
```

::: predict
## A sequence detector for a 6-bit pattern is built as a Moore machine with one state per matched prefix. How many states does it have?

- [ ] 6
- [x] 7
- [ ] 64
- [ ] 12

::: reveal
Seven: one for each prefix length from 0 to 6, the last one with output 1. The trick is in the transitions: on a mismatch the machine doesn't fall back to the start but to the longest prefix of the pattern that's still a suffix of what it has seen, which is what lets it find overlapping matches.
:::
:::

::: nameit
## Machines as tables

States are numbered 0 to n − 1, inputs are bits, `trans[s][b]` is the next state and `out[s]` the Moore output. A list of lists is a complete description.

## Building a detector

State i means "the last i bits match the first i bits of the pattern". On input b, the next state is the length of the longest prefix of the pattern that's a suffix of the first i bits followed by b. Checking candidate lengths from the longest down finds it; the full-match state has output 1 and continues the same way, so overlapping matches are found.

## Minimizing

Two states are **equivalent** if no input sequence can tell them apart by the outputs. Partition refinement finds them: start with the states grouped by output; split any group whose members go, on some input, to different groups; repeat until nothing splits. Each final group becomes one state.

## Reachability and equivalence

A state that can't be reached from the start is dead logic: a search from the start state finds the live ones. Two machines are equivalent if, run side by side on every input sequence, they always produce the same output. A search over pairs of states (one from each machine) starting from the two start states finds any reachable pair with different outputs, or proves there is none.
:::

::: example
## Build the 101 detector's table from its pattern.

::: solution
1. **State 0.** On 1 it goes to 1 ("1" matched); on 0 it stays at 0.
2. **State 1.** On 0 it goes to 2 ("10"); on 1 it stays at 1 (the new 1 is itself a prefix).
3. **State 2.** On 1 it goes to 3 ("101", output 1); on 0 back to 0 ("100" ends in no prefix).
4. **State 3.** On 0 it goes to 2 ("1010" ends in "10"); on 1 to 1.
5. **Write the table.** The table [[0, 1], [2, 1], [0, 3], [2, 1]] with outputs [0, 0, 0, 1] is exactly lesson 39's machine.

**Answer:** the next-state table [[0, 1], [2, 1], [0, 3], [2, 1]] with outputs [0, 0, 0, 1].
:::
:::

::: example
## Run the detector on 0101101. Where does it flag a match?

::: solution
1. **Step through the bits.** After each bit, the state and the output are:

| Bit | 0 | 1 | 0 | 1 | 1 | 0 | 1 |
|---|---|---|---|---|---|---|---|
| State | 0 | 1 | 2 | 3 | 1 | 2 | 3 |
| Output | 0 | 0 | 0 | 1 | 0 | 0 | 1 |

2. **Find the matches.** The stream holds 101 at bits 2 to 4 and again at bits 5 to 7, and the detector flags both, at the fourth and seventh bits.

**Answer:** at the fourth and seventh bits.
:::
:::

::: example
## A designer adds a fifth state that behaves exactly like state 2, and points state 1's 0-transition at it. Does the minimizer notice?

::: solution
1. **Compare states 2 and 4.** Both output 0, and both go to 0 on 0 and to 3 on 1.
2. **Minimize.** Partition refinement never splits them, so the minimized machine has 4 states, the same as the original.
3. **Confirm.** The equivalence checker confirms that the five-state and four-state machines produce identical outputs for every input.
4. **Why it matters.** Redundant states like this are common in hand designs and cost flip-flops and logic for nothing.

**Answer:** yes: states 2 and 4 merge, and the minimized machine has the original 4 states.
:::
:::

::: check
kind: python

## Step 1. Write `run_moore(trans, out, start, bits)` returning the list of outputs after each input bit.

```python starter
def run_moore(trans, out, start, bits):
    return [0] * len(bits)

print(run_moore([[0, 1], [2, 1], [0, 3], [2, 1]], [0, 0, 0, 1], 0, [0, 1, 0, 1, 1, 0, 1]))
```

```python solution
def run_moore(trans, out, start, bits):
    s, res = start, []
    for b in bits:
        s = trans[s][b]
        res.append(out[s])
    return res
print(run_moore([[0, 1], [2, 1], [0, 3], [2, 1]], [0, 0, 0, 1], 0, [0, 1, 0, 1, 1, 0, 1]))
```

```python tests
t, o = [[0, 1], [2, 1], [0, 3], [2, 1]], [0, 0, 0, 1]
assert run_moore(t, o, 0, [0, 1, 0, 1, 1, 0, 1]) == [0, 0, 0, 1, 0, 0, 1], "Matches at the fourth and seventh bits."
assert run_moore(t, o, 0, [1, 0, 1, 0, 1]) == [0, 0, 1, 0, 1], "Overlapping: 10101 holds two."
```

::: right
Right. A simulator for any Moore machine in four lines.
:::
:::

::: check
kind: python

## Step 2. Write `detector(pattern)` returning `(trans, out)` for a Moore machine that detects the bit string `pattern` (such as '101'), overlaps allowed.

```python starter
def detector(pattern):
    L = len(pattern)
    trans = [[0, min(i + 1, L)] for i in range(L + 1)]
    return trans, [0] * L + [1]

print(detector('101'))
```

```python solution
def detector(pattern):
    p = [int(c) for c in pattern]
    L = len(p)
    trans = []
    for i in range(L + 1):
        row = []
        for b in (0, 1):
            seq = p[:i] + [b] if i < L else p + [b]
            k = min(len(seq), L)
            while k > 0 and seq[len(seq) - k:] != p[:k]:
                k -= 1
            row.append(k)
        trans.append(row)
    out = [0] * L + [1]
    return trans, out
print(detector('101'))
```

```python tests
assert detector('101') == ([[0, 1], [2, 1], [0, 3], [2, 1]], [0, 0, 0, 1]), "The 101 detector of lesson 39."
assert detector('1011')[0] == [[0, 1], [2, 1], [0, 3], [2, 4], [2, 1]], "The 1011 detector."
import random
random.seed(3)
bits = [random.randint(0, 1) for _ in range(300)]
t, o = detector('0110')
s, hits = 0, []
for i, b in enumerate(bits):
    s = t[s][b]
    if o[s]:
        hits.append(i)
assert hits == [i for i in range(3, 300) if bits[i - 3:i + 1] == [0, 1, 1, 0]], "It must find every occurrence, overlaps included."
```

::: right
Right. Falling back to the longest prefix that's still a suffix is what makes overlapping matches work.
:::
:::

::: check
kind: python

## Step 3. Write `minimize(trans, out)` returning the number of states after merging equivalent ones, by partition refinement.

```python starter
def minimize(trans, out):
    return len(trans)

t = [[0, 1], [4, 1], [0, 3], [2, 1], [0, 3]]
print(minimize(t, [0, 0, 0, 1, 0]))
```

```python solution
def minimize(trans, out):
    n = len(trans)
    cls = list(out)
    while True:
        sig = [(cls[s], cls[trans[s][0]], cls[trans[s][1]]) for s in range(n)]
        ids = {}
        new = [ids.setdefault(x, len(ids)) for x in sig]
        if len(set(new)) == len(set(cls)):
            return len(set(new))
        cls = new
t = [[0, 1], [4, 1], [0, 3], [2, 1], [0, 3]]
print(minimize(t, [0, 0, 0, 1, 0]))
```

```python tests
assert minimize([[0, 1], [4, 1], [0, 3], [2, 1], [0, 3]], [0, 0, 0, 1, 0]) == 4, "The duplicate of state 2 merges."
assert minimize([[0, 1], [2, 1], [0, 3], [2, 1]], [0, 0, 0, 1]) == 4, "The detector is already minimal."
assert minimize([[1, 1], [0, 0]], [0, 0]) == 1, "Two states with the same output and nowhere different to go are one."
```

::: right
Right. Refinement stops when a round splits nothing; the groups are then the minimal states.
:::
:::

::: check
kind: python

## Step 4. Write `reachable(trans, start)` returning the set of states reachable from `start`.

```python starter
def reachable(trans, start):
    return set(range(len(trans)))

print(reachable([[0, 1], [0, 1], [2, 2]], 0))
```

```python solution
def reachable(trans, start):
    seen, stack = {start}, [start]
    while stack:
        s = stack.pop()
        for t in trans[s]:
            if t not in seen:
                seen.add(t); stack.append(t)
    return seen
print(reachable([[0, 1], [0, 1], [2, 2]], 0))
```

```python tests
assert reachable([[0, 1], [0, 1], [2, 2]], 0) == {0, 1}, "State 2 can't be reached."
assert reachable([[0, 1], [2, 1], [0, 3], [2, 1]], 0) == {0, 1, 2, 3}, "Every detector state is live."
```

::: right
Right. A depth-first search over the transition graph.
:::
:::

::: check
kind: python

## Step 5. Write `equivalent(m1, m2)` where each machine is `(trans, out, start)`, returning True if the two produce the same output sequence for every input sequence.

```python starter
def equivalent(m1, m2):
    return len(m1[0]) == len(m2[0])

d = ([[0, 1], [2, 1], [0, 3], [2, 1]], [0, 0, 0, 1], 0)
r = ([[0, 1], [4, 1], [0, 3], [2, 1], [0, 3]], [0, 0, 0, 1, 0], 0)
print(equivalent(d, r))
```

```python solution
def equivalent(m1, m2):
    (t1, o1, s1), (t2, o2, s2) = m1, m2
    seen, stack = {(s1, s2)}, [(s1, s2)]
    while stack:
        a, b = stack.pop()
        if o1[a] != o2[b]:
            return False
        for x in (0, 1):
            nxt = (t1[a][x], t2[b][x])
            if nxt not in seen:
                seen.add(nxt); stack.append(nxt)
    return True
d = ([[0, 1], [2, 1], [0, 3], [2, 1]], [0, 0, 0, 1], 0)
r = ([[0, 1], [4, 1], [0, 3], [2, 1], [0, 3]], [0, 0, 0, 1, 0], 0)
print(equivalent(d, r))
```

```python tests
d = ([[0, 1], [2, 1], [0, 3], [2, 1]], [0, 0, 0, 1], 0)
r = ([[0, 1], [4, 1], [0, 3], [2, 1], [0, 3]], [0, 0, 0, 1, 0], 0)
assert equivalent(d, r), "Different sizes, same behavior."
e = ([[0, 1], [2, 1], [0, 3], [2, 4], [2, 1]], [0, 0, 0, 0, 1], 0)
assert not equivalent(d, e), "The 101 and 1011 detectors differ."
```

::: right
Right. Exploring pairs of states proves equivalence for all input sequences, infinitely many, in a finite search.
:::
:::

::: check
given: L = 3 | 5 | 8 | 12
answer: L + 1
tolerance: 0

## How many states does the generated Moore detector have for an {L}-bit pattern?

::: right
Right: one per prefix length, {answer}.
:::

::: misses
- [L] Count the empty prefix too.
- [2^L] It only remembers how much of the pattern has matched.
- [any] Prefix lengths 0 to L.
:::
:::

::: explain
## How can a finite search prove that two state machines agree on infinitely many input sequences?

::: model
Whatever input sequence the two machines receive, at each moment the pair is in some combination of one state from each. There are only finitely many such pairs, so a search that starts from the two start states and follows every input from every pair it reaches will visit every pair that any input sequence could ever produce. If none of those pairs has different outputs, no input sequence can make the machines disagree, because any disagreement would have to happen in one of those reachable pairs. The infinite set of sequences collapses onto a finite set of reachable state pairs.
:::
:::

::: practice

::: check
given: L = 4 | 7 | 10
answer: ceil(log(L + 1)/log(2))
tolerance: 0

## Flip-flops for a binary-encoded Moore detector of an {L}-bit pattern?

::: misses
- [any] $\lceil\log_2(L + 1)\rceil$.
:::
:::
:::
