The Kraft Inequality
Short codewords are precious: there are only two codewords of length 1, four of length 2, and using a short one blocks every longer codeword that starts with it. The Kraft inequality turns this into a budget. It tells us exactly which lists of codeword lengths are possible, and it leads directly to the entropy bound for symbol codes.
The inequality
A binary prefix code with codeword lengths exists if and only if
Think of the full binary tree: a codeword of length claims a subtree containing a fraction of all leaves at any deep level. Prefix-freeness means the subtrees do not overlap, so the fractions add to at most 1. A code with is complete: no codeword can be added.
McMillan's theorem extends the inequality to all uniquely decodable codes, so restricting ourselves to prefix codes costs nothing.
import numpy as np
for name, lengths in [("{0, 10, 11}", [1, 2, 2]), ("{0, 10, 110, 111}", [1, 2, 3, 3]),
("lengths 1, 2, 2, 3", [1, 2, 2, 3]), ("lengths 2, 2, 3, 3, 3", [2, 2, 3, 3, 3])]:
k = sum(2.0 ** -l for l in lengths)
status = "complete" if k == 1 else ("possible" if k < 1 else "impossible")
print(f"{name:22s} Kraft sum = {k:.3f} {status}"){0, 10, 11} Kraft sum = 1.000 complete
{0, 10, 110, 111} Kraft sum = 1.000 complete
lengths 1, 2, 2, 3 Kraft sum = 1.125 impossible
lengths 2, 2, 3, 3, 3 Kraft sum = 0.875 possible
Building a code from lengths
The proof of the "if" direction is constructive: sort the lengths, and give each symbol the next available codeword of its length (a canonical code). This is how DEFLATE transmits Huffman codes: only the lengths are sent.
def canonical_code(lengths):
assert sum(2.0 ** -l for l in lengths) <= 1, "Kraft inequality violated"
order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
code, value, prev = {}, 0, lengths[order[0]]
for i in order:
value <<= lengths[i] - prev; prev = lengths[i]
code[i] = format(value, f"0{lengths[i]}b")
value += 1
return code
for lengths in ([2, 1, 3, 3], [3, 3, 2, 2, 3, 4, 4]):
print(lengths, "->", canonical_code(lengths))[2, 1, 3, 3] -> {1: '0', 0: '10', 2: '110', 3: '111'}
[3, 3, 2, 2, 3, 4, 4] -> {2: '00', 3: '01', 0: '100', 1: '101', 4: '110', 5: '1110', 6: '1111'}
The entropy bound
For any uniquely decodable code, the expected length is at least the entropy:
Proof. Let and define . Then and
using Gibbs' inequality and . Equality needs and , that is, exactly (Optimal Code Lengths).
import numpy as np
P = np.array([0.4, 0.3, 0.2, 0.1])
H = -np.sum(P * np.log2(P))
rng = np.random.default_rng(0)
best = np.inf
for _ in range(20000):
lengths = rng.integers(1, 7, size=4)
if np.sum(2.0 ** -lengths) <= 1:
best = min(best, float(P @ lengths))
print(f"entropy {H:.4f}; shortest expected length among random valid length lists: {best:.4f}")entropy 1.8464; shortest expected length among random valid length lists: 1.9000
The best lengths, , give 1.9 bits, about 0.05 above the entropy, because the probabilities are not powers of .
In software
- Canonical codes need only the length list in the header; both sides rebuild the same code with the function above. DEFLATE, JPEG and many formats do this.
- A decoder can check a received length list with the Kraft sum before building the code, rejecting corrupt headers.
Exercises
Exercise 1: Possible?
Can a prefix code have lengths ?
Answer
No.
Solution
.
Exercise 2: Room for more
A prefix code has lengths . How many more codewords of length 3 can be added?
Answer
Solution
The Kraft sum is . The remaining fits three codewords of length 3.
Exercise 3: Canonical code (code)
Build the canonical code for lengths .
Answer
Symbols 1, 3, 4 get 00, 01, 10; symbols 0, 2 get 110, 111.
Solution
def canonical_code(lengths):
order = sorted(range(len(lengths)), key=lambda i: (lengths[i], i))
code, value, prev = {}, 0, lengths[order[0]]
for i in order:
value <<= lengths[i] - prev; prev = lengths[i]
code[i] = format(value, f"0{lengths[i]}b")
value += 1
return dict(sorted(code.items()))
print(canonical_code([3, 2, 3, 2, 2])){0: '110', 1: '00', 2: '111', 3: '01', 4: '10'}
Test yourself
A prefix code with lengths exists if and only if…
- all are distinct
McMillan's theorem says that…
- uniquely decodable codes satisfy the Kraft inequality too
- Huffman codes are optimal
- every code is prefix-free
- arithmetic coding beats entropy
The expected length of any uniquely decodable code is at least…
- the entropy
- the number of symbols
- 1 bit
- the raw bit content