Salta al contenuto
Note per Studenti Huffman Codes Report

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 FF is a string over an alphabet CC of characters. A character code assigns to each c∈Cc \in C a binary word e(c)e(c) (the codeword); the encoding of the file is the concatenation of the words of its characters, e(x1x2⋯xn)=e(x1) e(x2)⋯e(xn).e(x_1 x_2 \cdots x_n) = e(x_1)\, e(x_2) \cdots e(x_n). 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 100100 million ASCII characters (800 Mbit directly) uses only six characters, with frequencies f(a)=0.45f(a)=0.45, f(b)=0.13f(b)=0.13, f(c)=0.12f(c)=0.12, f(d)=0.16f(d)=0.16, f(e)=0.09f(e)=0.09, f(f)=0.05f(f)=0.05. They are obtained by one linear scan of the file and always sum to 11. The number of occurrences of cc is f(c)⋅∣F∣f(c) \cdot \lvert F \rvert.

With six characters 3 bits suffice (23=8≥62^3 = 8 \ge 6): fixed-length code a=000a=000, b=001b=001, c=010c=010, d=011d=011, e=100e=100, f=101f=101. The file takes 300300 Mbit (saving 62.5%62.5\% 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 a=0a=0, b=10b=10, c=11c=11, d=1d=1, e=100e=100, f=101f=101 would cost only [(0.45+0.16)⋅1+(0.13+0.12)⋅2+(0.09+0.05)⋅3]⋅100=153 Mbit,\big[(0.45 + 0.16)\cdot 1 + (0.13 + 0.12)\cdot 2 + (0.09 + 0.05)\cdot 3\big] \cdot 100 = 153 \text{ Mbit}, 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 e(d)=1e(d) = 1 is a prefix of e(b),e(c),e(e),e(f)e(b), e(c), e(e), e(f) and e(b)=10e(b) = 10 is a prefix of e(e),e(f)e(e), e(f).

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. □\square

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 00 to the left child and 11 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 ∣C∣\lvert C \rvert leaves;
  • there is a bijection between prefix codes on CC and binary tries with ∣C∣\lvert C \rvert leaves;
  • the depth of cc in the trie is its word length: dT(c)=∣e(c)∣d_T(c) = \lvert e(c) \rvert.

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 a=0a=0, b=101b=101, c=100c=100, d=111d=111, e=1101e=1101, f=1100f=1100 the string badface becomes 101 0 111 1100 0 100 1101101\,0\,111\,1100\,0\,100\,1101, i.e. 1010111110001001101 (19 bits, against 7⋅3=217 \cdot 3 = 21 for the fixed code).

Cost of a trie

The number of bits of the compressed file is ∑c∈C∣e(c)∣ (f(c)∣F∣)=(∑c∈CdT(c) f(c))∣F∣.\sum_{c \in C} \lvert e(c) \rvert\,\big(f(c) \lvert F \rvert\big) = \Big( \sum_{c \in C} d_T(c)\, f(c) \Big) \lvert F \rvert .

Definition (trie cost). B(T)=∑c∈CdT(c) f(c)B(T) = \displaystyle\sum_{c \in C} d_T(c)\, f(c) (average bits per character).

Problem (optimal character code). Given CC and frequencies f:C→Q+f : C \to \mathbb{Q}^+, find the prefix code, i.e. the binary trie T∗T^\ast with ∣C∣\lvert C \rvert leaves, minimizing B(T)B(T).

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 T∗T^\ast be optimal with an internal node uu with one child vv (say the left) and let T′T' be the subtree rooted at vv (possibly just the leaf vv). Contract uu and vv into one node: the result T^\hat T is still a trie with the same nn leaves, hence a valid code, and the edge (u,v)(u,v), i.e. one bit, disappears from the path of every leaf of T′T', which has at least one leaf c′c'. Then dT^(c′)f(c′)=dT∗(c′)f(c′)−f(c′)<dT∗(c′)f(c′)d_{\hat T}(c') f(c') = d_{T^\ast}(c') f(c') - f(c') < d_{T^\ast}(c') f(c') (frequencies are positive), while for other characters dT^(c)≤dT∗(c)d_{\hat T}(c) \le d_{T^\ast}(c). So B(T^)<B(T∗)B(\hat T) < B(T^\ast), a contradiction. □\square

For example the fixed-length code for 6 characters has a non-full trie (words 110110 and 111111 unused): it is not optimal. A full binary tree with nn leaves always has n−1n - 1 internal nodes (counting edges, 2I=I+n−12I = I + n - 1, so I=n−1I = n - 1).

Cost as a sum over internal nodes. If each node vv has weight w(v)w(v) = sum of the frequencies of the leaves below it, then B(T)=∑v internalw(v),B(T) = \sum_{v \text{ internal}} w(v), because the frequency of a leaf cc appears in the weight of each of its dT(c)d_T(c) 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 n=∣C∣n = \lvert C \rvert 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 n−1n - 1 merges one full tree with nn 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 QQ of nodes with key z.fz.f, with insert and extractmin in O(log⁡n)O(\log n) where nn 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 trie

The words are read from root-to-leaf paths afterwards. Convention: the left child (edge 00) 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: a 45a\,45, b 13b\,13, c 12c\,12, d 16d\,16, e 9e\,9, f 5f\,5. The queue at each step:

step extracted (left, right) node created queue after the step
start f 5, e 9, c 12, b 13, d 16, a 45f\,5,\ e\,9,\ c\,12,\ b\,13,\ d\,16,\ a\,45
1 f 5, e 9f\,5,\ e\,9 z1=14z_1 = 14 c 12, b 13, z1 14, d 16, a 45c\,12,\ b\,13,\ z_1\,14,\ d\,16,\ a\,45
2 c 12, b 13c\,12,\ b\,13 z2=25z_2 = 25 z1 14, d 16, z2 25, a 45z_1\,14,\ d\,16,\ z_2\,25,\ a\,45
3 z1 14, d 16z_1\,14,\ d\,16 z3=30z_3 = 30 z2 25, z3 30, a 45z_2\,25,\ z_3\,30,\ a\,45
4 z2 25, z3 30z_2\,25,\ z_3\,30 z4=55z_4 = 55 a 45, z4 55a\,45,\ z_4\,55
5 a 45, z4 55a\,45,\ z_4\,55 z5=100z_5 = 100 z5 100z_5\,100

The trie (numbers are weights; edges are 00 left, 11 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:9

Words: e(a)=0e(a) = 0, e(b)=101e(b) = 101, e(c)=100e(c) = 100, e(d)=111e(d) = 111, e(e)=1101e(e) = 1101, e(f)=1100e(f) = 1100. Cost B(T)=0.45⋅1+(0.13+0.12+0.16)⋅3+(0.09+0.05)⋅4=0.45+1.23+0.56=2.24,B(T) = 0.45 \cdot 1 + (0.13 + 0.12 + 0.16) \cdot 3 + (0.09 + 0.05) \cdot 4 = 0.45 + 1.23 + 0.56 = 2.24, i.e. 224224 Mbit for the file against 300300 for the fixed code. Check with internal nodes: 14+25+30+55+100=22414 + 25 + 30 + 55 + 100 = 224 (in hundredths). The source entropy is H≈2.22H \approx 2.22 bits, and H≤B<H+1H \le B < H + 1.

The optimum is not unique. With frequencies 1,1,2,21, 1, 2, 2 there are two valid runs (after merging 1+1=21+1 = 2 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 1,2,3,31, 2, 3, 3; the cost is 1212 in both cases.

Complexity

The model counts comparisons between frequencies; n=∣C∣n = \lvert C \rvert.

  • The first phase performs nn insertions, each O(log⁡n)O(\log n): O(nlog⁡n)O(n \log n) (with bottom-up heap construction it would drop to O(n)O(n)).
  • The loop has n−1n - 1 iterations, each with 2 extractions and 1 insertion, i.e. O(log⁡n)O(\log n).
  • The return performs one last extraction.

In total the extractions of the minimum are 2(n−1)+1=2n−12(n-1) + 1 = 2n - 1 (for n=13n = 13: 2525), and insertions are n+(n−1)=2n−1n + (n-1) = 2n - 1. The complexity is O(nlog⁡n)O(n \log n). If the characters arrive already sorted by frequency one can drop to O(n)O(n) with two sorted queues, one for leaves and one for created nodes (which are created in non-decreasing order); sorting the characters costs O(nlog⁡n)O(n \log n) though.

python
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: x,yx, y are the two characters of minimum frequency, f(x)≤f(y)≤f(c)f(x) \le f(y) \le f(c) for every other cc; C′=(C∖{x,y})∪{z}C' = (C \setminus \{x, y\}) \cup \{z\} with f(z)=f(x)+f(y)f(z) = f(x) + f(y) is the residual alphabet.

Exchange lemma. Let a,ba, b be two leaves of a trie TT with f(a)≤f(b)f(a) \le f(b) and dT(a)≤dT(b)d_T(a) \le d_T(b), and let T′T' be the trie obtained by swapping the characters aa and bb. Then B(T′)≤B(T)B(T') \le B(T).

Proof. After the swap aa is at the depth of bb and vice versa, other characters do not move: B(T′)−B(T)=f(a)dT(b)+f(b)dT(a)−f(a)dT(a)−f(b)dT(b)=(f(a)−f(b))(dT(b)−dT(a))≤0,B(T') - B(T) = f(a) d_T(b) + f(b) d_T(a) - f(a) d_T(a) - f(b) d_T(b) = \big(f(a) - f(b)\big)\big(d_T(b) - d_T(a)\big) \le 0, since both factors are ≤0\le 0. □\square

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 xx and yy are sibling leaves (children of the same parent) at maximum depth.

Proof. Let T∗T^\ast be an optimal trie; it is full. Let mm be the maximum depth and ww a leaf at depth mm: its sibling is a leaf zz (if it had descendants there would be a deeper leaf), at depth mm.

  1. If x∉{w,z}x \notin \{w, z\} swap xx and ww: f(x)≤f(w)f(x) \le f(w) (xx has minimum frequency) and d(x)≤d(w)=md(x) \le d(w) = m, so by the lemma the cost does not increase. (If x∈{w,z}x \in \{w, z\} call ww the leaf xx.) Now xx is at depth mm with leaf sibling zz.
  2. If y≠zy \ne z swap yy and zz: f(y)≤f(z)f(y) \le f(z) (since z≠xz \ne x and yy is the rarest among characters other than xx) and d(y)≤d(z)=md(y) \le d(z) = m, so the cost does not increase. The swap does not move xx, which now has yy as sibling.

The resulting trie has x,yx, y as siblings at maximum depth and cost ≤B(T∗)\le B(T^\ast), hence, by optimality of T∗T^\ast, equal: it is optimal. □\square

Optimal substructure property. Let TT be a trie for CC in which xx and yy are sibling leaves and T′T' the trie for C′C' obtained by pruning the leaves xx and yy: their parent becomes the leaf zz. Other characters have the same depth in TT and T′T', and dT′(z)=dT(x)−1=dT(y)−1d_{T'}(z) = d_T(x) - 1 = d_T(y) - 1. Therefore B(T)=∑c∈C∖{x,y}f(c) dT′(c)+(f(x)+f(y)) dT(x)=∑c∈C∖{x,y}f(c) dT′(c)+f(z)(dT′(z)+1)=B(T′)+f(x)+f(y).\begin{aligned} B(T) &= \sum_{c \in C \setminus \{x,y\}} f(c)\, d_{T'}(c) + \big(f(x) + f(y)\big)\, d_T(x) \\ &= \sum_{c \in C \setminus \{x,y\}} f(c)\, d_{T'}(c) + f(z)\big(d_{T'}(z) + 1\big) \\ &= B(T') + f(x) + f(y). \end{aligned} This relation holds for every pair (T,T′)(T, T') and is a bijection: every trie for C′C' comes from a unique trie for CC by making zz the parent of two leaves x,yx, y. So the minimum of BB over tries for CC with x,yx, y siblings is OPT(C′)+f(x)+f(y)\mathrm{OPT}(C') + f(x) + f(y), and by the greedy choice property it is also OPT(C)\mathrm{OPT}(C): OPT(C)=OPT(C′)+f(x)+f(y).\mathrm{OPT}(C) = \mathrm{OPT}(C') + f(x) + f(y).

Theorem. HUFFMAN(C,f)\mathrm{HUFFMAN}(C, f) returns an optimal trie, for every alphabet with n≥1n \ge 1 characters.

Proof. Induction on nn. Base n=1n = 1: a single node, the only trie. Step n≥2n \ge 2: the first iteration merges x,yx, y into zz and what remains is exactly the execution of HUFFMAN(C′,f′)\mathrm{HUFFMAN}(C', f'), which by the induction hypothesis (alphabet of n−1n-1 characters) returns an optimal trie T′T' for C′C'. The algorithm returns the trie TT obtained from T′T' by making zz the parent of x,yx, y. By the cost relation B(T)=B(T′)+f(x)+f(y)=OPT(C′)+f(x)+f(y)=OPT(C).□B(T) = B(T') + f(x) + f(y) = \mathrm{OPT}(C') + f(x) + f(y) = \mathrm{OPT}(C). \quad \square

Once again the code is simple and the correctness proof is the hard part.

Typical exam questions

  1. The total number of minimum extractions performed by HUFFMAN on an alphabet of n=13n = 13 characters. Answer: 1212 iterations with 22 extractions, plus 11 in the return: 24+1=25=2n−124 + 1 = 25 = 2n - 1.
  2. 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 nn leaves has n−1n-1 internal nodes.
  3. State and prove the greedy choice property for Huffman. Answer: exchange lemma B(T′)−B(T)=(f(a)−f(b))(d(b)−d(a))B(T') - B(T) = (f(a) - f(b))(d(b) - d(a)); move xx and yy onto the two deepest sibling leaves.

Versione ripasso

  • Character code e:C→{0,1}∗e : C \to \{0,1\}^\ast, file == concatenation of words. Fixed length: ⌈log⁡2∣C∣⌉\lceil \log_2 \lvert C \rvert \rceil bits (6 characters: 3 bits, 300300 Mbit out of 800800). Variable length must stay injective: a=0a=0, b=10b=10, c=11c=11, d=1d=1, e=100e=100, f=101f=101 is not (daadaa and ee give 100100), its 153153 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 ∣C∣\lvert C \rvert leaves; dT(c)=∣e(c)∣d_T(c) = \lvert e(c) \rvert.
  • Cost: B(T)=∑cdT(c)f(c)B(T) = \sum_c d_T(c) f(c), file bits =B(T)∣F∣= B(T) \lvert F \rvert. The optimal trie is full (if uu has one child, contract uu with the child: some leaf loses a bit, BB drops) and has n−1n - 1 internal nodes. Also B(T)=∑v internalw(v)B(T) = \sum_{v \text{ internal}} w(v), with w(v)w(v) the sum of frequencies of the leaves under vv.
  • Problem: given CC and f:C→Q+f : C \to \mathbb{Q}^+, find the binary trie T∗T^\ast with ∣C∣\lvert C \rvert leaves minimizing B(T)B(T). Only alphabet and frequencies are needed.
  • HUFFMAN: forest of nn leaves in a priority queue; for i=1..n−1i = 1..n-1: x <- extractmin, y <- extractmin, node z with z.f <- x.f + y.f, z.left <- x, z.right <- y, insert(z); return the last extractmin. Left is the one of frequency ≤\le.
  • Example a 45a\,45, b 13b\,13, c 12c\,12, d 16d\,16, e 9e\,9, f 5f\,5: merges 5+9=145{+}9 = 14, 12+13=2512{+}13 = 25, 14+16=3014{+}16 = 30, 25+30=5525{+}30 = 55, 45+55=10045{+}55 = 100. Words a=0a=0, b=101b=101, c=100c=100, d=111d=111, e=1101e=1101, f=1100f=1100; B=0.45+3⋅0.41+4⋅0.14=2.24B = 0.45 + 3 \cdot 0.41 + 4 \cdot 0.14 = 2.24 (224224 Mbit against 300300), equal to the sum of internal nodes 14+25+30+55+10014+25+30+55+100. Decoding badface gives 1010111110001001101.
  • Complexity: nn initial inserts, then n−1n-1 iterations with 2 extractmin and 1 insert: in total 2n−12n - 1 extractions (for n=13n = 13: 2525) and 2n−12n - 1 insertions, each O(log⁡n)O(\log n), so O(nlog⁡n)O(n \log n). With heapify the initial phase is O(n)O(n); with sorted input and two sorted queues the whole algorithm is O(n)O(n).
  • Non-uniqueness: with frequencies 1,1,2,21,1,2,2 there are two tries with lengths (2,2,2,2)(2,2,2,2) and (3,3,2,1)(3,3,2,1), both of cost 1212.
  • Exchange lemma: if f(a)≤f(b)f(a) \le f(b) and d(a)≤d(b)d(a) \le d(b), swapping aa and bb gives B(T′)−B(T)=(f(a)−f(b))(d(b)−d(a))≤0B(T') - B(T) = (f(a) - f(b))(d(b) - d(a)) \le 0 (the rarer goes down, the more frequent goes up).
  • Greedy choice: the two rarest characters x,yx, y are sibling leaves of maximum depth mm in some optimal trie. Two swaps: if xx is not already among the two deepest sibling leaves w,zw, z, swap x↔wx \leftrightarrow w (f(x)≤f(w)f(x) \le f(w), d(x)≤md(x) \le m); then swap y↔zy \leftrightarrow z (f(y)≤f(z)f(y) \le f(z), d(y)≤md(y) \le m). Cost does not grow, so the trie stays optimal.
  • Substructure: C′=C∖{x,y}∪{z}C' = C \setminus \{x,y\} \cup \{z\}, f(z)=f(x)+f(y)f(z) = f(x) + f(y). For every trie with x,yx,y siblings, pruned to T′T': B(T)=B(T′)+f(x)+f(y)B(T) = B(T') + f(x) + f(y), since dT′(z)=dT(x)−1d_{T'}(z) = d_T(x) - 1; bijection between such TT and tries T′T' for C′C', hence OPT(C)=OPT(C′)+f(x)+f(y)\mathrm{OPT}(C) = \mathrm{OPT}(C') + f(x) + f(y).
  • Correctness: induction on nn; base n=1n = 1; step: the first merge is the greedy choice, the rest is HUFFMAN(C′,f′)\mathrm{HUFFMAN}(C', f'), optimal by induction, and B(T)=B(T′)+f(x)+f(y)=OPT(C′)+f(x)+f(y)=OPT(C)B(T) = B(T') + f(x) + f(y) = \mathrm{OPT}(C') + f(x) + f(y) = \mathrm{OPT}(C).
  • Typical mistakes: believing fewer bits is better without checking the prefix property; putting a character on an internal node; nn 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 f(x)+f(y)f(x) + f(y) in OPT(C)=OPT(C′)+f(x)+f(y)\mathrm{OPT}(C) = \mathrm{OPT}(C') + f(x) + f(y).

Teoria collegata