library(tidyverse)5 Huffman coding
5.1 Introduction
In 1951 David Huffman was a graduate student at MIT, taking Robert Fano’s course on information theory. Fano offered his students a choice: sit the final exam, or write a term paper on a hard problem, which was to find the most efficient way to represent symbols with binary codes. Huffman nearly gave up on the paper. Then he found a construction so simple, and so provably optimal, that it beat the method his professor had worked on (Stix 1991). He published it the next year (Huffman 1952), and more than seventy years later it is inside every zip file, PNG image and JPEG photograph.
The idea is the one Morse code had a century earlier: give the common symbols short codes and the rare ones long codes. In English, E is the most common letter, and its Morse code is a single dot. But Morse code needs pauses between letters, because some codes are the beginnings of others. Huffman’s codes are prefix codes: no code is the start of any other, so a stream of bits can be decoded without separators. And among all prefix codes for a given set of probabilities, no other has a shorter average length.
Prerequisites
The examples use the photon counts from Chapter 4, regenerated with the same seed:
set.seed(1948)
photons <- tibble(count = rpois(1e6, lambda = 2.5))
frequencies <- photons |>
count(count) |>
mutate(p = n / sum(n))5.2 Building the code
Huffman’s construction works from the bottom up. Treat each symbol as a node weighted by its probability. Take the two lightest nodes and merge them into one, whose weight is their sum; every symbol inside the first gets a 0 added to the front of its code, and every symbol inside the second gets a 1. Repeat until one node is left. The two rarest symbols end up with the longest codes, because they are merged first and then pick up a bit at every later merge.
Each merge depends on the result of the one before, so this is one of the sequential jobs that Chapter 3 said should stay a loop:
huffman_code <- function(symbol, weight) {
symbol <- as.character(symbol)
code <- setNames(rep("", length(symbol)), symbol)
nodes <- tibble(members = as.list(symbol), weight = weight)
while (nrow(nodes) > 1) {
nodes <- arrange(nodes, weight)
first <- nodes$members[[1]]
second <- nodes$members[[2]]
code[first] <- paste0("0", code[first])
code[second] <- paste0("1", code[second])
nodes <- nodes |>
slice(-(1:2)) |>
add_row(members = list(c(first, second)), weight = sum(nodes$weight[1:2]))
}
tibble(symbol = symbol, weight = weight, code = unname(code[symbol]))
}Each row of nodes holds a list of the symbols beneath it and their total weight, and code accumulates the bits. Here is the code for the photon counts:
photon_code <- huffman_code(frequencies$count, frequencies$p) |>
mutate(length = nchar(code))
photon_code
#> # A tibble: 14 × 4
#> symbol weight code length
#> <chr> <dbl> <chr> <int>
#> 1 0 0.0823 1110 4
#> 2 1 0.205 00 2
#> 3 2 0.256 10 2
#> 4 3 0.215 01 2
#> 5 4 0.133 110 3
#> 6 5 0.0671 11111 5
#> 7 6 0.0277 111101 6
#> 8 7 0.00980 1111001 7
#> 9 8 0.00306 11110001 8
#> 10 9 0.000829 111100001 9
#> 11 10 0.000186 1111000001 10
#> 12 11 0.000064 11110000001 11
#> 13 12 0.000008 111100000001 12
#> 14 13 0.000001 111100000000 12The most likely counts, 1, 2 and 3, get two-bit codes. A count of 13, seen once in a million readings, gets a twelve-bit code, and it does not matter, because it almost never has to be sent. Check the prefix property for yourself: no code in the table is the beginning of another.
Shannon’s theory says a symbol of probability p ideally deserves −log2 p bits. Huffman’s lengths are whole numbers, so they can only approximate that ideal, rounding some lengths up and others down:
photon_code |>
mutate(ideal_bits = -log2(weight)) |>
ggplot(aes(x = ideal_bits, y = length)) +
geom_abline(linetype = "dashed", colour = "grey50") +
geom_point(size = 2) +
coord_equal() +
labs(x = "Ideal length, -log2(p) (bits)", y = "Huffman code length (bits)")
5.3 Encoding and decoding
Encoding is a lookup and a paste. Here are the first twenty readings and their encoding:
lookup <- setNames(photon_code$code, photon_code$symbol)
first_counts <- photons$count[1:20]
first_counts
#> [1] 3 3 6 3 1 5 3 5 0 4 2 4 2 4 2 2 2 0 2 2
bits <- paste(lookup[as.character(first_counts)], collapse = "")
bits
#> [1] "010111110101001111101111111110110101101011010101011101010"
nchar(bits)
#> [1] 57Twenty readings in 57 bits, against 160 bits at one byte each. Decoding reads the bits one at a time and emits a symbol as soon as the bits so far match a code. The prefix property guarantees the first match is the right one:
decode_huffman <- function(bits, codes) {
symbol_of <- setNames(codes$symbol, codes$code)
out <- character(nchar(bits))
n_out <- 0
current <- ""
for (b in strsplit(bits, "")[[1]]) {
current <- paste0(current, b)
if (current %in% names(symbol_of)) {
n_out <- n_out + 1
out[n_out] <- symbol_of[[current]]
current <- ""
}
}
as.integer(out[seq_len(n_out)])
}
decoded <- decode_huffman(bits, photon_code)
identical(decoded, first_counts)
#> [1] TRUE5.4 How close to the floor?
The average number of bits per reading is each code’s length weighted by its probability. Compare it with the entropy:
photon_code |>
summarise(
huffman_bits = sum(weight * length),
entropy_bits = -sum(weight * log2(weight))
)
#> # A tibble: 1 × 2
#> huffman_bits entropy_bits
#> <dbl> <dbl>
#> 1 2.69 2.64The Huffman code comes within about two percent of the entropy, closer than any of the general-purpose compressors in Chapter 4, the best of which, xz, needed 2.86 bits per reading. That is no slight on xz. The Huffman code was built from the true frequencies, known in advance, and the cost of sending the code table along with the data has been left out. xz had to discover the statistics as it went and record everything a decoder would need. Real formats that use Huffman codes, like DEFLATE (Chapter 7), send the table too, in a compact form that lists only the code lengths.
Huffman proved that his average length L always satisfies \(H \le L < H + 1\). The extra bit in the worst case comes from rounding to whole bits, and it hurts when one symbol is very likely. A detector channel that fires in 10% of readings has an entropy of 0.47 bits per reading, but the shortest possible code for a single yes-or-no is one bit, more than twice the entropy. The cure is to code blocks of symbols. With pairs of readings there are four possible blocks, each with its own probability, and a Huffman code over the four can give the common block (no hit, no hit) a one-bit code shared by two readings:
block_huffman_bits <- function(block_size, p_hit) {
blocks <- expand.grid(rep(list(c(0, 1)), block_size)) # every possible block
hits <- rowSums(blocks)
p_block <- p_hit^hits * (1 - p_hit)^(block_size - hits)
code <- huffman_code(seq_along(p_block), p_block)
sum(p_block * nchar(code$code)) / block_size
}
tibble(block_size = 1:8) |>
mutate(
bits_per_reading = map_dbl(block_size, block_huffman_bits, p_hit = 0.1),
entropy_bits = -0.1 * log2(0.1) - 0.9 * log2(0.9)
)
#> # A tibble: 8 × 3
#> block_size bits_per_reading entropy_bits
#> <int> <dbl> <dbl>
#> 1 1 1 0.469
#> 2 2 0.645 0.469
#> 3 3 0.533 0.469
#> 4 4 0.493 0.469
#> 5 5 0.480 0.469
#> 6 6 0.470 0.469
#> 7 7 0.474 0.469
#> 8 8 0.476 0.469The cost per reading falls toward the entropy as the blocks grow, though not quite steadily, at the price of a code table that doubles in size with every extra reading per block. Modern compressors take a cleaner route to the same goal. Arithmetic coding, and its fast modern relative, asymmetric numeral systems (Duda 2013), effectively spend fractional numbers of bits on each symbol. xz uses a form of arithmetic coding called range coding (Chapter 9), and Zstandard uses asymmetric numeral systems alongside Huffman coding (Chapter 10).
5.5 Where Huffman codes live
Huffman coding is the final stage of DEFLATE, and so of every gzip file, zip archive and PNG image (Chapter 7). It is the last step of bzip2 (Chapter 8). Baseline JPEG uses it, and so do MP3 audio, Brotli, Zstandard (for literal bytes) and the HTTP/2 standard for compressing web headers. A method published in 1952, which needs no more than a sort and a loop, is still one of the most widely run algorithms on Earth. That is what durable looks like.
5.6 Summary
A Huffman code gives each symbol a prefix-free binary code whose length tracks −log2 p, and among all prefix codes no other has a shorter average length. You built one with a short loop that merges the two lightest nodes until one remains, used it to encode and decode photon counts, and found it within about two percent of Shannon’s entropy, because it was built from the known probabilities. Its weakness is whole-bit lengths, which waste up to a bit per symbol when one symbol dominates; coding blocks of symbols fixes that, and arithmetic coding and asymmetric numeral systems fix it more elegantly.
5.7 Exercises
- Build a Huffman code for the letters and spaces of a sentence of your choice, using
strsplit()to split it into characters. Compare the average code length with the entropy of the letters and with the 8 bits per character of plain ASCII. - Huffman codes are not unique: swapping
0and1at any merge gives a different code with the same lengths. Changehuffman_code()to break ties between equal weights differently and confirm that the average length does not change. - Build a Huffman code for the
runcolumn of the dimuon data. Why are all the code lengths 3 bits? - The magnetometer differences from Chapter 4 take 77 distinct values with an entropy of about 5.1 bits. Build their Huffman code and compare its average length with the entropy and with xz’s 5.9 bits per reading.
- For a detector channel that fires with probability 0.01, how large must the blocks be before the Huffman code comes within 5% of the entropy? How many entries does the code table have at that size?