Compression and complexity
Making data smaller: prefix-free codes, Huffman coding with a priority queue, LZW’s growing dictionary, why no algorithm compresses everything, and a first look at P, NP, and the problems nobody knows how to solve quickly.
- Swift book
- Advanced Operators
- Documentation
- Data
A text file stores every character in 8 bits, whether it is a common e or a rare
q. Compression exploits that waste. CS61B’s last technical lectures use it to bring
together several data structures of this unit, heaps, trees, tries, and hash maps, and
then step back to ask about problems that no known algorithm solves efficiently. This
lesson does both.
Prefix-free codes
Lossless compression makes data smaller in a way that can be undone exactly. The
simplest idea is to give frequent symbols short codes and rare ones long codes, as Morse
code does. But variable-length codes must be decodable: if a is 0 and b is 01,
then 01 could be b, or a followed by something.
A code is prefix-free if no symbol’s code is the beginning of another’s. Then a sequence of bits can be decoded left to right without ambiguity: read bits until they match a code, output its symbol, and continue. Prefix-free codes are exactly the codes that can be drawn as a binary trie (Lesson 50) with symbols only at the leaves: 0 goes left, 1 goes right, and a leaf is a complete code.
Huffman coding
Given how often each symbol occurs, which prefix-free code gives the shortest encoding? David Huffman found the answer in 1952, as a student, and it is short: put every symbol in a priority queue (Lesson 41) as a one-node tree, weighted by its frequency; then repeatedly remove the two lightest trees, join them under a new parent whose weight is their sum, and put it back. When one tree remains, it is the code.
indirect enum HuffmanTree {
case leaf(Character, weight: Int)
case node(HuffmanTree, HuffmanTree, weight: Int)
var weight: Int {
switch self {
case .leaf(_, let w), .node(_, _, let w): w
}
}
func codes(prefix: String = "") -> [Character: String] {
switch self {
case .leaf(let c, _):
[c: prefix.isEmpty ? "0" : prefix]
case .node(let left, let right, _):
left.codes(prefix: prefix + "0").merging(right.codes(prefix: prefix + "1")) { a, _ in a }
}
}
}
func huffman(_ text: String) -> HuffmanTree {
var counts: [Character: Int] = [:]
for c in text { counts[c, default: 0] += 1 }
// A sorted array as the priority queue, to keep the example short; ties by character.
var queue = counts.map { HuffmanTree.leaf($0.key, weight: $0.value) }
func key(_ t: HuffmanTree) -> (Int, String) {
if case .leaf(let c, let w) = t { return (w, String(c)) } else { return (t.weight, "~") }
}
while queue.count > 1 {
queue.sort { key($0) < key($1) }
let (a, b) = (queue.removeFirst(), queue.removeFirst())
queue.append(.node(a, b, weight: a.weight + b.weight))
}
return queue[0]
}
let text = "abracadabra"
let codes = huffman(text).codes()
let encoded = text.map { codes[$0]! }.joined()
print(codes.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }, encoded.count, text.count * 8)
// ["a=0", "b=110", "c=100", "d=101", "r=111"] 23 88
a, which occurs five times, gets a one-bit code; the rarer letters get three bits.
The whole word takes 23 bits instead of 88. Huffman’s algorithm is optimal: no
prefix-free code gives a shorter encoding for these frequencies. With a heap, building
the tree for R symbols takes O(R log R).
To decode, the receiver needs the tree too, so a compressed file stores it at the start. Decoding walks the tree bit by bit and restarts at the root after each leaf.
What would Swift print?
let codes: [String: Character] = ["0": "a", "10": "b", "110": "c", "111": "d"]
var output = ""
var current = ""
for bit in "0101100111" {
current.append(bit)
if let c = codes[current] {
output.append(c)
current = ""
}
}
print(output)Show answer and explanation
Answerabcad
Reading left to right: 0 is a; 1 is not a code, 10 is b; 110 is c; 0 is a; 111 is d. Because the code is prefix-free, the first match is always the right one.
LZW: learning as you go
Huffman coding treats each symbol alone. Real data has repeated phrases: words in text, runs of pixels. LZW (Lempel, Ziv, and Welch) builds a dictionary of phrases as it reads, starting with single characters. At each step it outputs the code for the longest phrase in the dictionary that matches the input, then adds that phrase plus the next character as a new entry:
func lzwEncode(_ text: String) -> [Int] {
var dictionary: [String: Int] = [:]
for c in Set(text).sorted() { dictionary[String(c)] = dictionary.count }
var phrase = ""
var output: [Int] = []
for c in text {
let extended = phrase + String(c)
if dictionary[extended] != nil {
phrase = extended
} else {
output.append(dictionary[phrase]!)
dictionary[extended] = dictionary.count
phrase = String(c)
}
}
if !phrase.isEmpty { output.append(dictionary[phrase]!) }
return output
}
let codesOut = lzwEncode("abababababab")
print(codesOut, codesOut.count) // [0, 1, 2, 4, 3, 6] 6
Twelve characters become six codes, and the longer the repetition, the longer the phrases the dictionary learns. The decoder rebuilds the same dictionary from the codes it receives, so the dictionary never has to be sent. LZW-style algorithms are behind GIF images and, in refined forms, ZIP and PNG.
You cannot compress everything
Could an algorithm compress every file, even by one bit? No, by counting. There are 2ⁿ files of exactly n bits, but only 2ⁿ − 1 files shorter than n bits (2⁰ + 2¹ + … + 2ⁿ⁻¹). A lossless compressor must map different inputs to different outputs, so it cannot map all 2ⁿ inputs into fewer possible outputs. Every compressor makes some files larger. Compression works on real data because real data is far from random, and random data, such as already-compressed files, does not compress.
CS61B takes this further. The best possible compression of a file is the shortest program that prints it: its Kolmogorov complexity. A million digits of π are very compressible by this measure, a short program computes them, though they look random. But no program can compute the Kolmogorov complexity of every file: the question is uncomputable, not just hard.
Hard problems: P and NP
Some problems are not uncomputable, just, as far as anyone knows, slow. Lesson 43’s Hamilton path problem, “is there a path visiting every vertex exactly once?”, has no known algorithm much faster than trying the possibilities, which grow exponentially. Yet a proposed path is easy to check.
- P is the class of yes-or-no problems that can be solved in polynomial time, O(Nᵏ) for some k: connectivity, shortest paths, sorting-based questions.
- NP is the class of yes-or-no problems whose yes-answers can be checked in polynomial time, given a certificate such as the path itself: Hamilton path, scheduling with deadlines, Sudoku of any size, and every problem in P.
A problem is NP-complete if it is in NP and every NP problem reduces to it (Lesson 47): Hamilton path, 3-coloring a graph, and boolean satisfiability are examples. Thousands of NP-complete problems are known, and a polynomial algorithm for any one of them would give one for all of NP. Whether P = NP is the most famous open question in computer science. Most researchers believe P ≠ NP, which would mean these problems have no efficient algorithm at all. Much of modern cryptography rests on problems like them being hard.
Put the lines in order
Put the lines in order so the program prints 7.
shorter += 1 << lengthlet n = 3var shorter = 0}for length in 0..<n {print(shorter)
Show the correct program
let n = 3
var shorter = 0
for length in 0..<n {
shorter += 1 << length
}
print(shorter)Lab 57: Compression
Q0: What would Swift print?
What would Swift print?
let frequencies = ["a": 45, "b": 13, "c": 12, "d": 16, "e": 9, "f": 5]
let codeLengths = ["a": 1, "b": 3, "c": 3, "d": 3, "e": 4, "f": 4]
let bits = frequencies.map { $0.value * codeLengths[$0.key]! }.reduce(0, +)
let fixed = frequencies.values.reduce(0, +) * 3
print(bits, fixed)Show answer and explanation
Answer224 300
With a fixed 3-bit code, 100 symbols take 300 bits. The Huffman code lengths for these frequencies, from the classic textbook example, give 45 + 3 × (13 + 12 + 16) + 4 × (9 + 5) = 224 bits, 25% less.
Q1: Decoding with the tree
Write decode(_:with:), which decodes a string of bits by walking the lesson’s
HuffmanTree, and check that decoding the encoding of several texts gives them back.
Show solution
indirect enum HuffmanTree {
case leaf(Character, weight: Int)
case node(HuffmanTree, HuffmanTree, weight: Int)
var weight: Int {
switch self { case .leaf(_, let w), .node(_, _, let w): w }
}
func codes(prefix: String = "") -> [Character: String] {
switch self {
case .leaf(let c, _): [c: prefix.isEmpty ? "0" : prefix]
case .node(let l, let r, _): l.codes(prefix: prefix + "0").merging(r.codes(prefix: prefix + "1")) { a, _ in a }
}
}
}
func huffman(_ text: String) -> HuffmanTree {
var counts: [Character: Int] = [:]
for c in text { counts[c, default: 0] += 1 }
var queue = counts.sorted { $0.key < $1.key }.map { HuffmanTree.leaf($0.key, weight: $0.value) }
while queue.count > 1 {
queue.sort { $0.weight < $1.weight }
let (a, b) = (queue.removeFirst(), queue.removeFirst())
queue.append(.node(a, b, weight: a.weight + b.weight))
}
return queue[0]
}
func decode(_ bits: String, with tree: HuffmanTree) -> String {
if case .leaf(let c, _) = tree { // a one-symbol text
return String(repeating: c, count: bits.count)
}
var output = ""
var node = tree
for bit in bits {
guard case .node(let left, let right, _) = node else { break }
node = bit == "0" ? left : right
if case .leaf(let c, _) = node {
output.append(c)
node = tree
}
}
return output
}
for text in ["abracadabra", "mississippi river", "aaaa", "the quick brown fox"] {
let tree = huffman(text)
let codes = tree.codes()
let bits = text.map { codes[$0]! }.joined()
assert(decode(bits, with: tree) == text)
assert(bits.count <= text.count * 8)
}A text with one distinct symbol has a tree that is a single leaf; giving it the code
0 and decoding one symbol per bit handles that edge case. Sorting with a stable sort
(Lesson 54) after an initial sort by character makes the tree the same on every run.
Q2: LZW decoding
Write lzwDecode(_:alphabet:), the inverse of the lesson’s encoder, given the same
starting alphabet. The tricky case: a code can refer to the entry the encoder added
at the previous step, which the decoder has not added yet. That entry is always the
previous phrase plus its own first character.
Show solution
func lzwEncode(_ text: String, alphabet: [Character]) -> [Int] {
var dictionary: [String: Int] = [:]
for c in alphabet { dictionary[String(c)] = dictionary.count }
var phrase = ""
var output: [Int] = []
for c in text {
let extended = phrase + String(c)
if dictionary[extended] != nil {
phrase = extended
} else {
output.append(dictionary[phrase]!)
dictionary[extended] = dictionary.count
phrase = String(c)
}
}
if !phrase.isEmpty { output.append(dictionary[phrase]!) }
return output
}
func lzwDecode(_ codes: [Int], alphabet: [Character]) -> String {
var entries = alphabet.map { String($0) }
guard let first = codes.first else { return "" }
var previous = entries[first]
var output = previous
for code in codes.dropFirst() {
let current = code < entries.count ? entries[code] : previous + String(previous.first!)
output += current
entries.append(previous + String(current.first!))
previous = current
}
return output
}
let alphabet: [Character] = ["a", "b", "r", "c", "d"]
for text in ["abababababab", "abracadabra", "aaaaaaa", ""] {
assert(lzwDecode(lzwEncode(text, alphabet: alphabet), alphabet: alphabet) == text)
}"aaaaaaa" exercises the tricky case: the encoder adds “aa” and immediately outputs
its code, before the decoder has seen enough to know it. The rule “previous phrase plus
its own first character” recovers it.
Q3 (optional): Compressing random data
Show the counting argument in action: “compress” 10,000 random 16-character strings of the letters a and b with the Huffman code of each string, counting the bits for the code table as a byte per symbol plus a byte per code length, and compare with the 16 bits that a plain one-bit-per-letter encoding needs.
Show solution
var generator = SystemRandomNumberGenerator()
var larger = 0
for _ in 0..<10_000 {
let text = String((0..<16).map { _ in Bool.random(using: &generator) ? Character("a") : "b" })
// Huffman gives each of at most two symbols a 1-bit code: 16 bits of data,
// plus a table of 2 bytes (16 bits) per distinct symbol.
let dataBits = 16
let tableBits = Set(text).count * 16
if dataBits + tableBits > 16 { larger += 1 }
}
assert(larger == 10_000)Random strings of two letters are already as compact as one bit per letter; Huffman cannot improve on that, and the table it must store makes every result larger. Real compressors store a flag saying “stored uncompressed” for such inputs, which costs a few bits and caps the damage, but, as the counting argument proves, cannot avoid it entirely.
What’s next
The last lesson steps back from algorithms to the people who use software, and to where to go from here.