数据压缩

Data Compression

我一直很好奇数据压缩的原理:我们常用的 zip, 7z 等压缩软件,到底是依据什么样的原理进行工作的呢?

先介绍几个数据压缩中的常用术语:

  • Message. Binary data BB we want to compress.
  • Compress. Generate a "compressed" representation C(B)C(B).
  • Expand. Reconstructs original bitstream BB.
  • Compression ratio. Bits in C(B)C(B) / bits in BB.

一般来说,被压缩的数据都是 Standard ASCII characters: 每个 ASCII 字符 (char) 都占 8 bits。

Non-existence of universal data compression. No algorithm can compress every bitstream.

用反证法简单证明:如果 universal data compression 算法存在,那么对于某个 bitstream BB,我们不断对其应用该算法,理论上可以将空间压缩至 0;这显然是不合理的。

Run-Length Coding

Run-length coding 是一个简单的数据压缩算法:对于 long runs of repeated bits,我们用 4-bits counts to represent alternating runs of 0s and 1s。

0000000000000001111111000000011111111111 (40 bits) => 15 0s, then 7 1s, then 7 0s, then 11 1s => 1111011101111011 (16 bits)。这 16 bits,每 4 bits 分别是 15, 7, 7 与 11 的二进制表示。

在实际应用中,我们一般用一个 8-bits string 来记录 run-length。也就是说,若某个连续的 0/10/1 段的长度超过 28−1=2552^8-1=255 时,我们需要 intersperse runs of length 0。(例如,当一个长度超过 255 的 00 段出现时,我们将其分为两个长度小于 255 的 00 段并用一个形式化的长为 0 的 11 段隔开)

java
public class RunLength {
    private final static int R   = 256;
    private final static int lgR = 8;
    
    public static void compress() { /* see textbook */ }
    
    public static void expand() {
        boolean bit = false;
        while (!BinaryStdIn.isEmpty()) {
            int run = BinaryStdIn.readInt(lgR);  // read 8-bit count from standard input
            for (int i = 0; i < run; ++i)
             	BinaryStdOut.write(bit);         // write 1 bit to standard output
            bit = !bit;                          // alternate 0 and 1
        }
        BinaryStdOut.close();
    }
}

Huffman Compression

我们常常能发现,一些 encoding 方式会导致 ambiguity:比如这一段摩斯电码 ***---*** 可以解释为 SOS,V7,IAMIE 与 EEWNI。在实际应用中,摩斯电码在每个 codewords 间停顿一段时间以作区分。

但对于 data compression 我们需要采取另外的方式来避免 ambiguity: we need to ensure no code word is a prefix of another.

  • Ex 1. Fixed-length code.
  • Ex 2. Append special stop char to each codeword.
  • Ex 3. General prefix-free code.

很巧妙的是,prefix-free code 可以用一颗 binary trie 来表示!

  • Char in leaves.
  • Codeword is path from root to leaf.
java
private static class Node implements Comparable<Node> {
    private final char ch;            // used only for leaf nodes
    private final int freq;           // used only for compress (stay tuned)
    private final Node left, right; 
    
    public Node(char ch, int freq, Node left, Node right) {
        this.ch    = ch;
        this.freq  = freq;
        this.left  = left;
        this.right = right;
    }
    
    public boolean isLeaf() { return left == null && right == null; }
    
    public int compareTo(Node that) { return this.freq - that.freq; }
}

这样,对于一个给定的用 binary trie 表示的 prefix-free coding scheme 与一段待压缩的 message,我们能够轻易的进行 compression (从 leaf 开始向上) 与 expansion (从 root 开始向下)。以 expansion 为例:

java
public void expand() {
    Node root = readTrie();           // read in encoding trie
    int N = BinaryStdIn.readInt();    // read in number of chars
    for (int i = 0; i < N; ++i) {
        Node x = root;
        while (!x.isLeaf()) {         // expand codeword for ith char
            if (!BinaryStdIn.readBoolean())
                x = x.left;
            else
                x = x.right;
        }
        BinaryStdOut.write(x.ch, 8);  // field 'ch' stores the encoded char
    }
    BinaryStdOut.close();
}

现在,问题来到如何构建一颗 optimal prefix-free binary trie。Huffman tree 是一个绝佳的选择:

  • Count frequency freq[i] for each char i in input.
  • Start with one node corresponding to each char i (with weight freq[i]).
  • Repeat until a single binary trie formed:
    • select two tries with min weight freq[i] and freq[j]
    • merge into single trie with weight freq[i] + freq[j]

Huffman tree 贪心的对当前权值最小的两颗 trie 进行二叉合并,可以证明这样做能够使得权值越大的叶子节点离根节点的距离越远。也就是说,出现频率越高的字符,其编码 (codeword) 的长度越短。

java
private static Node buildTrie(int[] freq) {
    MinPQ<Node> pq = new MinPQ<Node>();
    for (char i = 0; i < R; ++i)    // initialize PQ with singleton tries
        if (freq[i] > 0)
            pq.insert(new Node(i, freq[i], null, null));  
    
    while (pq.size() > 1) {
        Node x = pq.delMin();
        Node y = pq.delMin();  // greedily merge two smallest tries
        Node parent = new Node('\0', x.freq + y.freq, x, y);  // new root/internal nodes
        pq.insert(parent);
    }
    
    return pq.delMin();
}

LZW Compression

与 static model (ex. ASCII, Morse code) 与 dynamic model (ex. Huffman code) 不同,LZW code 是一种 adaptive model: it progressively learn and update model as you read text.

LZW 算法维护一个 symbol table,其中记录着一系列 string-code 的映射。与 Huffman code 逐字符编码的方式不同,LZW 算法能够为特定的字符串进行编码。

与 Huffman code 相同的是,LZW 中的 symbol table 也用 trie 进行实现 (但并非 binary trie);并且该 trie 需要支持 longest prefix match 操作。这是因为 LZW compression 的步骤如下:

  • Create ST associating WW-bit codewords with string keys.
  • Initialize ST with codewords for single-char keys.
  • (longest prefix match) Find longest string ss in ST that is a prefix of unscanned part of input.
  • Write the WW-bit codeword associated with ss.
  • Add s+cs+c to ST as an update, where cc is the next char in the input.
java
public static void compress() {
    String input = BinaryStdIn.readString();
    TST<Integer> st = new TST<Integer>();
    for (int i = 0; i < R; ++i)    // codewords for single-char, radix R keys
        st.put("" + (char) i, i);
    int code = R+1;
    
    while (input.length() > 0) {
        String s = st.longestPrefixOf(input);    // find longest prefix match s
        BinaryStdOut.write(st.get(s), W);        // write W-bit codeword for s
        int t = s.length();
        if (t < input.length() && code < L)      // add new codeword
            st.put(input.substring(0, t+1), code++);
        input = input.substring(t);              // scan past s in input
    }
    BinaryStdOut.write(R, W);                    // write "stop" codeword
    BinaryStdOut.close();
}

LZW expansion 需要在 decode 的同时 reconstruct the symbol table. 其步骤如下:

  • Create ST associating string values with WW-bit keys.
  • Initialize ST to contain single-char values.
  • Read a WW-bit key.
  • Find associated string value in ST and write it out.
  • Update ST.

注意,LZW expansion 存在一种 tricky case 需要 handle: 尝试 expand 以下例子,可以发现有时我们会遇到 symbol table 中当前未记录的编码。(具体的处理方式 not cover in this class)

expansion stops for unknown code value

LZW 与 Huffman compression 都是一种 loseless compression (我们熟悉的 JPEG, MP3 compression 均不属于此类,它们是 lossy compression),并且都被 Shannon entropy 理论所限制。它们最大的区别在于:

  • LZW: represent variable-length symbols with fixed-length codes.
  • Huffman: represent fixed-length symbols with variable-length codes.
CC BY-NC-SA 4.0
正在加载评论…