---
title: "Coding lab: Hamming codes and Viterbi decoding"
heading: A Hamming (7,4) encoder and syndrome decoder, its block error rate by simulation, a Viterbi decoder for the rate-1/2 K = 3 code, and free distances found by searching the trellis
eyebrow: S8 · Lesson 41 · Coding lab
xp: 60
---

::: hook
Lessons 34 to 37 described codes by their distances and their decoders by what they can correct. In this lab you'll build two of them and test those claims exhaustively or statistically: a Hamming code that must correct every single error in every codeword, a Viterbi decoder that must undo scattered errors in a convolutional codeword, and a search that finds the free distance of any small convolutional code, the number that sets its coding gain.
:::

::: play
- The curves are the block error probability of 4 data bits over a binary symmetric channel with crossover p: sent raw, $1 - (1 - p)^4$, and Hamming (7,4)-coded, $1 - (1 - p)^7 - 7p(1 - p)^6$.
- At the same crossover probability the code wins for every p below one half. A fair comparison also charges it for its extra bits: at equal energy per data bit, each coded bit gets only 4/7 of the energy and flips more often.
- At p = 10⁻³ it cuts the block error rate from 4.0 × 10⁻³ to 2.1 × 10⁻⁵.
:::

```sim plot
view: graph
x: p = 0.0001..0.3 log
y: P = 1e-8..1 log
plot: 1 - (1 - p)^4 | label: uncoded, 4 bits
plot: 1 - (1 - p)^7 - 7*p*(1 - p)^6 | label: Hamming (7,4)
```

::: predict
## The rate-1/2, K = 3 convolutional code (generators 7 and 5 in octal) has free distance 5. How many channel errors can a hard-decision Viterbi decoder always correct, if they're spread far enough apart?

- [ ] 1
- [x] 2 within any stretch the size of an error event
- [ ] 5
- [ ] Any number, given enough time

::: reveal
A code of distance d corrects $\lfloor(d - 1)/2\rfloor$ errors, so 2 for d = 5. For a convolutional code that holds per error event: two errors close together are corrected, three close together may not be, but errors spread over the codeword are each repaired locally, so a long message can survive many errors in total.
:::
:::

::: nameit
## What the lab computes

- **Hamming (7,4)**: data $d_1 \ldots d_4$ and parity $p_1 = d_1 + d_2 + d_4$, $p_2 = d_1 + d_3 + d_4$, $p_3 = d_2 + d_3 + d_4$ (mod 2), sent as $d_1d_2d_3d_4p_1p_2p_3$. The syndrome of a received word matches the column of the parity-check matrix at the position of a single error.
- **Block error rate** on a binary symmetric channel: the code fails when two or more of the seven bits flip.
- **Convolutional encoding** with constraint length K and generators $g_i$ (octal): shift each input bit into a K-bit register, newest bit highest, and send the parity of the register ANDed with each generator. Two zeros flush the K = 3 encoder back to state 0.
- **Viterbi decoding**: for each state, keep the path with the smallest Hamming distance to the received bits; at the end, take the survivor in state 0.
- **Free distance**: the smallest output weight of a path that leaves state 0 and returns to it, found by a shortest-path search over the trellis with output weights as edge lengths.
:::

::: check
kind: python

## Write `ham_encode(d)` for a list of 4 bits, returning 7 bits in the order $d_1d_2d_3d_4p_1p_2p_3$, and `ham_decode(r)`, which corrects any single error by its syndrome and returns the 4 data bits.

```python starter
def ham_encode(d):
    return list(d) + [0, 0, 0]

def ham_decode(r):
    return list(r[:4])
```

```python solution
H = [[1, 1, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1]]

def ham_encode(d):
    d1, d2, d3, d4 = d
    return [d1, d2, d3, d4, (d1 + d2 + d4) % 2, (d1 + d3 + d4) % 2, (d2 + d3 + d4) % 2]

def ham_decode(r):
    r = list(r)
    s = [sum(H[i][j] * r[j] for j in range(7)) % 2 for i in range(3)]
    if any(s):
        for j in range(7):
            if [H[i][j] for i in range(3)] == s:
                r[j] ^= 1
                break
    return r[:4]
```

```python tests
import itertools
assert ham_encode([1, 0, 1, 1]) == [1, 0, 1, 1, 0, 1, 0], "1011 encodes to 1011010."
for d in itertools.product([0, 1], repeat=4):
    c = ham_encode(list(d))
    for j in range(-1, 7):
        r = [b ^ (k == j) for k, b in enumerate(c)]
        assert ham_decode(r) == list(d), f"Every single error must be corrected (data {d}, error at {j})."
```

::: right
Right. The syndrome's three bits name one of seven positions or none, which is exactly why a three-parity-bit code can protect seven bits and no more: it's a perfect code.
:::
:::

::: check
kind: python

## Write `ham_block_error(p, nblocks, seed)`: send nblocks random 4-bit messages through your Hamming code and a binary symmetric channel with crossover p (`random.Random(seed)`), and return the fraction decoded wrongly.

```python starter
def ham_block_error(p, nblocks, seed):
    return 0.0
```

```python solution
import random
H = [[1, 1, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1]]

def ham_encode(d):
    d1, d2, d3, d4 = d
    return [d1, d2, d3, d4, (d1 + d2 + d4) % 2, (d1 + d3 + d4) % 2, (d2 + d3 + d4) % 2]

def ham_decode(r):
    r = list(r)
    s = [sum(H[i][j] * r[j] for j in range(7)) % 2 for i in range(3)]
    if any(s):
        for j in range(7):
            if [H[i][j] for i in range(3)] == s:
                r[j] ^= 1
                break
    return r[:4]

def ham_block_error(p, nblocks, seed):
    r = random.Random(seed)
    e = 0
    for _ in range(nblocks):
        d = [r.randint(0, 1) for _ in range(4)]
        c = [b ^ (r.random() < p) for b in ham_encode(d)]
        e += ham_decode(c) != d
    return e / nblocks
```

```python tests
import math
for p in (0.02, 0.05):
    P = 1 - (1 - p) ** 7 - 7 * p * (1 - p) ** 6
    assert abs(ham_block_error(p, 40000, 6) - P) < 4 * math.sqrt(P / 40000), f"At p = {p}, about {P:.2e}."
```

::: right
Right. Every pattern of two or more errors defeats the decoder (it "corrects" the wrong bit), so the block error rate is exactly the probability of two or more flips.
:::
:::

::: check
kind: python

## Write `conv_encode(bits)` for the rate-1/2, K = 3 code with generators 7 and 5 (octal), appending two flushing zeros, and `viterbi(r)`, a hard-decision decoder that returns the message bits (without the flush).

```python starter
def conv_encode(bits):
    return [b for b in bits for _ in range(2)] + [0, 0, 0, 0]

def viterbi(r):
    return r[0:len(r) // 2 - 2:1]
```

```python solution
G = (0b111, 0b101)

def conv_encode(bits):
    s, out = 0, []
    for b in list(bits) + [0, 0]:
        reg = (b << 2) | s
        out += [bin(reg & g).count('1') % 2 for g in G]
        s = reg >> 1
    return out

def viterbi(r):
    INF = 10 ** 9
    pm, paths = [0, INF, INF, INF], [[], [], [], []]
    for t in range(len(r) // 2):
        seg = r[2 * t:2 * t + 2]
        npm, npaths = [INF] * 4, [None] * 4
        for s in range(4):
            if pm[s] >= INF:
                continue
            for b in (0, 1):
                reg = (b << 2) | s
                out = [bin(reg & g).count('1') % 2 for g in G]
                m = pm[s] + (out[0] != seg[0]) + (out[1] != seg[1])
                if m < npm[reg >> 1]:
                    npm[reg >> 1], npaths[reg >> 1] = m, paths[s] + [b]
        pm, paths = npm, npaths
    return paths[0][:len(r) // 2 - 2]
```

```python tests
import random
assert conv_encode([1]) == [1, 1, 1, 0, 1, 1], "A single 1 gives 11 10 11: weight 5."
r = random.Random(2)
msg = [r.randint(0, 1) for _ in range(60)]
c = conv_encode(msg)
assert viterbi(c) == msg, "No errors: the message comes back."
for pos in ((5, 40, 90), (10, 11), (0, 70)):
    e = list(c)
    for p in pos:
        e[p] ^= 1
    assert viterbi(e) == msg, f"Errors at {pos} must be corrected."
```

::: right
Right. Two adjacent errors are corrected because the code's distance is 5; scattered errors are corrected one event at a time, however many there are in total.
:::
:::

::: check
kind: python

## Write `free_distance(g, K)`: the free distance of a rate-1/n convolutional code with generators g (a tuple of integers) and constraint length K, by a shortest-path search from the first step out of state 0 back to state 0.

```python starter
def free_distance(g, K):
    return K
```

```python solution
import heapq

def free_distance(g, K):
    w = lambda reg: sum(bin(reg & gg).count('1') % 2 for gg in g)
    reg = 1 << (K - 1)
    start = reg >> 1
    dist = {start: w(reg)}
    heap = [(w(reg), start)]
    while heap:
        d, s = heapq.heappop(heap)
        if d > dist.get(s, float('inf')):
            continue
        if s == 0:
            return d
        for b in (0, 1):
            reg = (b << (K - 1)) | s
            nd, ns = d + w(reg), reg >> 1
            if nd < dist.get(ns, float('inf')):
                dist[ns] = nd
                heapq.heappush(heap, (nd, ns))
```

```python tests
assert free_distance((0o7, 0o5), 3) == 5, "(7, 5), K = 3: 5."
assert free_distance((0o15, 0o17), 4) == 6, "(15, 17), K = 4: 6."
assert free_distance((0o23, 0o35), 5) == 7, "(23, 35), K = 5: 7."
assert free_distance((0o133, 0o171), 7) == 10, "The NASA standard (133, 171), K = 7: 10."
assert free_distance((0o7, 0o7, 0o5), 3) == 8, "Rate 1/3 (7, 7, 5): 8."
```

::: right
Right. Dijkstra's search works because output weights are never negative, and the first time it pops state 0 it has the lightest path back.
:::
:::

::: explain
## Why does a Viterbi decoder need to keep only one path per state, and what does that make its cost?

::: model
Two paths that reach the same state at the same time have the same future: from that state on, every continuation adds the same output bits to both, and so the same distance to the received sequence. Whichever path is already farther behind can never catch up, so it can be dropped. That leaves one survivor per state at each step, and each step costs a fixed amount of work per state, so decoding is linear in the message length and proportional to the number of states, 2 to the power K − 1. That's why constraint lengths stay around 7 in practice: each extra stage of memory doubles the decoder.
:::
:::
