TExcelTAD
Home › Information Theory › Random Codes and Typical-Set Decoding

Random Codes and Typical-Set Decoding

Shannon's proof of the coding theorem picks a code at random: each of the 2nR2^{nR} codewords is a string of nn 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 (x,y)(\mathbf{x}, \mathbf{y}) of length nn is jointly typical if x\mathbf{x} is typical, y\mathbf{y} is typical, and the pair is typical for the joint distribution P(x)Q(y∣x)P(x)Q(y \mid x) (Typical Sets). For a BSC with uniform inputs this boils down to one condition: the number of positions where x\mathbf{x} and y\mathbf{y} differ is close to nfnf.

Two facts drive the proof:

  1. The transmitted codeword and the received word are jointly typical with probability close to 1.
  2. An unrelated random codeword is jointly typical with the received word with probability about 2−nI(X;Y)2^{-nI(X;Y)}.
python · try it yourself
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 −I-I; the gap comes from the tolerance β\beta and shrinks as β\beta gets smaller. With 2nR2^{nR} codewords, the expected number of wrong codewords that look typical is about 2nR⋅2−nI=2−n(I−R)2^{nR} \cdot 2^{-nI} = 2^{-n(I - R)}, which vanishes when R<IR < I. 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:

python · try it yourself
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:

python · try it yourself
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 RR and length nn needs a table of 2nR2^{nR} codewords, and maximum-likelihood decoding compares the received word with all of them. For n=1000n = 1000 and R=0.5R = 0.5 that is 25002^{500} codewords. Practical codes add structure (linearity, sparse parity checks) so that encoding and decoding take time polynomial in nn, 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 I(X;Y)=0.5I(X; Y) = 0.5. About how many wrong codewords look jointly typical with the received word?

Answer

About 2−502^{-50}, essentially none.

Solution

2−n(I−R)=2−500×0.12^{-n(I - R)} = 2^{-500 \times 0.1}.

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

232≈4.32^{32} \approx 4.3 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
python · try it yourself
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 n2\frac{n}{2} apart, which is what matters for the average error probability.

Test yourself

Why does a random code of rate below capacity work?

  1. An unrelated codeword is jointly typical with the output with probability about 2−nI2^{-nI}
  2. Random codes have no close codewords
  3. The decoder knows the noise
  4. Random codewords are orthogonal

What is the maximum-likelihood decoder for a BSC with f < 0.5?

  1. choose the codeword at minimum Hamming distance
  2. choose the codeword at maximum distance
  3. choose a random codeword
  4. flip all bits

Why are random codes not used in practice?

  1. Encoding and decoding need exponentially large tables
  2. They are worse than repetition codes
  3. They exceed capacity
  4. They cannot be decoded at all