Huffman Codes
In questa pagina 5
A notable application of the greedy paradigm (Greedy Paradigm and Activity Selectionthe greedy paradigm makes the locally best choice immediately, cleans up the instance and solves the single residual subinstance (tail recursion, hence a loop); the code is easy and correctness is not, requiring the greedy choice property and optimal substructure; case study activity selection with the earliest-finish rule, full proof, Theta(n) after sorting, and counterexamples for wrong greedy rules.Greedy Paradigm and Activity Selection →). What matters here is the proof of optimality (greedy choice and substructure) and the complexity with a priority queue.
Character codes and fixed-length codes
A file is a string over an alphabet of characters. A character code assigns to each a binary word (the codeword); the encoding of the file is the concatenation of the words of its characters, The code must be invertible (otherwise information is destroyed) and efficiently computable, with the best possible compression, measured as the bit length of the compressed string against direct encoding (8 bits per ASCII character).
Case study. A file of million ASCII characters (800 Mbit directly) uses only six characters, with frequencies , , , , , . They are obtained by one linear scan of the file and always sum to . The number of occurrences of is .
With six characters 3 bits suffice (): fixed-length code , , , , , . The file takes Mbit (saving over 800), and is compressed and decompressed in linear time. But this code ignores frequencies: the idea is to give shorter words to more frequent characters.
Warning: variable length alone can break invertibility. The code , , , , , would cost only
but it is not injective on strings: daadaa and ee both give 100100. The saving would be illusory, since decompression is impossible.
Prefix codes and tries
Definition (prefix code). A code is prefix-free if no word is a prefix of another.
In the wrong code above is a prefix of and is a prefix of .
Theorem. A prefix code is invertible on strings and is decoded with a single scan, reading bits until a word is met.
Proof. Read from the start the minimum number of bits forming a word: it is the only word with that beginning, because a second word, also a beginning of the same sequence, would be a prefix of the first or vice versa. So the first character is determined; repeat from the next bit.
A fixed-length code is also a prefix code. The condition is sufficient, not necessary, for unique decoding; but restricting to prefix codes loses nothing in average length, by the Kraft-McMillan theorem.
Tree representation
A prefix code is represented by a trie: a binary tree with edges labelled to the left child and to the right child, where each node corresponds to the string of bits along the path from the root.
- words are on the leaves. If a character were on an internal node, its word would be a prefix of the word of a descendant. So the trie has leaves;
- there is a bijection between prefix codes on and binary tries with leaves;
- the depth of in the trie is its word length: .
Decoding with the trie starts at the root, follows 0 left and 1 right for each bit read until a leaf, emits the character and restarts from the root.
Example. With the prefix code , , , , , the string badface becomes , i.e. 1010111110001001101 (19 bits, against for the fixed code).
Cost of a trie
The number of bits of the compressed file is
Definition (trie cost). (average bits per character).
Problem (optimal character code). Given and frequencies , find the prefix code, i.e. the binary trie with leaves, minimizing .
The file is not needed, only the alphabet and the frequencies (like matrix chains, where only dimensions were needed).
The optimal trie is full. A binary tree is full if every internal node has exactly two children. Proof by contradiction: let be optimal with an internal node with one child (say the left) and let be the subtree rooted at (possibly just the leaf ). Contract and into one node: the result is still a trie with the same leaves, hence a valid code, and the edge , i.e. one bit, disappears from the path of every leaf of , which has at least one leaf . Then (frequencies are positive), while for other characters . So , a contradiction.
For example the fixed-length code for 6 characters has a non-full trie (words and unused): it is not optimal. A full binary tree with leaves always has internal nodes (counting edges, , so ).
Cost as a sum over internal nodes. If each node has weight = sum of the frequencies of the leaves below it, then because the frequency of a leaf appears in the weight of each of its proper ancestors. This is the formula for checking a result by hand.
Huffman's algorithm
Idea. Build the trie bottom-up. Start from a forest of trees, one per character (a leaf with its frequency). At each step merge two trees, creating a new root with them as left and right children and with weight the sum of the weights: the forest loses one tree, so after merges one full tree with leaves remains, the trie.
Each merge increases by 1 the depth of all leaves of the two trees, lengthening their words by one bit; the impact on the cost is the weight of the tree. The greedy choice is therefore to merge the two trees of minimum weight.
The implementation uses a priority queue of nodes with key , with insert and extractmin in where is the maximum number of elements. A node has fields left, right, f and char (meaningful only for leaves, which have null left and right).
HUFFMAN(C, f)
n <- |C|
Q <- {}
for c in C do
z <- newnode(); z.f <- f(c); z.char <- c; z.left <- null; z.right <- null
Q.insert(z)
for i <- 1 to n-1 do
x <- Q.extractmin()
y <- Q.extractmin()
z <- newnode()
z.f <- x.f + y.f
z.left <- x; z.right <- y // convention: left is the lighter
Q.insert(z)
return Q.extractmin() // the root of the trieThe words are read from root-to-leaf paths afterwards. Convention: the left child (edge ) is the one extracted first, i.e. of frequency not greater; with equal frequencies the trie may change but the cost does not.
Worked example
Frequencies in percent: , , , , , . The queue at each step:
| step | extracted (left, right) | node created | queue after the step |
|---|---|---|---|
| start | |||
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 |
The trie (numbers are weights; edges are left, right):
(100)
0/ \1
a:45 (55)
0/ \1
(25) (30)
0/ \1 0/ \1
c:12 b:13 (14) d:16
0/ \1
f:5 e:9Words: , , , , , . Cost i.e. Mbit for the file against for the fixed code. Check with internal nodes: (in hundredths). The source entropy is bits, and .
The optimum is not unique. With frequencies there are two valid runs (after merging there are three trees of weight 2): merging the two original 2's gives all words of length 2; merging one of them with the created node gives lengths ; the cost is in both cases.
Complexity
The model counts comparisons between frequencies; .
- The first phase performs insertions, each : (with bottom-up heap construction it would drop to ).
- The loop has iterations, each with 2 extractions and 1 insertion, i.e. .
- The
returnperforms one last extraction.
In total the extractions of the minimum are (for : ), and insertions are . The complexity is . If the characters arrive already sorted by frequency one can drop to with two sorted queues, one for leaves and one for created nodes (which are created in non-decreasing order); sorting the characters costs though.
import heapq, itertools
def huffman(freq): # freq: dict character -> frequency
cnt = itertools.count() # tie-break for the heap: nodes are never compared
Q = [(f, next(cnt), (c,)) for c, f in freq.items()] # a leaf is (character,)
heapq.heapify(Q)
for _ in range(len(freq) - 1):
fx, _, x = heapq.heappop(Q)
fy, _, y = heapq.heappop(Q)
heapq.heappush(Q, (fx + fy, next(cnt), (x, y))) # an internal node is (left, right)
return Q[0][2]
def codes(t, p=""):
if len(t) == 1: return {t[0]: p or "0"}
return {**codes(t[0], p + "0"), **codes(t[1], p + "1")}Correctness
The space of choices is the set of trees of the forest, each with frequency equal to the sum of its leaves; each choice is the pair to merge, and after the merge the two trees are replaced by one of frequency equal to the sum. Each tree of the forest can be seen as a supercharacter with that frequency, whose optimal encoding must be computed: its word will be the common prefix of all leaves of the subtree. The forest after a merge is the residual subinstance, with one character less.
Notation: are the two characters of minimum frequency, for every other ; with is the residual alphabet.
Exchange lemma. Let be two leaves of a trie with and , and let be the trie obtained by swapping the characters and . Then .
Proof. After the swap is at the depth of and vice versa, other characters do not move: since both factors are .
In words: the rarest character can only gain by going deeper, and the most frequent by going up.
Greedy choice property. There is an optimal trie in which and are sibling leaves (children of the same parent) at maximum depth.
Proof. Let be an optimal trie; it is full. Let be the maximum depth and a leaf at depth : its sibling is a leaf (if it had descendants there would be a deeper leaf), at depth .
- If swap and : ( has minimum frequency) and , so by the lemma the cost does not increase. (If call the leaf .) Now is at depth with leaf sibling .
- If swap and : (since and is the rarest among characters other than ) and , so the cost does not increase. The swap does not move , which now has as sibling.
The resulting trie has as siblings at maximum depth and cost , hence, by optimality of , equal: it is optimal.
Optimal substructure property. Let be a trie for in which and are sibling leaves and the trie for obtained by pruning the leaves and : their parent becomes the leaf . Other characters have the same depth in and , and . Therefore This relation holds for every pair and is a bijection: every trie for comes from a unique trie for by making the parent of two leaves . So the minimum of over tries for with siblings is , and by the greedy choice property it is also :
Theorem. returns an optimal trie, for every alphabet with characters.
Proof. Induction on . Base : a single node, the only trie. Step : the first iteration merges into and what remains is exactly the execution of , which by the induction hypothesis (alphabet of characters) returns an optimal trie for . The algorithm returns the trie obtained from by making the parent of . By the cost relation
Once again the code is simple and the correctness proof is the hard part.
Typical exam questions
- The total number of minimum extractions performed by HUFFMAN on an alphabet of characters. Answer: iterations with extractions, plus in the
return: . - Why is the trie of an optimal code full? How many internal nodes does it have? Answer: if an internal node has one child, contracting the edge shortens at least one word by a bit, lowering the cost; a full tree with leaves has internal nodes.
- State and prove the greedy choice property for Huffman. Answer: exchange lemma ; move and onto the two deepest sibling leaves.
Versione ripasso
- Character code , file concatenation of words. Fixed length: bits (6 characters: 3 bits, Mbit out of ). Variable length must stay injective: , , , , , is not (
daadaaandeegive100100), its Mbit is illusory. - Prefix code: no word is a prefix of another, hence unique decoding in one scan (read until a word, the only one with that beginning). It is a binary trie (0 left, 1 right) with words only on leaves; bijection with tries with leaves; .
- Cost: , file bits . The optimal trie is full (if has one child, contract with the child: some leaf loses a bit, drops) and has internal nodes. Also , with the sum of frequencies of the leaves under .
- Problem: given and , find the binary trie with leaves minimizing . Only alphabet and frequencies are needed.
- HUFFMAN: forest of leaves in a priority queue; for :
x <- extractmin,y <- extractmin, nodezwithz.f <- x.f + y.f,z.left <- x,z.right <- y,insert(z); return the lastextractmin. Left is the one of frequency . - Example , , , , , : merges , , , , . Words , , , , , ; ( Mbit against ), equal to the sum of internal nodes . Decoding
badfacegives1010111110001001101. - Complexity: initial
inserts, then iterations with 2extractminand 1insert: in total extractions (for : ) and insertions, each , so . With heapify the initial phase is ; with sorted input and two sorted queues the whole algorithm is . - Non-uniqueness: with frequencies there are two tries with lengths and , both of cost .
- Exchange lemma: if and , swapping and gives (the rarer goes down, the more frequent goes up).
- Greedy choice: the two rarest characters are sibling leaves of maximum depth in some optimal trie. Two swaps: if is not already among the two deepest sibling leaves , swap (, ); then swap (, ). Cost does not grow, so the trie stays optimal.
- Substructure: , . For every trie with siblings, pruned to : , since ; bijection between such and tries for , hence .
- Correctness: induction on ; base ; step: the first merge is the greedy choice, the rest is , optimal by induction, and .
- Typical mistakes: believing fewer bits is better without checking the prefix property; putting a character on an internal node; merges or one extraction too many, or forgetting the one in the
return; putting the heavier node on the left; thinking the optimum is unique; forgetting the term in .