Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·09

Channel Capacity and the Noisy-Channel Coding Theorem

Around chapter 9: how capacity, the coding theorem, its converse and separation connect the book; three other ways to see them; what the chapter simplifies (a fading channel has no single capacity, real signal sets fall up to 1.53 dB short of the Gaussian formula, and feedback makes capacity easy to reach on an erasure channel); how the dit library computes capacity with bounds that certify the answer; four debugging drills; and interview questions.

6 topics · ~18 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Mutual information (chapter 7) maximised over the sender's choice of inputs → capacity C.
  • Typical sets (chapter 6) applied to the noise → about 2nh(p) patterns per codeword → at most 2nC codewords fit → why C=1−h(p).
  • Random coding → good codes exist below C → the price is block length, not rate.
  • Data processing inequality + Fano (chapter 7) → the converse: above C, errors are unavoidable.
  • Source coding (chapter 6) + channel coding → separation: compress to H, code for C; chapter 8's order (compress, then protect).
  • Differential entropy (chapter 4's exercises) → the Gaussian channel, 12log2(1+SNR) → Shannon–Hartley, the −1.59 dB limit.
  • Chapter 8's codes (repetition, Hamming) fall far short → turbo, LDPC, polar codes approach C.
  • Next: chapter 10 measures the entropy of real sources; chapter 11 turns mutual information into KL divergence.

Explain it differently

Parking in fog. Each car (codeword) needs a parking space, and fog (noise) means drivers end up somewhere in a cloud around where they aimed. If the clouds don't overlap, every car can be found. The car park's area divided by one cloud's area is how many cars fit: the capacity. Bigger car parks (longer blocks) don't change the ratio, but they make the clouds' edges sharper, so the count becomes exact.

A tax on not knowing. Each bit through a channel that flips 10 % of bits carries 1 bit of "content", but the receiver must also learn which bits flipped, and that knowledge costs h(0.1)≈0.47 bits per bit. Capacity is what's left after the tax. An erasure channel charges a smaller tax, because it tells you where the damage is.

A shipping department. The separation theorem is a warehouse with two departments: packing (compression), which squeezes every order into the smallest box without caring how it will travel, and shipping (channel coding), which adds just the right padding for the road without opening the boxes. Neither needs to know the other's job, and the theorem says nothing is lost by keeping them apart, as long as shipments are large.

Gaps and misconceptions

What the chapter oversimplifies

1. "A channel has a capacity", but a fading channel's capacity changes from moment to moment. A mobile radio's received power rises and falls as the phone moves (Rayleigh fading). With an average SNR of 10 dB:

Python
import math
import numpy as np

rng = np.random.default_rng(9)
mean_snr = 10.0                                         # 10 dB on average
gain = rng.exponential(1.0, size=1_000_000)             # Rayleigh fading: the received power varies from moment to moment
C = np.log2(1 + mean_snr * gain) / 2                    # the capacity at each moment, bits per use
print(f"steady channel at 10 dB: {0.5 * math.log2(1 + mean_snr):.3f} bits per use")
print(f"fading channel, average capacity over time: {C.mean():.3f} bits per use")
print(f"{'fixed rate':>11}{'share of moments too weak for it':>36}")
for R in (0.25, 0.5, 1.0, 1.5, 1.73):
    print(f"{R:>11}{float(np.mean(C < R)) * 100:>34.1f} %")
Text
steady channel at 10 dB: 1.730 bits per use
fading channel, average capacity over time: 1.452 bits per use
 fixed rate    share of moments too weak for it
       0.25                               4.1 %
        0.5                               9.6 %
        1.0                              26.0 %
        1.5                              50.4 %
       1.73                              63.3 %

A steady channel at 10 dB carries 1.73 bits per use. The fading one averages 1.45 over time, but a code sent at a fixed rate meets moments when the channel can't carry it: 26 % of moments for 1 bit per use, 63 % for 1.73. So "capacity" splits into several numbers: the ergodic capacity (the average, achievable with codes long enough to span many fades), and the outage capacity (the rate that fails only a chosen small fraction of the time). Mobile systems handle it by measuring the channel and adapting the rate (the exercises' S2), spreading codewords over time and frequency, and using several antennas, so that a fade on one path is covered by another.

2. "Gaussian inputs reach 12log2(1+SNR)", but real transmitters send a few equally spaced levels. Equally likely levels on a grid aren't a normal distribution:

Python
import math
import numpy as np

rng = np.random.default_rng(9)
def pam_capacity(M, snr, samples=400_000):
    """I(X; Y) for M equally spaced, equally likely levels with average power 1, plus Gaussian noise (Monte Carlo)."""
    levels = np.arange(M) - (M - 1) / 2
    levels = levels / math.sqrt(np.mean(levels**2))
    sigma = math.sqrt(1 / snr)
    x = rng.integers(0, M, samples)
    y = levels[x] + rng.normal(0, sigma, samples)
    d = -((y[:, None] - levels[None, :]) ** 2 - (y - levels[x])[:, None] ** 2) / (2 * sigma**2)
    return math.log2(M) - float(np.mean(np.logaddexp.reduce(d, axis=1))) / math.log(2)

def snr_for(rate, f):
    lo, hi = -10.0, 40.0
    for _ in range(40):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if f(10 ** (mid / 10)) < rate else (lo, mid)
    return hi

print(f"{'rate':>5}{'Gaussian inputs':>17}{'8 levels':>10}{'16 levels':>11}{'gap (16 levels)':>17}   SNR in dB needed")
for rate in (1.0, 2.0, 3.0):
    g = snr_for(rate, lambda s: 0.5 * math.log2(1 + s))
    p8 = "never" if rate >= 3 else f"{snr_for(rate, lambda s: pam_capacity(8, s)):.2f}"   # 8 levels carry at most 3 bits
    p16 = snr_for(rate, lambda s: pam_capacity(16, s))
    print(f"{rate:>5}{g:>17.2f}{p8:>10}{p16:>11.2f}{p16 - g:>17.2f}")
print(f"the gap's limit at high SNR, 10 log10(pi e / 6): {10 * math.log10(math.pi * math.e / 6):.2f} dB")
Text
 rate  Gaussian inputs  8 levels  16 levels  gap (16 levels)   SNR in dB needed
  1.0             4.77      5.03       5.02             0.25
  2.0            11.76     12.63      12.53             0.77
  3.0            17.99     never      19.17             1.18
the gap's limit at high SNR, 10 log10(pi e / 6): 1.53 dB

At 1 bit per use, 16 equally likely levels need only 0.25 dB more than the Gaussian formula; at 2 bits, 0.77 dB; at 3 bits, 1.18 dB; and at high rates the gap approaches 10log10(πe/6)≈1.53 dB, the shaping gap: a uniform spread of levels wastes power compared with the bell shape the theorem wants. (8 levels can never carry 3 bits per use: log28 is their ceiling, reached only without noise.) Modern systems recover part of the gap with probabilistic shaping, sending the outer, expensive levels less often, as recent optical-fibre systems do.

3. "Reaching capacity needs long, clever codes", unless the receiver can talk back. On an erasure channel with feedback, the simplest possible scheme reaches capacity:

Python
import random

rng = random.Random(9)
eps, n = 0.2, 100_000
message = [rng.getrandbits(1) for _ in range(n)]
uses = 0
received = []
for bit in message:                       # the receiver says "lost" after each erasure; the sender simply sends it again
    while True:
        uses += 1
        if rng.random() >= eps:
            received.append(bit)
            break
print(f"erasure channel, e = {eps}: capacity {1 - eps}")
print(f"with feedback and resending: {n:,} bits in {uses:,} uses, rate {n / uses:.4f}, errors {sum(a != b for a, b in zip(message, received))}")
Text
erasure channel, e = 0.2: capacity 0.8
with feedback and resending: 100,000 bits in 125,257 uses, rate 0.7984, errors 0

Sending each bit again whenever it's lost delivers 100,000 bits in 125,257 uses, a rate of 0.7984 against the capacity of 0.8, with no errors and no code at all. Feedback doesn't raise the capacity of a memoryless channel (Shannon, 1956), but it can make reaching it trivial, which is why networks, where every link has a return path and losses look like erasures, rely on acknowledgements and retransmission. Without feedback (broadcast, storage, deep space at long distances), long codes are the only way.

Common misconceptions

Misconception What's actually true Where it's shown
"A mobile link's capacity is one number." At 10 dB average, a fixed rate of 1 bit per use fails 26 % of moments. What the chapter oversimplifies, point 1
"Any signal set can reach the Gaussian capacity." Equally spaced levels need up to 1.53 dB more. What the chapter oversimplifies, point 2
"Reaching capacity always needs complex codes." With feedback, resending lost bits reached 0.7984 of 0.8 with no code. What the chapter oversimplifies, point 3
"An iterative capacity algorithm's latest value is the answer." dit stops only when certified lower and upper bounds meet. Code walkthrough
"The formula gives capacity in bits." With natural logarithms it gives nats: 0.368 instead of 0.531. Drill D1
"Any matrix of probabilities describes a channel." Rows must be P(output given input) and add to 1; transposed, the answer was 0.0007. Drill D2
"SNR in the formula can be in decibels." It must be a ratio: 20 dB is 100, not 20. Drill D3
"The smaller file is the better design." Protecting before compressing was smaller and lost everything to one bit in 10,000. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Capacity as a game. Capacity is a maximum over inputs of a minimum-like quantity, and for the Gaussian channel there's a saddle point: Gaussian inputs are best against Gaussian noise, and Gaussian noise is worst against Gaussian inputs. So among all noises of a given power, Gaussian noise is the hardest to communicate through, which is one reason the Gaussian channel is a safe design target.
  • Rate–distortion theory. The dual of capacity for lossy compression: the fewest bits per symbol needed to describe a source within a given distortion (Shannon, 1959). It explains how far audio, image and video codecs can go, and computing it uses the same Blahut–Arimoto iteration.
  • Zero-error capacity. Asking for no errors, not just vanishing ones, gives a different and much harder quantity (Shannon, 1956): for the noisy typewriter it's log213 (use every second key), but for the five-letter "pentagon" channel it took until László Lovász's 1979 proof to find that it's 12log25, and for most channels it's still unknown.

Applying it

Code walkthrough

The dit library (discrete information theory, BSD licence) computes capacity with Blahut–Arimoto and, unlike the chapter's ten-line version, certifies its answer. Excerpt from dit/algorithms/channelcapacity.py in dit 2.4 (pip install dit==2.4):

Python
    q, D = evaluate(r)
    lower = float(r @ D)
    upper = float(D.max())
    mu = 1.0
    iters = 0
    while upper - lower > tol(lower) and iters < maxiter:
        iters += 1
        new_logr, new_r = _normalize_log(logr + mu * D)
        new_q, new_D = evaluate(new_r)
        new_lower = float(new_r @ new_D)
        if accelerated:
            if mu > 1.0 and new_lower < lower:
                mu = 1.0
                new_logr, new_r = _normalize_log(logr + D)
                new_q, new_D = evaluate(new_r)
                new_lower = float(new_r @ new_D)
            else:
                dq = _kl(new_q, q)
                mu = min(_kl(new_r, r) / dq, _MAX_STEP) if dq > 0 else 1.0
        logr, r, q, D, lower = new_logr, new_r, new_q, new_D, new_lower
        upper = float(D.max())
    return logr, r, q, D, lower, upper, iters

D holds, for each input, how far its output distribution is from the average output (a Kullback–Leibler divergence, chapter 11). The update logr + mu * D is the chapter's rule in logarithms: inputs whose outputs stand out get more probability. The key idea is in lower and upper. For any input distribution r, the mutual information ∑xr(x)Dx is a lower bound on capacity (it's achievable), and the largest Dx is an upper bound (a theorem of Blahut's paper). The loop stops when the two meet, so the answer comes with a guarantee, not just "the estimate stopped changing". The accelerated version takes bigger steps when that's safe and falls back to the plain step when a bigger one would lower the bound. Measured on the Z channel:

Python
import math
import numpy as np
import dit
from dit.algorithms.channelcapacity import channel_capacity, _blahut_arimoto, _row_plogp

Z = np.array([[1.0, 0.0], [0.5, 0.5]])
print("dit", dit.__version__, "Z channel:", channel_capacity(Z))
plogp = _row_plogp(Z)
start = np.log(np.full(2, 0.5))
print(f"{'iterations':>11}{'lower bound':>13}{'upper bound':>13}   (bits; plain Blahut-Arimoto)")
for k in (0, 1, 2, 5, 10, 20, 40):
    *_, lower, upper, iters = _blahut_arimoto(Z, plogp, start, lambda c: 0.0, k, accelerated=False)
    print(f"{iters:>11}{lower / math.log(2):>13.6f}{upper / math.log(2):>13.6f}")
for name, acc in (("plain", False), ("accelerated", True)):
    *_, lower, upper, iters = _blahut_arimoto(Z, plogp, start, lambda c: 1e-12, 100_000, accelerated=acc)
    print(f"{name:<12} gap below 1e-12 nats after {iters} iterations")
Text
dit 2.4 Z channel: (np.float64(0.32192809488736235), array([0.6, 0.4]))
 iterations  lower bound  upper bound   (bits; plain Blahut-Arimoto)
          0     0.311278     0.415037
          1     0.317468     0.380917
          2     0.320112     0.359037
          5     0.321814     0.331040
         10     0.321927     0.322798
         20     0.321928     0.321936
         40     0.321928     0.321928
plain        gap below 1e-12 nats after 54 iterations
accelerated  gap below 1e-12 nats after 6 iterations

dit returns 0.3219 bits with 60 % zeros, as the chapter found. The bounds close in from both sides: after 5 plain iterations the capacity is known to lie between 0.3218 and 0.3310, after 20 between 0.321928 and 0.321936. The plain iteration needs 54 steps to close the gap to 10−12 nats; the accelerated one, 6.

Read it yourself

Using the code above: why can't the loop simply stop when lower stops changing much between iterations? And why is the update done on logarithms (logr) rather than on the probabilities themselves?

Debugging drills

D1. Capacity below 1−h(p)

A capacity routine reports 0.368 bits per use for a binary symmetric channel with p=0.1, and 0.637 for p=0.01.

Python
import numpy as np

def mutual_info(px, W):
    px, W = np.asarray(px, float), np.asarray(W, float)
    py = px @ W
    with np.errstate(divide="ignore", invalid="ignore"):
        terms = np.where(W > 0, px[:, None] * W * np.log(W / py[None, :]), 0)
    return float(terms.sum())

for p in (0.01, 0.1, 0.2):
    print(f"BSC p = {p}: capacity reported {mutual_info([0.5, 0.5], [[1 - p, p], [p, 1 - p]]):.4f} bits per use")
Text
BSC p = 0.01: capacity reported 0.6371 bits per use
BSC p = 0.1: capacity reported 0.3681 bits per use
BSC p = 0.2: capacity reported 0.1927 bits per use

D2. The Z channel with almost no capacity

An analyst computes the Z channel's capacity as 0.0007 bits, with all inputs zero.

Python
import numpy as np
from cap import capacity

# the Z channel, written by the analyst as P(input | output): columns are inputs, rows are outputs
Z_as_written = np.array([[1.0, 0.5],
                         [0.0, 0.5]])
C, px = capacity(Z_as_written)
print(f"reported capacity {C:.4f} bits, best inputs {px.round(3)}")
print("row sums:", Z_as_written.sum(axis=1))
Text
reported capacity 0.0007 bits, best inputs [1. 0.]
row sums: [1.5 0.5]

D3. A capacity calculator that undersells the link

A planning tool says a 20 MHz link at 30 dB can carry 99 Mbit/s, while the link's specification promises far more.

Python
import math

def capacity_bps(bandwidth_hz, snr):
    return bandwidth_hz * math.log2(1 + snr)

for snr_db in (10, 20, 30):
    print(f"20 MHz at {snr_db} dB: {capacity_bps(20e6, snr_db) / 1e6:.1f} Mbit/s")
Text
20 MHz at 10 dB: 69.2 Mbit/s
20 MHz at 20 dB: 87.8 Mbit/s
20 MHz at 30 dB: 99.1 Mbit/s

D4. The smaller file that loses everything

Two ways to prepare text for a noisy link: protect with Hamming(7,4) and then compress, or compress and then protect. The first is smaller.

Python
import random, zlib
from pathlib import Path
from chan import ham_encode, ham_decode

rng = random.Random(9)
text = Path("shakespeare.txt").read_bytes()[:200_000]
def bits_of(data):
    return [(b >> k) & 1 for b in data for k in range(8)]
def bytes_of(bits):
    return bytes(sum(bits[i + k] << k for k in range(8)) for i in range(0, len(bits), 8))
def pad4(data):
    return data + bytes(-len(data) % 4)                   # whole Hamming blocks fill whole bytes
def noisy(data, p):
    bad = bytearray(data)
    for i in rng.sample(range(len(data) * 8), rng.binomialvariate(len(data) * 8, p)):
        bad[i // 8] ^= 1 << (i % 8)
    return bytes(bad)
def inflate(data):
    try:
        return zlib.decompressobj().decompress(data)
    except zlib.error:
        return b""
def wrong(out):
    return sum(a != b for a, b in zip(out, text)) + abs(len(out) - len(text))

a = zlib.compress(bytes_of(ham_encode(bits_of(text))), 9)          # protect, then compress
b = bytes_of(ham_encode(bits_of(pad4(zlib.compress(text, 9)))))    # compress, then protect
print(f"text {len(text):,} bytes; protect then compress {len(a):,} bytes; compress then protect {len(b):,} bytes")
print("one bit in 10,000 flipped on the way, 5 trials each: bytes of text wrong after decoding")
for name, blob, decode in (("protect then compress", a, lambda d: bytes_of(ham_decode(bits_of(inflate(d))))),
                           ("compress then protect", b, lambda d: inflate(bytes_of(ham_decode(bits_of(d)))))):
    print(f"  {name:<22}", "  ".join(f"{wrong(decode(noisy(blob, 1e-4))):,}" for _ in range(5)))
Text
text 200,000 bytes; protect then compress 127,083 bytes; compress then protect 138,425 bytes
one bit in 10,000 flipped on the way, 5 trials each: bytes of text wrong after decoding
  protect then compress  200,000  200,000  200,000  200,000  200,000
  compress then protect  0  0  0  0  0

Career-oriented

Interview prep

Mid level

Q1. What does Shannon's noisy-channel coding theorem say, in plain terms?

How to get there. Capacity; below it, errors vanish with long blocks; above, they can't.

Q2. What's the Shannon–Hartley theorem, and what does it say about how to make a link faster?

How to get there. C=Blog2(1+SNR).

Senior level

Q3. A product manager asks why the app's video calls degrade on a weak mobile signal even though "the network has plenty of bandwidth". Explain.

How to get there. Capacity depends on SNR, fading, and delay limits.

Q4. Your team stores data on flash memory whose error rate rises as cells wear. How do you use the chapter's ideas to set the error-correction overhead?

How to get there. Capacity at the worst error rate, margins, long codes.

Staff level

Q5. Leadership wants to know whether investing in a better error-correcting code for your satellite product is worthwhile. How do you frame the analysis?

How to get there. Distance from the Shannon limit, in dB, translated into money.

Q6. A team proposes a single integrated system that jointly compresses and protects sensor data, arguing it will beat separate compression and error correction. When would you support it?

How to get there. Separation's assumptions: long blocks, one receiver, no delay limit.