TExcelTAD
Home › Information Theory › Mini Project: Compress, Transmit, Decode

Mini Project: Compress, Transmit, Decode

This project builds a complete digital communication system from the pieces of the course. A message is compressed with a Huffman code, protected with an error-correcting code, sent through a noisy channel, then decoded and decompressed. At each stage we compare with Shannon's limits: the entropy for compression and the capacity for transmission.

What we are building:

Step Part Course topics
1. The source data entropy, typical messages
2. Compress source coding Huffman codes, canonical codes, Kraft
3. Why compression needs protection channel BSC, error propagation in prefix codes
4. Protect with Hamming channel coding linear codes, syndromes
5. Protect with LDPC channel coding LDPC codes, sum-product decoding
6. The whole system separation source-channel separation, capacity

Note: Each step is a complete program (the playground does not share variables between runs), so the helper functions are repeated where a later step needs them.

Step 1: The source

The source emits letters from a small alphabet with fixed probabilities, independently. Its entropy is the compression limit (Entropy).

python · try it yourself
import numpy as np

alphabet = list("etaoins ")
probs = np.array([0.22, 0.16, 0.13, 0.12, 0.11, 0.1, 0.09, 0.07])
rng = np.random.default_rng(0)
message = "".join(rng.choice(alphabet, size=4000, p=probs))
H = float(-np.sum(probs * np.log2(probs)))
print("first 60 characters:", repr(message[:60]))
print(f"entropy {H:.4f} bits/char; fixed-length code needs {np.log2(len(alphabet)):.0f} bits/char; ASCII uses 8")
print(f"limit for the whole message: about {H * len(message):.0f} bits")
first 60 characters: 'iteensoio neseiesotaeeiioa  iiiaeiotas tototastoenntseteante'
entropy 2.9170 bits/char; fixed-length code needs 3 bits/char; ASCII uses 8
limit for the whole message: about 11668 bits

Step 2: Compress with a canonical Huffman code

Build Huffman lengths from the probabilities, turn them into a canonical code (Huffman Coding in Practice), and encode. Then decode and check that the message comes back exactly.

python · try it yourself
import heapq
import numpy as np

alphabet = list("etaoins ")
probs = np.array([0.22, 0.16, 0.13, 0.12, 0.11, 0.1, 0.09, 0.07])
rng = np.random.default_rng(0)
message = "".join(rng.choice(alphabet, size=4000, p=probs))

def huffman_lengths(p):
    heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
    lengths = [0] * len(p); counter = len(p)
    while len(heap) > 1:
        w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
        for s in s1 + s2: lengths[s] += 1
        heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
    return lengths

def canonical_code(lengths):
    order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
    code, value, prev = {}, 0, lengths[order[0]]
    for i in order:
        value <<= lengths[i] - prev; prev = lengths[i]
        code[i] = format(value, f"0{lengths[i]}b"); value += 1
    return code

lengths = huffman_lengths(probs)
code = {alphabet[i]: w for i, w in canonical_code(lengths).items()}
print("code:", code, " Kraft sum:", sum(2.0 ** -l for l in lengths))
bits = "".join(code[c] for c in message)
inverse = {w: c for c, w in code.items()}
out, cur = [], ""
for b in bits:
    cur += b
    if cur in inverse:
        out.append(inverse[cur]); cur = ""
print(f"compressed: {len(bits)} bits = {len(bits) / len(message):.4f} bits/char  (entropy {-np.sum(probs * np.log2(probs)):.4f})")
print("decompressed correctly:", "".join(out) == message)
code: {'e': '00', 't': '010', 'a': '011', 'o': '100', 'i': '101', 'n': '110', 's': '1110', ' ': '1111'}  Kraft sum: 1.0
compressed: 11740 bits = 2.9350 bits/char  (entropy 2.9170)
decompressed correctly: True

The Huffman code is within a few hundredths of a bit of the entropy per character (Optimal Code Lengths).

Step 3: Why compressed data need protection

Send the compressed bits through a binary symmetric channel with flip probability 0.01 (The Binary Symmetric Channel). A single flipped bit in a prefix code can change the boundaries of the following codewords, so errors spread:

python · try it yourself
import heapq
import numpy as np

alphabet = list("etaoins ")
probs = np.array([0.22, 0.16, 0.13, 0.12, 0.11, 0.1, 0.09, 0.07])
rng = np.random.default_rng(0)
message = "".join(rng.choice(alphabet, size=4000, p=probs))

def huffman_lengths(p):
    heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
    lengths = [0] * len(p); counter = len(p)
    while len(heap) > 1:
        w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
        for s in s1 + s2: lengths[s] += 1
        heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
    return lengths

def canonical_code(lengths):
    order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
    code, value, prev = {}, 0, lengths[order[0]]
    for i in order:
        value <<= lengths[i] - prev; prev = lengths[i]
        code[i] = format(value, f"0{lengths[i]}b"); value += 1
    return code

code = {alphabet[i]: w for i, w in canonical_code(huffman_lengths(probs)).items()}
inverse = {w: c for c, w in code.items()}
bits = np.array([int(b) for b in "".join(code[c] for c in message)])
noisy = bits ^ (rng.random(bits.size) < 0.01)
out, cur = [], ""
for b in noisy:
    cur += str(b)
    if cur in inverse:
        out.append(inverse[cur]); cur = ""
decoded = "".join(out)
wrong = sum(a != b for a, b in zip(decoded, message)) + abs(len(decoded) - len(message))
print(f"flipped bits: {int(np.sum(noisy != bits))} of {bits.size}")
print(f"decoded length {len(decoded)} (sent {len(message)}), wrong characters: {wrong}")
print("sent:    ", repr(message[1000:1040]))
print("received:", repr(decoded[1000:1040]))
flipped bits: 107 of 11740
decoded length 4011 (sent 4000), wrong characters: 3170
sent:     'enaaostteteeoeesee iioesaaeeoooosatttona'
received: 'aeaenaaostteteeoeesee iioesaaeeoooosattt'

Compression removed the redundancy that might have let a reader guess the damaged characters, and the prefix code lost synchronization. Compressed data must be protected with a channel code.

Step 4: Protect with the (7,4) Hamming code

Encode each block of 4 compressed bits into 7 channel bits (The (7,4) Hamming Code) and decode with the syndrome. The rate drops to 47\frac{4}{7}, but single errors per block are corrected:

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
bits = rng.integers(0, 2, 11_740)                    # stands for the compressed message (same length as in Step 2)
bits = np.concatenate([bits, np.zeros((-len(bits)) % 4, dtype=int)])
P = np.array([[1, 0, 1], [1, 1, 0], [1, 1, 1], [0, 1, 1]])
G = np.hstack([np.eye(4, dtype=int), P]); H = np.hstack([P.T, np.eye(3, dtype=int)])
lookup = np.full(8, -1)
for j in range(7):
    lookup[H[:, j] @ [4, 2, 1]] = j

def hamming_transmit(f):
    S = bits.reshape(-1, 4)
    R = (S @ G % 2) ^ (rng.random((len(S), 7)) < f)
    z = (R @ H.T % 2) @ [4, 2, 1]
    rows = np.nonzero(lookup[z] >= 0)[0]
    R[rows, lookup[z][rows]] ^= 1
    return int(np.sum(R[:, :4] != S))

for f in [0.001, 0.01, 0.05]:
    errs = hamming_transmit(f)
    print(f"f = {f}: uncoded errors expected {f * bits.size:7.1f};  after Hamming decoding {errs:4d} bit errors  (rate 4/7)")
f = 0.001: uncoded errors expected    11.7;  after Hamming decoding    0 bit errors  (rate 4/7)
f = 0.01: uncoded errors expected   117.4;  after Hamming decoding   11 bit errors  (rate 4/7)
f = 0.05: uncoded errors expected   587.0;  after Hamming decoding  222 bit errors  (rate 4/7)

At f=0.001f = 0.001 the Hamming code usually cleans up everything. At f=0.01f = 0.01 a few blocks get two errors, and each surviving error would still corrupt the decompressed text. A stronger code is needed for noisier channels.

Step 5: Protect with an LDPC code

A rate-12\frac{1}{2} LDPC code with sum-product decoding (Sum-Product (Belief Propagation) Decoding) corrects far more. We build a Gallager (3,6)(3, 6) code of length 480, an encoder from its parity-check matrix (Low-Density Parity-Check Codes), and send real data blocks:

python · try it yourself
import numpy as np

def gallager_H(n, wc, wr, rng):
    band = np.zeros((n // wr, n), dtype=np.int8)
    for i in range(n // wr):
        band[i, i * wr:(i + 1) * wr] = 1
    return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)]).astype(int)

def make_encoder(H):
    H = H.copy() % 2; m, n = H.shape; pivots = []; r = 0
    for c in range(n - 1, -1, -1):
        rows = np.nonzero(H[r:, c])[0]
        if len(rows) == 0:
            continue
        p = r + rows[0]; H[[r, p]] = H[[p, r]]
        for i in range(m):
            if i != r and H[i, c]:
                H[i] ^= H[r]
        pivots.append(c); r += 1
        if r == m:
            break
    free = [c for c in range(n) if c not in pivots]
    return free, pivots, H[:r][:, free]

def sum_product(H, llr, max_iter=50):
    rows, cols = np.nonzero(H); wr = int(H[0].sum()); r = np.zeros(len(cols))
    for _ in range(max_iter):
        total = llr + np.bincount(cols, weights=r, minlength=H.shape[1]); x = (total < 0).astype(int)
        if not np.any(H @ x % 2):
            return x
        t = np.tanh(np.clip(total[cols] - r, -30, 30) / 2).reshape(-1, wr)
        t = np.where(np.abs(t) < 1e-12, 1e-12, t)
        r = (2 * np.arctanh(np.clip(np.prod(t, axis=1, keepdims=True) / t, -0.999999, 0.999999))).ravel()
    return x

rng = np.random.default_rng(2)
H = gallager_H(480, 3, 6, rng)
free, pivots, A = make_encoder(H)
k = len(free)
print(f"LDPC code: n = 480, k = {k}, rate {k / 480:.3f}")
for f in [0.01, 0.03, 0.05]:
    bad_blocks = bit_errs = 0
    for _ in range(30):
        s = rng.integers(0, 2, k)
        c = np.zeros(480, dtype=int); c[free] = s; c[pivots] = A @ s % 2
        y = c ^ (rng.random(480) < f)
        x = sum_product(H, np.log((1 - f) / f) * (1 - 2 * y))
        e = int(np.sum(x[free] != s)); bit_errs += e; bad_blocks += int(e > 0)
    print(f"f = {f}: {bad_blocks} of 30 blocks with errors, {bit_errs} bit errors in {30 * k} data bits")
LDPC code: n = 480, k = 242, rate 0.504
f = 0.01: 0 of 30 blocks with errors, 0 bit errors in 7260 data bits
f = 0.03: 0 of 30 blocks with errors, 0 bit errors in 7260 data bits
f = 0.05: 1 of 30 blocks with errors, 37 bit errors in 7260 data bits

Step 6: The whole system

Now put everything together over a BSC with f=0.03f = 0.03: Huffman compression, LDPC protection, sum-product decoding, Huffman decompression. The source-channel separation theorem says this two-stage design loses nothing in the limit: the message needs about HC\frac{H}{C} channel uses per character.

python · try it yourself
import heapq
import numpy as np

alphabet = list("etaoins ")
probs = np.array([0.22, 0.16, 0.13, 0.12, 0.11, 0.1, 0.09, 0.07])
rng = np.random.default_rng(0)
message = "".join(rng.choice(alphabet, size=4000, p=probs))

def huffman_lengths(p):
    heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
    lengths = [0] * len(p); counter = len(p)
    while len(heap) > 1:
        w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
        for s in s1 + s2: lengths[s] += 1
        heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
    return lengths

def canonical_code(lengths):
    order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
    code, value, prev = {}, 0, lengths[order[0]]
    for i in order:
        value <<= lengths[i] - prev; prev = lengths[i]
        code[i] = format(value, f"0{lengths[i]}b"); value += 1
    return code

def gallager_H(n, wc, wr, rng):
    band = np.zeros((n // wr, n), dtype=np.int8)
    for i in range(n // wr):
        band[i, i * wr:(i + 1) * wr] = 1
    return np.vstack([band] + [band[:, rng.permutation(n)] for _ in range(wc - 1)]).astype(int)

def make_encoder(H):
    H = H.copy() % 2; m, n = H.shape; pivots = []; r = 0
    for c in range(n - 1, -1, -1):
        rows = np.nonzero(H[r:, c])[0]
        if len(rows) == 0:
            continue
        p = r + rows[0]; H[[r, p]] = H[[p, r]]
        for i in range(m):
            if i != r and H[i, c]:
                H[i] ^= H[r]
        pivots.append(c); r += 1
        if r == m:
            break
    free = [c for c in range(n) if c not in pivots]
    return free, pivots, H[:r][:, free]

def sum_product(H, llr, max_iter=60):
    rows, cols = np.nonzero(H); wr = int(H[0].sum()); r = np.zeros(len(cols))
    for _ in range(max_iter):
        total = llr + np.bincount(cols, weights=r, minlength=H.shape[1]); x = (total < 0).astype(int)
        if not np.any(H @ x % 2):
            return x
        t = np.tanh(np.clip(total[cols] - r, -30, 30) / 2).reshape(-1, wr)
        t = np.where(np.abs(t) < 1e-12, 1e-12, t)
        r = (2 * np.arctanh(np.clip(np.prod(t, axis=1, keepdims=True) / t, -0.999999, 0.999999))).ravel()
    return x

# 1. compress
code = {alphabet[i]: w for i, w in canonical_code(huffman_lengths(probs)).items()}
inverse = {w: c for c, w in code.items()}
bits = np.array([int(b) for b in "".join(code[c] for c in message)])
# 2. protect
f = 0.03
H = gallager_H(480, 3, 6, np.random.default_rng(3))
free, pivots, A = make_encoder(H); k = len(free)
padded = np.concatenate([bits, np.zeros((-len(bits)) % k, dtype=int)]).reshape(-1, k)
received_bits, channel_uses, flips = [], 0, 0
for s in padded:
    c = np.zeros(480, dtype=int); c[free] = s; c[pivots] = A @ s % 2
    y = c ^ (rng.random(480) < f)                                  # 3. the noisy channel
    flips += int(np.sum(y != c)); channel_uses += 480
    x = sum_product(H, np.log((1 - f) / f) * (1 - 2 * y))          # 4. decode
    received_bits.append(x[free])
rx = np.concatenate(received_bits)[:len(bits)]
# 5. decompress
out, cur = [], ""
for b in rx:
    cur += str(b)
    if cur in inverse:
        out.append(inverse[cur]); cur = ""
decoded = "".join(out)
Hs = float(-np.sum(probs * np.log2(probs))); C = 1 + f * np.log2(f) + (1 - f) * np.log2(1 - f)
print(f"channel flips: {flips} in {channel_uses} uses; residual bit errors after LDPC: {int(np.sum(rx != bits))}")
print("message recovered exactly:", decoded == message)
print(f"channel uses per character: {channel_uses / len(message):.3f}")
print(f"Shannon limit H/C = {Hs:.4f} / {C:.4f} = {Hs / C:.3f};  uncoded ASCII would need 8 with no protection")
channel flips: 686 in 23520 uses; residual bit errors after LDPC: 0
message recovered exactly: True
channel uses per character: 5.880
Shannon limit H/C = 2.9170 / 0.8056 = 3.621;  uncoded ASCII would need 8 with no protection

The system delivers the 4000 characters exactly. It uses more channel uses per character than the Shannon limit, because the Huffman code is slightly above the entropy, the short LDPC code of rate about 0.5 is far from the capacity 0.81 at f=0.03f = 0.03, and padding wastes part of the last block. Longer, irregular LDPC codes and an arithmetic coder would close most of the gap.

Where to go next

  • Replace Huffman with the arithmetic coder of Arithmetic Coding and an adaptive model, then measure bits per character.
  • Use a longer LDPC code (for example n=2400n = 2400) and find the highest ff at which all blocks decode; compare with the capacity limit (Channel Capacity).
  • Replace the BSC by a Gaussian channel and feed soft LLRs 2yσ2\frac{2y}{\sigma^2} to the decoder (The Gaussian Channel).
  • Add a CRC to each block so the receiver can detect the rare decoding failures and request a resend (Error Detection and CRCs).
  • For the machine-learning side of the same ideas, continue with Math for Deep Learning & LLMs.

Test yourself

Why does a single bit error in Huffman-compressed data often corrupt many characters?

  1. The decoder loses codeword boundaries and stays out of step
  2. Huffman codes are not prefix-free
  3. The channel flips several bits at once
  4. Compression adds redundancy

The source-channel separation theorem says that…

  1. compressing to the entropy and then channel coding below capacity is optimal in the limit
  2. compression and protection must be done together
  3. channel coding makes compression unnecessary
  4. compression increases capacity

What is the Shannon limit for the number of channel uses per source symbol?

  1. H / C
  2. C / H
  3. H times C
  4. 8