Ciência da computação · Livro 5 · Graduação — Ano 3

University Computer Science — Year 3

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 p1,…,pnp_1, \ldots, p_n is ∑ipilog⁡2(1/pi)\sum_i p_i \log_2 (1/p_i) (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 1+1=01 + 1 = 0, 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 xx with probability p(x)p(x). The self-information of an outcome of probability pp is log⁡2(1/p)\log_2 (1/p) bits. The entropy of a source is the expected self-information of a symbol, H=∑xp(x)log⁡2(1/p(x))H = \sum_x p(x) \log_2 (1/p(x)) bits per symbol. The block entropy HkH_k is the entropy of blocks of kk symbols taken as one symbol; for a source of independent symbols, Hk=kHH_k = kH.

A rare outcome carries much information, a certain one none, and the information of two independent outcomes adds, since log⁡2(1/(pq))=log⁡2(1/p)+log⁡2(1/q)\log_2 (1/(pq)) = \log_2 (1/p) + \log_2 (1/q). 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()}
Listing 19.1. Entropy, and the frequencies of blocks of symbols. code/bachelor-3/19-information-and-codes/listings/entropy.py
$ 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
Output 19.1. The catalogue’s letters: the space is the commonest 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 log⁡2n\log_2 n)

For distributions pp and qq on the same nn symbols, ∑xp(x)log⁡2(1/q(x))≥∑xp(x)log⁡2(1/p(x))\sum_x p(x) \log_2 (1/q(x)) \ge \sum_x p(x) \log_2 (1/p(x)), with equality only when p=qp = q. In particular H≤log⁡2nH \le \log_2 n, with equality only for the uniform source.

Proof. Using ln⁡t≤t−1\ln t \le t - 1, with equality only at t=1t = 1, the difference is ∑xp(x)log⁡2(q(x)/p(x))≤1ln⁡2∑xp(x)(q(x)/p(x)−1)=1ln⁡2(∑xq(x)−1)≤0\sum_x p(x) \log_2 (q(x)/p(x)) \le \frac{1}{\ln 2} \sum_x p(x) \bigl(q(x)/p(x) - 1\bigr) = \frac{1}{\ln 2} \bigl(\sum_x q(x) - 1\bigr) \le 0, sums over the xx with p(x)>0p(x) > 0. Take qq uniform: ∑xp(x)log⁡2n=log⁡2n≥H\sum_x p(x) \log_2 n = \log_2 n \ge H. ∎

For two symbols with probabilities pp and 1−p1 - p the entropy is the binary entropy function h(p)=plog⁡2(1/p)+(1−p)log⁡2(1/(1−p))h(p) = p \log_2 (1/p) + (1 - p) \log_2 (1/(1 - p)): zero at p=0p = 0 and p=1p = 1, and one bit at p=1/2p = 1/2.

The binary entropy function and the capacity 1 - h(p) of the binary symmetric channel of .
The binary entropy function and the capacity 1−h(p)1 - h(p) of the binary symmetric channel of Section 19.3.

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 ℓ1,…,ℓn\ell_1, \ldots, \ell_n satisfy the Kraft inequality when ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \le 1.

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 ℓ\ell claims the fraction 2−ℓ2^{-\ell} 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
Listing 19.2. The Kraft sum, a prefix test, and the canonical code for given lengths. code/bachelor-3/19-information-and-codes/listings/kraft.py
$ 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
Output 19.2. A Kraft sum of 1 is not enough to be a prefix code; it is enough for some prefix code with those lengths to exist.

Theorem 19.5 (Source-coding theorem)

For a source of entropy HH, the least expected length L∗L^* of a prefix code for its symbols satisfies H≤L∗<H+1H \le L^* < H + 1. Coding blocks of kk symbols at once gives an expected length per symbol below H+1/kH + 1/k.

The lower bound is Gibbs’ inequality with q(x)=2−ℓ(x)q(x) = 2^{-\ell(x)}; the upper bound takes ℓ(x)=⌈log⁡2(1/p(x))⌉\ell(x) = \lceil \log_2 (1/p(x)) \rceil, which satisfies Kraft (Exercise 19.10). Huffman’s code is optimal, so its length is L∗L^*. 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
Listing 19.3. The lengths of a Huffman code: each merge adds one bit to every symbol beneath it. code/bachelor-3/19-information-and-codes/listings/huffman_vs_h.py
$ 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
Output 19.3. Huffman against the entropy: within 0.04 bits per letter for single letters, and closer with blocks, as the theorem says; the bound 1/k1/k is far from reached.

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 log⁡223≈4.52\log_2 23 \approx 4.52 with blocks.

19.3 Channels

Definition 19.6 (Binary symmetric channel, channel capacity, repetition code)

The binary symmetric channel with crossover probability pp transmits bits, flipping each independently with probability pp. Its channel capacity is C=1−h(p)C = 1 - h(p) bits per use. A code of rate k/nk/n sends kk bits of message in nn uses of the channel. The repetition code of length nn sends each bit nn times, rate 1/n1/n, and decodes by majority.

The binary symmetric channel: each bit arrives intact with probability 1 - p and flipped with probability p.
The binary symmetric channel: each bit arrives intact with probability 1−p1 - p and flipped with probability pp.

Theorem 19.7 (Noisy-channel coding theorem)

For every rate R<CR < C and every ε>0\varepsilon > 0 there are codes of rate at least RR whose probability of decoding a block wrongly is below ε\varepsilon; 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))
Listing 19.4. The channel, and the exact error of majority decoding. code/bachelor-3/19-information-and-codes/listings/bsc.py
$ 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
Output 19.4. Repetition codes over a seeded channel, 100,000 bits each: the measured rates agree with the exact ones.
$ 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
Output 19.5. Capacity of the binary symmetric channel.

At p=0.1p = 0.1 the capacity is 0.53 bits per use, so codes of rate 1/21/2 with errors as rare as wanted exist; the repetition code of rate 1/51/5 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 tt errors when nearest-codeword decoding recovers the sent word whenever at most tt bits are flipped.

Theorem 19.9 (Detection and correction)

A code of minimum distance dd detects every pattern of at most d−1d - 1 errors and corrects every pattern of at most ⌊(d−1)/2⌋\lfloor (d - 1)/2 \rfloor.

The distance is a metric, so the balls of radius ⌊(d−1)/2⌋\lfloor (d - 1)/2 \rfloor around the codewords are disjoint, and fewer than dd 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 nn and dimension kk is a subspace of F2n\mathbb{F}_2^n of dimension kk, F2\mathbb{F}_2 being the field with two elements: the sum of two codewords, bit by bit modulo 2, is a codeword. A generator matrix is a k×nk \times n matrix GG whose rows are a basis: the message mm encodes to mGmG. A parity-check matrix is an (n−k)×n(n - k) \times n matrix HH with Hc=0Hc = 0 exactly for the codewords cc. The syndrome of a received word rr is HrHr.

If r=c+er = c + e, the syndrome is H(c+e)=HeH(c + e) = He: 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 c−c′c - c' is a codeword of weight equal to their distance.

Definition 19.11 (Hamming code, perfect code, sphere-packing bound)

The Hamming code with rr check bits has length n=2r−1n = 2^r - 1 and a parity-check matrix whose columns are the nn nonzero vectors of F2r\mathbb{F}_2^r, column jj being jj written in binary. The sphere-packing bound: a code of MM words of length nn correcting tt errors has M∑i=0t(ni)≤2nM \sum_{i=0}^{t} \binom{n}{i} \le 2^n. A code meeting it with equality is a perfect code.

The bound holds because the balls of radius tt around the codewords are disjoint and each holds ∑i≤t(ni)\sum_{i \le t} \binom{n}{i} words of F2n\mathbb{F}_2^n. For r=3r = 3 the Hamming code is the (7,4)(7, 4) code: a single error at position jj has syndrome column jj, which is jj in binary, so the receiver flips bit jj 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

G=(1110000100110001010101101001).G = \begin{pmatrix} 1&1&1&0&0&0&0\\ 1&0&0&1&1&0&0\\ 0&1&0&1&0&1&0\\ 1&1&0&1&0&0&1 \end{pmatrix}.

With 16 codewords and balls of 1+7=81 + 7 = 8 words, 16×8=128=2716 \times 8 = 128 = 2^7: the (7,4)(7, 4) 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.

The (7, 4) Hamming code as three circles. A single flipped bit makes exactly the circles that contain it odd, and the set of odd circles names its position: that set is the syndrome.
The (7,4)(7, 4) Hamming code as three circles. A single flipped bit makes exactly the circles that contain it odd, and the set of odd circles names its position: that set is the syndrome.
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]
Listing 19.5. Hamming (7,4)(7, 4): encode, compute the syndrome, correct. code/bachelor-3/19-information-and-codes/listings/hamming74.py
$ 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%
Output 19.6. One flipped bit at position 5 is found and corrected; the minimum distance is 3; and a million 4-bit blocks over the channel with p=0.01p = 0.01.

At p=0.01p = 0.01 an uncoded block of four bits is wrong with probability 1−0.994≈3.94%1 - 0.99^4 \approx 3.94\%. The Hamming code fails only when two or more of its seven bits flip, with probability 1−0.997−7×0.01×0.996≈0.203%1 - 0.99^7 - 7 \times 0.01 \times 0.99^6 \approx 0.203\%, at rate 4/74/7; the simulation agrees.

19.5 Cyclic codes

Definition 19.12 (Cyclic code, Reed–Solomon code)

Read a word c0c1⋯cn−1c_0 c_1 \cdots c_{n-1} as the polynomial c0+c1x+⋯+cn−1xn−1c_0 + c_1 x + \cdots + c_{n-1} x^{n-1} with coefficients in F2\mathbb{F}_2. A cyclic code is a linear code closed under rotating its words by one place; its codewords are the multiples of a generator polynomial gg that divides xn−1x^n - 1. 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 mm of degree below kk is sent as m(x)xr+(m(x)xr mod g(x))m(x) x^r + (m(x) x^r \bmod g(x)), a multiple of gg, and the receiver checks that the remainder of what it receives is zero. Over F2\mathbb{F}_2 subtraction is exclusive or, so long division is a loop of shifts and XORs. A burst of length bb is an error pattern whose first and last flipped bits are b−1b - 1 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)
Listing 19.6. Remainder and encoding over F2\mathbb{F}_2, with the generator x8+x2+x+1x^8 + x^2 + x + 1. code/bachelor-3/19-information-and-codes/listings/crc_poly.py

Theorem 19.13 (Burst detection)

If the generator gg has degree rr and a nonzero constant term, every burst of length at most rr is detected.

Proof. A burst of length b≤rb \le r starting at position ii is e(x)=xiu(x)e(x) = x^i u(x) with u(0)=1u(0) = 1 and deg⁡u=b−1<r\deg u = b - 1 < r. It goes undetected only if gg divides xiu(x)x^i u(x). Since g(0)=1g(0) = 1, gg has no factor in common with xix^i, so gg would divide uu, 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 r+1=9r + 1 = 9 is missed only when it equals gg shifted, one pattern in 272^7, and longer bursts one in 282^8.

$ 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
Output 19.7. Every burst of up to 8 bits is caught; longer bursts escape at the rates 2−72^{-7} and 2−82^{-8}.

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 1/21/2 and each other face with probability 1/101/10. Which is larger, and why must it be?

Solution

Solution of Exercise 19.1.

Fair die: log⁡26≈2.585\log_2 6 \approx 2.585 bits. Loaded die: 12log⁡22+5×110log⁡210=0.5+0.5log⁡210≈2.161\frac12 \log_2 2 + 5 \times \frac{1}{10} \log_2 10 = 0.5 + 0.5 \log_2 10 \approx 2.161 bits. The fair die has more: by Theorem 19.2 the uniform distribution is the only one reaching log⁡26\log_2 6.

Exercise 19.2 ★

For each code, give its Kraft sum and say whether it is prefix-free: {0,10,11}\{0, 10, 11\}; {1,01,001,000}\{1, 01, 001, 000\}; {0,10,01}\{0, 10, 01\}; {00,01,100,101,11}\{00, 01, 100, 101, 11\}.

Solution

Solution of Exercise 19.2.

{0,10,11}\{0, 10, 11\}: sum 1/2+1/4+1/4=11/2 + 1/4 + 1/4 = 1, prefix-free. {1,01,001,000}\{1, 01, 001, 000\}: sum 1, prefix-free. {0,10,01}\{0, 10, 01\}: sum 1, not prefix-free, since 0 begins 01; it is not even uniquely decodable, as 010 reads 0,10 or 01,0. {00,01,100,101,11}\{00, 01, 100, 101, 11\}: sum 1/4+1/4+1/8+1/8+1/4=11/4 + 1/4 + 1/8 + 1/8 + 1/4 = 1, 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, 1⊕2⊕3⊕5=51 \oplus 2 \oplus 3 \oplus 5 = 5. Flipping bit 5 gives 1110000, the codeword of 1000, the first row of GG.

Exercise 19.5 ★★

exercises/ex5_syndrome.py decodes Hamming (7,4)(7, 4) 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 ii of the syndrome by ii, as in Listing 19.5.

Exercise 19.6 ★★

Write encode15 and decode15 for the Hamming (15,11)(15, 11) 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 2i2^i is the sum of the data bits whose position has bit ii 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; 2−ℓ2^{-\ell} is the fraction of bit strings of a fixed length L≥ℓL \ge \ell that begin with a given word of length ℓ\ell.

Let LL be the longest length. A codeword of length ℓi\ell_i begins 2L−ℓi2^{L - \ell_i} strings of length LL, and these sets are disjoint for a prefix code, since a common string would make one codeword a prefix of the other. So ∑i2L−ℓi≤2L\sum_i 2^{L - \ell_i} \le 2^L. Conversely, for lengths in increasing order with Kraft sum at most 1, give the ii-th word the first ℓi\ell_i bits of the binary expansion of ∑j<i2−ℓj\sum_{j < i} 2^{-\ell_j}, which is below 1. Two words j<ij < i: the interval of numbers beginning with word jj has width 2−ℓj2^{-\ell_j}, and word ii’s value lies at or beyond its end, so word jj is not a prefix of word ii. 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 aa into cc through bb changes at most d(a,b)+d(b,c)d(a, b) + d(b, c) positions.

Detection: a pattern of 1≤e≤d−11 \le e \le d - 1 errors turns codeword cc into rr with 0<d(c,r)<d0 < d(c, r) < d, so rr is not a codeword, and the receiver sees the error. Correction: let t=⌊(d−1)/2⌋t = \lfloor (d - 1)/2 \rfloor, so 2t<d2t < d. If d(c,r)≤td(c, r) \le t and c′c' is another codeword, d(c′,r)≥d(c,c′)−d(c,r)≥d−t>td(c', r) \ge d(c, c') - d(c, r) \ge d - t > t, so cc is the unique nearest codeword.

Exercise 19.9 ★★

Compute the probability that the repetition code of length 3 decodes a bit wrongly at p=0.05p = 0.05 and p=0.2p = 0.2, and check against Output 19.4. What is the probability that a 4-bit block sent with it arrives wrong at p=0.01p = 0.01, and at what rate, compared with Hamming (7,4)(7, 4)?

Solution

Solution of Exercise 19.9.

The majority is wrong when 2 or 3 copies flip: 3p2(1−p)+p33p^2(1 - p) + p^3. At p=0.05p = 0.05: 0.007125+0.000125=0.007250.007125 + 0.000125 = 0.00725; at p=0.2p = 0.2: 0.096+0.008=0.1040.096 + 0.008 = 0.104; both the exact column of Output 19.4. At p=0.01p = 0.01 a bit fails with probability 0.0002980.000298, a 4-bit block with 1−(1−0.000298)4≈0.119%1 - (1 - 0.000298)^4 \approx 0.119\%, at rate 1/31/3: fewer errors than Hamming’s 0.203% but at rate 0.33 instead of 0.57.

Exercise 19.10 ★★★

Prove the source-coding theorem: H≤L∗<H+1H \le L^* < H + 1, and the bound H+1/kH + 1/k for blocks of kk symbols.

Solution

Solution of Exercise 19.10.

Facts used: Gibbs’ inequality; Kraft’s theorem in both directions.

Lower bound: let ℓ(x)\ell(x) be the lengths of any prefix code and S=∑x2−ℓ(x)≤1S = \sum_x 2^{-\ell(x)} \le 1. With q(x)=2−ℓ(x)/Sq(x) = 2^{-\ell(x)}/S, Gibbs gives H≤∑xp(x)log⁡2(1/q(x))=∑xp(x)ℓ(x)+log⁡2S≤LH \le \sum_x p(x) \log_2 (1/q(x)) = \sum_x p(x) \ell(x) + \log_2 S \le L. Upper bound: ℓ(x)=⌈log⁡2(1/p(x))⌉\ell(x) = \lceil \log_2 (1/p(x)) \rceil gives 2−ℓ(x)≤p(x)2^{-\ell(x)} \le p(x), a Kraft sum at most 1, so a prefix code exists, of length ∑xp(x)ℓ(x)<∑xp(x)(log⁡2(1/p(x))+1)=H+1\sum_x p(x) \ell(x) < \sum_x p(x) (\log_2 (1/p(x)) + 1) = H + 1; the optimum L∗L^* is no longer. For blocks of kk independent symbols the entropy is kHkH, so kH≤Lk∗<kH+1kH \le L_k^* < kH + 1, and per symbol Lk∗/k<H+1/kL_k^*/k < H + 1/k.

Exercise 19.11 ★★★

Prove that every Hamming code, with r≥2r \ge 2 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; Hc=0Hc = 0 is a sum of the columns at the 1s of cc.

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 (1⊕2=31 \oplus 2 = 3), so a word of weight 3 is a codeword: the distance is exactly 3, and the code corrects t=1t = 1. It has n=2r−1n = 2^r - 1 and k=n−rk = n - r, since HH has rank rr (it contains the rr unit columns). Sphere packing: 2k(1+n)=2n−r2r=2n2^k (1 + n) = 2^{n - r} 2^r = 2^n, equality, so the code is perfect.

Exercise 19.12 ★★★

Prove that a burst of length r+1r + 1 escapes the generator gg of degree rr, with g(0)=1g(0) = 1, only when it is a shift of gg, and deduce the fraction 2−(r−1)2^{-(r-1)} of Output 19.7.

Solution

Solution of Exercise 19.12.

Facts used: g(0)=1g(0) = 1, so gg is coprime with xix^i.

A burst of length r+1r + 1 is xib(x)x^i b(x) with deg⁡b=r\deg b = r and b(0)=1b(0) = 1. As in the theorem, it escapes only if gg divides bb; both have degree rr, so b=gb = g, and the burst is xig(x)x^i g(x). Among the bursts of length r+1r + 1 at one position, the r−1r - 1 inner bits are free: 2r−12^{r - 1} patterns, one of them gg. The fraction is 2−(r−1)=2−7≈0.00782^{-(r-1)} = 2^{-7} \approx 0.0078 for r=8r = 8, 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 p=0.01p = 0.01. This problem compresses the catalogue, adds a Hamming code, and computes and simulates what arrives.

Part I — The source.

  1. The catalogue has 1,437 symbols over 23 letters. How many bits does a fixed-length code need?
  2. What does an entropy of 3.99 bits per symbol mean for every lossless code?
  3. Which symbol carries the most information, and how much?
  4. How many bits does the Huffman code of single letters take for the whole catalogue, on average per letter as in Output 19.3?
  5. Why can coding triples of letters not beat 3.99 bits per letter on this source?
  6. 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.

  1. What is the capacity of the line?
  2. The compressed catalogue is about 5,800 bits. How many bit errors are expected with no code?
  3. What is the probability that it arrives with no error at all?
  4. Why is a single error in a Huffman-coded stream worse than in a fixed-length one?
  5. How many channel uses at least does the noisy-channel theorem allow for 5,800 bits sent reliably?
  6. What would a repetition code of length 3 cost, and what bit error would it leave?

Part III — Hamming (7,4).

  1. How many 4-bit blocks and channel bits does the coded catalogue use?
  2. Compute the probability that a block decodes wrongly.
  3. How many wrong blocks are expected in the catalogue?
  4. Compare with the uncoded block error of 1−0.9941 - 0.99^4.
  5. What happens when two bits of one block flip?
  6. Why can the code not even tell that two bits flipped?
  7. What do Output 19.6’s measured rates add?

Part IV — The bill.

  1. Give the rate of the coded transmission and compare it with the capacity.
  2. Would the (15,11)(15, 11) Hamming code do better or worse on this line? Compute its block error.
  3. How would a CRC added to each title help, and what can it not do?
  4. A burst of 5 bits hits the line. What does Hamming (7,4)(7, 4) do, and what does a CRC of degree 8 do?
  5. How could interleaving, sending the first bits of many blocks, then the second bits, turn a burst into single errors?
  6. 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 24=16<23≤322^4 = 16 < 23 \le 32: 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. 4.0292×1,437≈5,7904.0292 \times 1{,}437 \approx 5{,}790 bits on average.

5. Blocks of independent letters have entropy 3H3H, 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. 1−h(0.01)=0.91921 - h(0.01) = 0.9192 bits per use.

8. 5,800×0.01=585{,}800 \times 0.01 = 58.

9. 0.995,800≈5×10−260.99^{5{,}800} \approx 5 \times 10^{-26}: 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 5,800/0.9192≈6,3105{,}800 / 0.9192 \approx 6{,}310.

12. 17,400 channel bits, rate 1/31/3, and a bit error of 0.0002980.000298: about 1.7 wrong bits expected.

13. 1,450 blocks, 10,150 channel bits.

14. 1−0.997−7×0.01×0.996≈0.203%1 - 0.99^7 - 7 \times 0.01 \times 0.99^6 \approx 0.203\%.

15. 1,450×0.00203≈2.91{,}450 \times 0.00203 \approx 2.9.

16. 3.94%3.94\%, 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. 4/7≈0.5714/7 \approx 0.571, against a capacity of 0.919: the code spends far more than the theorem requires.

21. Rate 11/15≈0.73311/15 \approx 0.733, better; its block error is 1−0.9915−15×0.01×0.9914≈0.96%1 - 0.99^{15} - 15 \times 0.01 \times 0.99^{14} \approx 0.96\% 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 (7,4)(7, 4) 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 DD, consecutive channel bits belong to DD different blocks, so a burst of at most DD 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

Ver todos os 1050 termos do glossário