Este livro ainda não está disponível em Português. Edições: English.
University Computer Science — Year 3 · Graduação — Ano 3
19Information, Entropy and Error-Correcting Codes
How many bits does a message really need, and how many more must be added so that it survives a noisy line? Both questions have exact answers, given by Claude Shannon in 1948. The first is the entropy of the source: no code can do better on average, and Huffman’s code comes within one bit of it. The second is the capacity of the channel: below it, codes can make errors as rare as wanted. This chapter measures both on Brenmoor’s library catalogue, then builds the codes engineers use: the Hamming code, which corrects any single flipped bit with three check bits for four of data, and the cyclic codes behind every CRC, read again as division of polynomials. Every claim about error rates is checked twice, by computing it and by simulating a seeded channel.
You already know
The entropy of a finite distribution is (Year 2 volume). A prefix code gives each symbol a binary codeword, no codeword a prefix of another, so a stream decodes without separators; Huffman’s algorithm builds one of least average length (Year 1 volume). A cyclic redundancy check appends to a frame the remainder of a division, so that the receiver detects most corruptions (Year 2 volume). Matrices, their products and the field with two elements, where , are those of the mathematics book.
19.1 Entropy
Definition 19.1 (Self-information, entropy of a source)
A source emits symbols of an alphabet independently, each with probability . The self-information of an outcome of probability is bits. The entropy of a source is the expected self-information of a symbol, bits per symbol. The block entropy is the entropy of blocks of symbols taken as one symbol; for a source of independent symbols, .
A rare outcome carries much information, a certain one none, and the information of two independent outcomes adds, since . The source of this chapter is the titles of the 80 books in Brenmoor’s library catalogue, in lower case with letters and spaces only.
def entropy(probabilities):
"""H = sum of p log2(1/p), in bits per symbol; zero probabilities add nothing."""
return sum(p * math.log2(1 / p) for p in probabilities if p > 0)
def frequencies(text, block=1):
"""Relative frequencies of the non-overlapping blocks of `block` symbols."""
blocks = [text[i:i + block] for i in range(0, len(text) - block + 1, block)]
return {b: c / len(blocks) for b, c in Counter(blocks).items()}
$ python entropy.py
1437 symbols, alphabet of 23
' ': p = 0.1816, information 2.46 bits
'e': p = 0.1357, information 2.88 bits
't': p = 0.0842, information 3.57 bits
'w': p = 0.0077, information 7.03 bits
entropy of the letters: 3.990 bits per symbol
uniform on 23 symbols: 4.524 bits per symbol
w the rarest; 3.99 bits per symbol, against 4.52 for a uniform source on 23 symbols.Theorem 19.2 (Gibbs’ inequality; entropy is at most )
For distributions and on the same symbols, , with equality only when . In particular , with equality only for the uniform source.
Proof. Using , with equality only at , the difference is , sums over the with . Take uniform: . ∎
For two symbols with probabilities and the entropy is the binary entropy function : zero at and , and one bit at .
Joint and conditional entropy, the uncertainty of a pair of variables and of one when the other is known, extend these definitions; they are not needed here.
19.2 The source-coding theorem
Definition 19.3 (Kraft inequality, uniquely decodable code)
A code is uniquely decodable when no two different strings of symbols encode to the same bits; prefix codes are. Codeword lengths satisfy the Kraft inequality when .
Theorem 19.4 (Kraft)
The lengths of a prefix code satisfy the Kraft inequality, and for any lengths that satisfy it there is a prefix code with those lengths.
A codeword of length claims the fraction of all infinite bit strings, those that begin with it, and in a prefix code the claims are disjoint (Exercise 19.7 is the full proof). Kraft published the inequality for prefix codes in 1949; Brockway McMillan proved in 1956 that it holds for every uniquely decodable code.
The construction gives the shortest lengths the smallest binary numbers, a canonical code.
def kraft_sum(lengths):
return sum(Fraction(1, 2 ** n) for n in lengths)
def is_prefix_free(words):
words = sorted(words) # a prefix sorts just before the words it starts
return all(not b.startswith(a) for a, b in zip(words, words[1:]))
def code_from_lengths(lengths):
"""Canonical code: shortest first, each word the next binary number, padded."""
assert kraft_sum(lengths) <= 1
words, value, previous = [], 0, 0
for n in sorted(lengths):
value <<= n - previous # extend the next free value to n bits
words.append(format(value, f"0{n}b"))
value, previous = value + 1, n
return words
$ python kraft.py
['0', '10', '110', '111']: Kraft sum 1, prefix-free True
['0', '01', '11']: Kraft sum 1, prefix-free False
['00', '01', '10']: Kraft sum 3/4, prefix-free True
lengths 1, 2, 3, 3 -> ['0', '10', '110', '111']
lengths 2, 2, 2, 3, 4, 4 -> ['00', '01', '10', '110', '1110', '1111']
lengths 1, 1, 2: Kraft sum 5/4 > 1, no prefix code
Theorem 19.5 (Source-coding theorem)
For a source of entropy , the least expected length of a prefix code for its symbols satisfies . Coding blocks of symbols at once gives an expected length per symbol below .
The lower bound is Gibbs’ inequality with ; the upper bound takes , which satisfies Kraft (Exercise 19.10). Huffman’s code is optimal, so its length is . David Huffman published his construction in 1952. Below, the catalogue’s letters are treated as a source of independent letters with the catalogue’s frequencies, and Huffman codes are built for single letters, pairs and triples.
def huffman_lengths(probabilities):
"""Codeword length of each symbol: merge the two least likely, again and again."""
heap = [(p, i, [s]) for i, (s, p) in enumerate(probabilities.items())]
heapq.heapify(heap)
depth = dict.fromkeys(probabilities, 0)
count = len(heap)
while len(heap) > 1:
p1, _, a = heapq.heappop(heap)
p2, _, b = heapq.heappop(heap)
for s in a + b:
depth[s] += 1 # every symbol under the merged node gets one bit longer
heapq.heappush(heap, (p1 + p2, count, a + b))
count += 1
return depth
$ python huffman_vs_h.py
H = 3.9904 bits per letter
block symbols Huffman bits per letter excess over H bound 1/k
1 23 4.0292 0.0389 1.000
2 529 4.0048 0.0145 0.500
3 12,167 3.9999 0.0095 0.333
So no lossless code for this source averages fewer than 3.99 bits per letter, and a simple one averages 4.03. The 23-symbol uniform code would need 5 bits, or with blocks.
19.3 Channels
Definition 19.6 (Binary symmetric channel, channel capacity, repetition code)
The binary symmetric channel with crossover probability transmits bits, flipping each independently with probability . Its channel capacity is bits per use. A code of rate sends bits of message in uses of the channel. The repetition code of length sends each bit times, rate , and decodes by majority.
Theorem 19.7 (Noisy-channel coding theorem)
For every rate and every there are codes of rate at least whose probability of decoding a block wrongly is below ; above capacity, no such codes exist.
Shannon stated it in 1948; the proof, by choosing a code at random, is not given here. It says that noise costs rate, not reliability. The repetition code shows what a naive code pays.
def channel(bits, p, rng):
return [b ^ (rng.random() < p) for b in bits]
def repetition_error(n, p):
"""A majority of n copies is wrong when more than n/2 of them are flipped."""
return sum(comb(n, k) * p ** k * (1 - p) ** (n - k)
for k in range(n // 2 + 1, n + 1))
$ python bsc.py
p n rate measured exact
0.01 1 1/1 0.01037 0.01000
0.01 3 1/3 0.00029 0.00030
0.01 5 1/5 0.00000 0.00001
0.05 1 1/1 0.04955 0.05000
0.05 3 1/3 0.00754 0.00725
0.05 5 1/5 0.00134 0.00116
0.1 1 1/1 0.10207 0.10000
0.1 3 1/3 0.02807 0.02800
0.1 5 1/5 0.00886 0.00856
0.2 1 1/1 0.20083 0.20000
0.2 3 1/3 0.10497 0.10400
0.2 5 1/5 0.05822 0.05792
$ python capacity.py
p h(p) capacity 1 - h(p)
0.0 0.0000 1.0000
0.001 0.0114 0.9886
0.01 0.0808 0.9192
0.05 0.2864 0.7136
0.1 0.4690 0.5310
0.2 0.7219 0.2781
0.5 1.0000 0.0000
At the capacity is 0.53 bits per use, so codes of rate with errors as rare as wanted exist; the repetition code of rate still errs on almost one bit in a hundred. Making a repetition code reliable sends its rate to zero. Better codes spread each message bit over several check bits.
19.4 Hamming distance and linear codes
Definition 19.8 (Hamming distance, minimum distance, error-correcting code)
The Hamming distance between two words of the same length is the number of positions where they differ. The minimum distance of a code is the least distance between two of its codewords. A code is an error-correcting code for errors when nearest-codeword decoding recovers the sent word whenever at most bits are flipped.
Theorem 19.9 (Detection and correction)
A code of minimum distance detects every pattern of at most errors and corrects every pattern of at most .
The distance is a metric, so the balls of radius around the codewords are disjoint, and fewer than flips cannot turn a codeword into another (Exercise 19.8).
Definition 19.10 (Linear code, generator matrix, parity-check matrix, syndrome)
A linear code of length and dimension is a subspace of of dimension , being the field with two elements: the sum of two codewords, bit by bit modulo 2, is a codeword. A generator matrix is a matrix whose rows are a basis: the message encodes to . A parity-check matrix is an matrix with exactly for the codewords . The syndrome of a received word is .
If , the syndrome is : it depends on the error only, not on the message. And the minimum distance of a linear code is the least weight of a nonzero codeword, since is a codeword of weight equal to their distance.
Definition 19.11 (Hamming code, perfect code, sphere-packing bound)
The Hamming code with check bits has length and a parity-check matrix whose columns are the nonzero vectors of , column being written in binary. The sphere-packing bound: a code of words of length correcting errors has . A code meeting it with equality is a perfect code.
The bound holds because the balls of radius around the codewords are disjoint and each holds words of . For the Hamming code is the code: a single error at position has syndrome column , which is in binary, so the receiver flips bit back. No two columns are equal and none is zero, so no codeword has weight 1 or 2, and the minimum distance is 3. A generator matrix, its rows being the codewords of the four unit messages, is
With 16 codewords and balls of words, : the code is perfect, and every word of 7 bits is within distance 1 of exactly one codeword (Exercise 19.11). Richard Hamming published these codes in 1950, after relay computers at Bell Labs kept stopping on errors their punched input could detect but not correct.
H = [[(j >> i) & 1 for j in range(1, 8)] for i in range(3)] # row i: bit i of 1..7
DATA = [3, 5, 6, 7] # the positions of the four data bits
def encode(d):
c = [0] * 8 # c[1..7]; c[0] unused
for pos, bit in zip(DATA, d):
c[pos] = bit
for i in range(3): # parity bit 2^i makes row i of H c even
c[1 << i] = sum(c[j] for j in range(1, 8) if j >> i & 1 and j != 1 << i) % 2
return c[1:]
def syndrome(word):
"""H times the word, mod 2, read as a binary number."""
bits = [sum(h * w for h, w in zip(row, word)) % 2 for row in H]
return sum(b << i for i, b in enumerate(bits))
def decode(word):
word, s = list(word), syndrome(word)
if s:
word[s - 1] ^= 1 # a single error at position s
return [word[pos - 1] for pos in DATA]
$ python hamming74.py
parity-check matrix: 1010101 0110011 0001111
1011 -> 0110011
received 0110111 syndrome 5 decoded 1011
16 codewords, minimum distance 3
p = 0.01, 1,000,000 blocks of 4 bits: block errors 3.9336% uncoded, 0.2077% with Hamming (7,4)
computed: 3.9404% and 0.2031%
At an uncoded block of four bits is wrong with probability . The Hamming code fails only when two or more of its seven bits flip, with probability , at rate ; the simulation agrees.
19.5 Cyclic codes
Definition 19.12 (Cyclic code, Reed–Solomon code)
Read a word as the polynomial with coefficients in . A cyclic code is a linear code closed under rotating its words by one place; its codewords are the multiples of a generator polynomial that divides . A Reed–Solomon code is a cyclic code over a larger finite field, whose symbols are bytes rather than bits.
The CRC of the Year 2 volume is division by a generator: a message of degree below is sent as , a multiple of , and the receiver checks that the remainder of what it receives is zero. Over subtraction is exclusive or, so long division is a loop of shifts and XORs. A burst of length is an error pattern whose first and last flipped bits are positions apart.
def remainder(a, g=G):
"""a mod g over GF(2): cancel the leading term with a shifted g, until
deg a < deg g."""
while a.bit_length() >= g.bit_length():
a ^= g << (a.bit_length() - g.bit_length())
return a
def encode(message):
"""Append r check bits so that the codeword is a multiple of g."""
shifted = message << R
return shifted | remainder(shifted)
Theorem 19.13 (Burst detection)
If the generator has degree and a nonzero constant term, every burst of length at most is detected.
Proof. A burst of length starting at position is with and . It goes undetected only if divides . Since , has no factor in common with , so would divide , a nonzero polynomial of smaller degree: impossible. ∎
The program checks the theorem by brute force on a 32-bit codeword, then counts what longer bursts escape: a burst of length is missed only when it equals shifted, one pattern in , and longer bursts one in .
$ python crc_poly.py
message 010011000110100101100010
codeword 01001100011010010110001000011101, remainder 0
burst length patterns undetected fraction
1 32 0 0.00000
2 31 0 0.00000
3 60 0 0.00000
4 116 0 0.00000
5 224 0 0.00000
6 432 0 0.00000
7 832 0 0.00000
8 1,600 0 0.00000
9 3,072 24 0.00781
10 5,888 23 0.00391
11 11,264 44 0.00391
12 21,504 84 0.00391
Cyclic codes are well suited to bursts, the runs of corrupted bits that scratches and electrical noise produce. Reed–Solomon codes, by Irving Reed and Gustave Solomon in 1960, use the finite fields of the mathematics book’s Year 3 to correct whole corrupted bytes. They are in compact discs, the first mass-produced consumer use in 1982, in DVDs and Blu-ray discs, and in QR codes and other two-dimensional bar codes, which they let a scanner read even with part of the code damaged. They are told here, not built.
19.6 Exercises
Exercise 19.1 ★
Compute the entropy of a fair six-sided die, and of a die that shows 6 with probability and each other face with probability . Which is larger, and why must it be?
Solution
Solution of Exercise 19.1.
Fair die: bits. Loaded die: bits. The fair die has more: by Theorem 19.2 the uniform distribution is the only one reaching .
Exercise 19.2 ★
For each code, give its Kraft sum and say whether it is prefix-free: ; ; ; .
Solution
Solution of Exercise 19.2.
: sum , prefix-free. : sum 1, prefix-free. : sum 1, not prefix-free, since 0 begins 01; it is not even uniquely decodable, as 010 reads 0,10 or 01,0. : sum , prefix-free.
Exercise 19.3 ★
Give the Hamming distances between 1011010, 1001110 and 0011011. How many errors could a code containing these three words correct?
Solution
Solution of Exercise 19.3.
1011010 and 1001110: 2. 1011010 and 0011011: 2. 1001110 and 0011011: 4. The minimum distance is 2, so by Theorem 19.9 the code detects one error and corrects none.
Exercise 19.4 ★
hamming74.py receives 1110100. Predict the syndrome, the corrected codeword and the decoded data.
Solution
Solution of Exercise 19.4.
The 1s are at positions 1, 2, 3 and 5; the syndrome is their exclusive or, . Flipping bit 5 gives 1110000, the codeword of 1000, the first row of .
Exercise 19.5 ★★
exercises/ex5_syndrome.py decodes Hamming with the rows of the parity-check matrix taken in the opposite order. Which single errors does it still correct, which does it not, and why? Fix it.
Solution
Solution of Exercise 19.5.
Reading the rows in the opposite order reverses the three bits of the syndrome. The positions 2 (010), 5 (101) and 7 (111) read the same both ways and are corrected. An error at 1 is read as 4 and one at 4 as 1: the wrong parity bit is flipped, but the data comes out right. An error at 3 (011) is read as 6 (110), and one at 6 as 3: a second data bit is flipped, and two data bits come out wrong (test_exercise_5). The fix shifts bit of the syndrome by , as in Listing 19.5.
Exercise 19.6 ★★
Write encode15 and decode15 for the Hamming code, parity bits at positions 1, 2, 4 and 8. They are tested on every single error of random words.
Solution
Solution of Exercise 19.6.
exercises/ex6_hamming15.py: data at the eleven positions that are not powers of two; parity bit is the sum of the data bits whose position has bit set. The syndrome is the exclusive or of the positions of the 1s: zero for a codeword, and the position of a single error otherwise (test_exercise_6_all_single_errors).
Exercise 19.7 ★★
Prove Theorem 19.4.
Solution
Solution of Exercise 19.7.
Facts used: in a prefix code no codeword is a prefix of another; is the fraction of bit strings of a fixed length that begin with a given word of length .
Let be the longest length. A codeword of length begins strings of length , and these sets are disjoint for a prefix code, since a common string would make one codeword a prefix of the other. So . Conversely, for lengths in increasing order with Kraft sum at most 1, give the -th word the first bits of the binary expansion of , which is below 1. Two words : the interval of numbers beginning with word has width , and word ’s value lies at or beyond its end, so word is not a prefix of word . This is code_from_lengths.
Exercise 19.8 ★★
Prove Theorem 19.9.
Solution
Solution of Exercise 19.8.
Facts used: Hamming distance satisfies the triangle inequality, since changing into through changes at most positions.
Detection: a pattern of errors turns codeword into with , so is not a codeword, and the receiver sees the error. Correction: let , so . If and is another codeword, , so is the unique nearest codeword.
Exercise 19.9 ★★
Compute the probability that the repetition code of length 3 decodes a bit wrongly at and , and check against Output 19.4. What is the probability that a 4-bit block sent with it arrives wrong at , and at what rate, compared with Hamming ?
Solution
Solution of Exercise 19.9.
The majority is wrong when 2 or 3 copies flip: . At : ; at : ; both the exact column of Output 19.4. At a bit fails with probability , a 4-bit block with , at rate : fewer errors than Hamming’s 0.203% but at rate 0.33 instead of 0.57.
Exercise 19.10 ★★★
Prove the source-coding theorem: , and the bound for blocks of symbols.
Solution
Solution of Exercise 19.10.
Facts used: Gibbs’ inequality; Kraft’s theorem in both directions.
Lower bound: let be the lengths of any prefix code and . With , Gibbs gives . Upper bound: gives , a Kraft sum at most 1, so a prefix code exists, of length ; the optimum is no longer. For blocks of independent symbols the entropy is , so , and per symbol .
Exercise 19.11 ★★★
Prove that every Hamming code, with check bits, has minimum distance 3 and is perfect.
Solution
Solution of Exercise 19.11.
Facts used: the minimum distance of a linear code is the least weight of a nonzero codeword; is a sum of the columns at the 1s of .
A codeword of weight 1 would make a column zero, and one of weight 2 would make two columns equal; neither happens, since the columns are the distinct nonzero vectors. Columns 1, 2 and 3 add to zero (), so a word of weight 3 is a codeword: the distance is exactly 3, and the code corrects . It has and , since has rank (it contains the unit columns). Sphere packing: , equality, so the code is perfect.
Exercise 19.12 ★★★
Prove that a burst of length escapes the generator of degree , with , only when it is a shift of , and deduce the fraction of Output 19.7.
Solution
Solution of Exercise 19.12.
Facts used: , so is coprime with .
A burst of length is with and . As in the theorem, it escapes only if divides ; both have degree , so , and the burst is . Among the bursts of length at one position, the inner bits are free: patterns, one of them . The fraction is for , as printed: 24 of 3,072, one per position.
19.7 Weekend problem
Problem 19.1
Weekend problem — Sending the library catalogue over a noisy line
The library sends its catalogue of titles to the town hall over an old line that flips each bit with probability . This problem compresses the catalogue, adds a Hamming code, and computes and simulates what arrives.
Part I — The source.
- The catalogue has 1,437 symbols over 23 letters. How many bits does a fixed-length code need?
- What does an entropy of 3.99 bits per symbol mean for every lossless code?
- Which symbol carries the most information, and how much?
- How many bits does the Huffman code of single letters take for the whole catalogue, on average per letter as in Output 19.3?
- Why can coding triples of letters not beat 3.99 bits per letter on this source?
- The real titles repeat whole words. Would a model of pairs of letters have lower or higher entropy per letter than the independent model? Why?
Part II — The line.
- What is the capacity of the line?
- The compressed catalogue is about 5,800 bits. How many bit errors are expected with no code?
- What is the probability that it arrives with no error at all?
- Why is a single error in a Huffman-coded stream worse than in a fixed-length one?
- How many channel uses at least does the noisy-channel theorem allow for 5,800 bits sent reliably?
- What would a repetition code of length 3 cost, and what bit error would it leave?
Part III — Hamming (7,4).
- How many 4-bit blocks and channel bits does the coded catalogue use?
- Compute the probability that a block decodes wrongly.
- How many wrong blocks are expected in the catalogue?
- Compare with the uncoded block error of .
- What happens when two bits of one block flip?
- Why can the code not even tell that two bits flipped?
- What do Output 19.6’s measured rates add?
Part IV — The bill.
- Give the rate of the coded transmission and compare it with the capacity.
- Would the Hamming code do better or worse on this line? Compute its block error.
- How would a CRC added to each title help, and what can it not do?
- A burst of 5 bits hits the line. What does Hamming do, and what does a CRC of degree 8 do?
- How could interleaving, sending the first bits of many blocks, then the second bits, turn a burst into single errors?
- Sum up: the bits sent, the expected errors, and what the town hall receives.
Solution
Solution of Problem 19.1.
1. 5 bits per symbol, since : 7,185 bits.
2. No lossless code for this source, modelled as independent letters, averages fewer than 3.99 bits per letter (Theorem 19.5).
3. The rarest, w: 7.03 bits.
4. bits on average.
5. Blocks of independent letters have entropy , and no code beats the entropy.
6. Lower: the letters of real words depend on each other, and knowing one letter makes the next more predictable. The independent model ignores that, so it overestimates.
7. bits per use.
8. .
9. : in practice never.
10. After a flipped bit, the decoder may read a codeword of the wrong length and lose its place, so every symbol after it can be wrong until it falls back in step; a fixed-length code loses one symbol.
11. About .
12. 17,400 channel bits, rate , and a bit error of : about 1.7 wrong bits expected.
13. 1,450 blocks, 10,150 channel bits.
14. .
15. .
16. , about 57 wrong blocks: the code divides the wrong blocks by about 19.
17. The syndrome is the exclusive or of two positions, a third nonzero position; the decoder flips that bit and outputs a wrong block with three errors.
18. Two errors and one error at the third position give the same syndrome; a distance-3 code cannot both correct one error and detect two (that needs distance 4).
19. That the formula is right: 0.2077% measured against 0.2031% computed, within the sampling error of a million blocks.
20. , against a capacity of 0.919: the code spends far more than the theorem requires.
21. Rate , better; its block error is per 11 bits, about 5 wrong blocks of 528 instead of 3 of 1,450.
22. It detects the titles still wrong after decoding, so they can be sent again; it cannot correct them.
23. Hamming corrects one error per block; a burst of 5 spreads over one or two blocks with several errors each, decoded wrongly. A CRC of degree 8 detects every burst of 5 (Theorem 19.13).
24. With depth , consecutive channel bits belong to different blocks, so a burst of at most bits puts at most one error in each block, and each block corrects it.
25. About 5,800 bits of Huffman code become 10,150 channel bits; about 58 bit flips occur on the line, and about 3 blocks of 4 bits arrive wrong; a CRC per title flags them for resending.
Termos definidos neste capítulo
- Binary symmetric channel, channel capacity, repetition code
- Cyclic code, Reed–Solomon code
- Hamming code, perfect code, sphere-packing bound
- Hamming distance, minimum distance, error-correcting code
- Kraft inequality, uniquely decodable code
- Linear code, generator matrix, parity-check matrix, syndrome
- Self-information, entropy of a source