Random Codes and Typical-Set Decoding
Shannon's proof of the coding theorem picks a code at random: each of the codewords is a string of independent random symbols. Surprisingly, such a code is almost always good. This lesson simulates random codes on a binary symmetric channel and explains why they work.
Joint typicality
A pair of sequences of length is jointly typical if is typical, is typical, and the pair is typical for the joint distribution (Typical Sets). For a BSC with uniform inputs this boils down to one condition: the number of positions where and differ is close to .
Two facts drive the proof:
- The transmitted codeword and the received word are jointly typical with probability close to 1.
- An unrelated random codeword is jointly typical with the received word with probability about .
import numpy as np
from scipy.stats import binom
from scipy.special import gammaln
n, f, beta = 1000, 0.1, 0.02
lo, hi = int(np.ceil(n * (f - beta))), int(np.floor(n * (f + beta)))
p_true = binom.cdf(hi, n, f) - binom.cdf(lo - 1, n, f)
# an unrelated uniform word differs in Binomial(n, 1/2) positions
log2_p_other = np.logaddexp2.reduce([(gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1)) / np.log(2) - n
for k in range(lo, hi + 1)])
I = 1 - (-f * np.log2(f) - (1 - f) * np.log2(1 - f))
print(f"P(true codeword jointly typical) = {p_true:.4f}")
print(f"log2 P(unrelated codeword jointly typical) / n = {log2_p_other / n:.4f} (-I = {-I:.4f})")P(true codeword jointly typical) = 0.9695
log2 P(unrelated codeword jointly typical) / n = -0.4751 (-I = -0.5310)
The exponent is close to ; the gap comes from the tolerance and shrinks as gets smaller. With codewords, the expected number of wrong codewords that look typical is about , which vanishes when . That is the whole proof idea.
Simulating random codes
Typical-set decoding is convenient for proofs; in simulation we use the best decoder for the BSC, minimum Hamming distance (maximum likelihood). We draw a random codebook, send random codewords through the channel and count block errors:
import numpy as np
def block_error_rate(n, R, f, trials, rng):
M = int(2 ** round(n * R))
code = rng.integers(0, 2, (M, n), dtype=np.int8)
errors = 0
for _ in range(trials):
m = rng.integers(M)
y = code[m] ^ (rng.random(n) < f)
d = np.count_nonzero(code != y, axis=1)
errors += int(np.argmin(d) != m)
return errors / trials
rng = np.random.default_rng(0)
f = 0.05 # capacity 1 - H2(0.05) = 0.714
for R in [0.25, 0.5]:
for n in [8, 16, 24, 32]:
print(f"R = {R}, n = {n:2d} ({int(2 ** round(n * R)):5d} codewords): block error rate {block_error_rate(n, R, f, 400, rng):.3f}")R = 0.25, n = 8 ( 4 codewords): block error rate 0.062
R = 0.25, n = 16 ( 16 codewords): block error rate 0.007
R = 0.25, n = 24 ( 64 codewords): block error rate 0.003
R = 0.25, n = 32 ( 256 codewords): block error rate 0.000
R = 0.5, n = 8 ( 16 codewords): block error rate 0.083
R = 0.5, n = 16 ( 256 codewords): block error rate 0.085
R = 0.5, n = 24 ( 4096 codewords): block error rate 0.070
R = 0.5, n = 32 (65536 codewords): block error rate 0.037
At a fixed rate below capacity, longer random codes make fewer errors. Lower rates converge faster, because more room is left between codewords.
Above capacity
Push the rate above capacity and longer codes make things worse, not better:
import numpy as np
def block_error_rate(n, R, f, trials, rng):
M = int(2 ** round(n * R))
code = rng.integers(0, 2, (M, n), dtype=np.int8)
errors = 0
for _ in range(trials):
m = rng.integers(M)
y = code[m] ^ (rng.random(n) < f)
errors += int(np.argmin(np.count_nonzero(code != y, axis=1)) != m)
return errors / trials
rng = np.random.default_rng(1)
f = 0.2 # capacity 1 - H2(0.2) = 0.278
for n in [8, 16, 24, 32]:
print(f"R = 0.5 > C, n = {n:2d}: block error rate {block_error_rate(n, 0.5, f, 400, rng):.3f}")R = 0.5 > C, n = 8: block error rate 0.580
R = 0.5 > C, n = 16: block error rate 0.623
R = 0.5 > C, n = 24: block error rate 0.690
R = 0.5 > C, n = 32: block error rate 0.792
Why random codes are not used directly
A random code of rate and length needs a table of codewords, and maximum-likelihood decoding compares the received word with all of them. For and that is codewords. Practical codes add structure (linearity, sparse parity checks) so that encoding and decoding take time polynomial in , while keeping most of the random-code performance (Linear Block Codes, Low-Density Parity-Check Codes).
In software
- Random linear codes (a random generator matrix) behave like random codes and are easy to encode; their decoding is still hard in general, which is the basis of code-based cryptography (McEliece).
np.count_nonzero(code != y, axis=1)computes all Hamming distances at once; for larger codebooks pack bits into integers and use popcount.
Exercises
Exercise 1: Expected false matches
A random code has rate 0.4 and length 500, on a channel with . About how many wrong codewords look jointly typical with the received word?
Answer
About , essentially none.
Solution
.
Exercise 2: Codebook size
How many codewords does a rate-0.5 code of length 64 have, and why is ML decoding by brute force hopeless?
Answer
billion codewords.
Solution
Every received word would need billions of distance computations. Structured codes avoid this.
Exercise 3: Distances in a random code (code)
Draw a random code with 256 codewords of length 32 and find its minimum distance (the smallest Hamming distance between two codewords).
Answer
5 for this seed, while the average distance is about 16.
Solution
import numpy as np
rng = np.random.default_rng(2)
code = rng.integers(0, 2, (256, 32), dtype=np.int8)
D = (code[:, None, :] != code[None, :, :]).sum(axis=2)
np.fill_diagonal(D, 99)
print("minimum distance:", int(D.min()), " average distance:", round(float(D[D < 99].mean()), 2))minimum distance: 5 average distance: 16.01
Random codes have a few close pairs, but most codewords are about apart, which is what matters for the average error probability.
Test yourself
Why does a random code of rate below capacity work?
- An unrelated codeword is jointly typical with the output with probability about
- Random codes have no close codewords
- The decoder knows the noise
- Random codewords are orthogonal
What is the maximum-likelihood decoder for a BSC with f < 0.5?
- choose the codeword at minimum Hamming distance
- choose the codeword at maximum distance
- choose a random codeword
- flip all bits
Why are random codes not used in practice?
- Encoding and decoding need exponentially large tables
- They are worse than repetition codes
- They exceed capacity
- They cannot be decoded at all