Squeeze: the Information Theory CapstoneSqueeze
0 / 0

Workbench / Squeeze: the Information Theory Capstone

S6 · B1·06

Arithmetic Coding and the Method Chooser

Stage 6 of Squeeze, after chapter 6: an order-0 arithmetic coder (method 3) with a compact table of counts, which lands exactly on stage 4's order-0 targets; a "store" method for data that won't compress; and a chooser that tries every method and keeps the smallest, so zeros use the fixed-length code, random data is stored as is, and everything else is arithmetic-coded, with every file restored exactly.

6 topics · ~7 min read
Updated Suggest a correction

Stage 6: arithmetic coding and the method chooser

The brief

What you'll build. Two additions. arith.py is method 3: it scales the file's byte counts to a total of at most 215 (every present byte keeping at least 1), stores them in a small table (a 32-byte map of which bytes occur, then 2 bytes per present byte), and arithmetic-codes the data with chapter 6's coder. squeeze.py becomes the front end: it tries store (method 0), fixed-length, Huffman and arithmetic, and keeps the smallest result. The method byte in the header tells the decoder which one to use.

Why a compressor needs this. Chapter 6 showed two things this stage puts to work: arithmetic coding removes Huffman's whole-bit rounding (stage 5's one-bit floor on zeros.bin), and no method shrinks every file, so a real compressor needs a fallback that makes incompressible data only a few bytes bigger.

Why now. The chapter supplies the coder, the reason it reaches the model's entropy, the counting argument behind "store", and (in the companion) the trick of scaling counts to a small total so the coder's slices never collapse.

What you'll have at the end. arith.py, the new squeeze.py with pack and unpack commands, and a table showing every method on every file and which one wins.

Theory to own

  1. Why the arithmetic coder hits the target. Why should its size match stage 4's order-0 total almost exactly? (Chapter: "Arithmetic coding"; Deeper page, "Derive it".)
  2. Why scale the counts. What goes wrong if the counts' total is too large for the coder's precision? (Companion, drill D1 and code walkthrough.)
  3. Why "store" must exist. Why can't any method shrink random.bin, and how much bigger should a good compressor make it? (Chapter: "Why random data can't be compressed".)
  4. What the chooser costs. The chooser runs four coders on every file. When is that worth it, and what would a faster design do? (Exercises, senior S1.)

Build it

Step 1: the arithmetic method.

Python
"""Squeeze, stage 6: method 3, order-0 arithmetic coding with a compact table of counts scaled to 2^15."""
from collections import Counter
import ac

def scaled_counts(data, bits=15):
    """Counts scaled so they add up to about 2^bits at most, every present byte at least 1 (chapter 6's companion)."""
    c, n = Counter(data), len(data)
    scale = min(1.0, (1 << bits) / n)
    return {b: max(1, int(k * scale)) for b, k in c.items()}

def pack(data):
    if not data:
        raise ValueError("nothing to code")          # the chooser will store an empty file instead
    counts = scaled_counts(data)
    present = bytes(32)                                   # a 256-bit map of which bytes occur
    m = bytearray(present)
    for b in counts:
        m[b // 8] |= 1 << (b % 8)
    table = bytes(m) + b"".join(counts[b].to_bytes(2, "big") for b in sorted(counts))
    bits = ac.encode(data, counts)
    bits += "0" * (-len(bits) % 8)
    body = int(bits, 2).to_bytes(len(bits) // 8, "big") if bits else b""
    return b"SQZ\x03" + len(data).to_bytes(4, "big") + table + body

def unpack(blob):
    if blob[:4] != b"SQZ\x03":
        raise ValueError("not a Squeeze arithmetic file")
    n = int.from_bytes(blob[4:8], "big")
    m = blob[8:40]
    symbols = [b for b in range(256) if m[b // 8] >> (b % 8) & 1]
    counts = {b: int.from_bytes(blob[40 + 2 * i:42 + 2 * i], "big") for i, b in enumerate(symbols)}
    body = blob[40 + 2 * len(symbols):]
    bits = "".join(format(x, "08b") for x in body)
    return bytes(ac.decode(bits, counts, n))

Step 2: the chooser and command-line front end. Methods that can't handle an input (such as an empty file for the arithmetic coder) raise ValueError and are skipped.

Python
"""Squeeze, stage 6: try every method and keep the smallest. Usage: python3 squeeze.py pack|unpack IN OUT"""
import sys
from pathlib import Path
import fixed, huffman, arith

def store(data):
    return b"SQZ\x00" + len(data).to_bytes(4, "big") + data

METHODS = {0: ("store", store, lambda b: b[8:]), 1: ("fixed", fixed.pack, fixed.unpack),
           2: ("huffman", huffman.pack, huffman.unpack), 3: ("arithmetic", arith.pack, arith.unpack)}

def pack(data):
    results = []
    for m, (name, enc, _) in METHODS.items():
        try:
            results.append((len(blob := enc(data)), m, blob))
        except ValueError:
            pass                                           # a method that can't handle this input is skipped
    return min(results)[2]

def unpack(blob):
    if blob[:3] != b"SQZ" or blob[3] not in METHODS:
        raise ValueError("not a Squeeze file, or an unknown method")
    return METHODS[blob[3]][2](blob)

if __name__ == "__main__":
    if len(sys.argv) != 4 or sys.argv[1] not in ("pack", "unpack"):
        sys.exit(__doc__)
    f = pack if sys.argv[1] == "pack" else unpack
    Path(sys.argv[3]).write_bytes(f(Path(sys.argv[2]).read_bytes()))

Step 3: every method on every file.

Python
from pathlib import Path
import squeeze
from report import report
print(f"{'file':<16}{'store':>9}{'fixed':>9}{'huffman':>9}{'arith':>9}{'chosen':>12}{'b/B':>7}{'target':>8}  round trip")
for name in ("shakespeare.txt", "zeros.bin", "random.bin", "squares.csv", "server.log"):
    data = Path(name).read_bytes()
    sizes = {m: len(enc(data)) for m, (_, enc, _) in squeeze.METHODS.items()}
    blob = squeeze.pack(data)
    ok = squeeze.unpack(blob) == data
    print(f"{name:<16}" + "".join(f"{sizes[m]:>9,}" for m in range(4)) +
          f"{squeeze.METHODS[blob[3]][0]:>12}{8 * len(blob) / len(data):>7.3f}{report(name, data)['order 0'][2]:>8.3f}  {'exact' if ok else 'FAILED'}")
for edge in (b"", b"x", b"ab" * 3, bytes(range(256))):
    assert squeeze.unpack(squeeze.pack(edge)) == edge
print("edge cases: exact")
Text
file                store    fixed  huffman    arith      chosen    b/B  target  round trip
shakespeare.txt 1,115,402  976,045  671,747  666,539  arithmetic  4.781   4.781  exact
zeros.bin         200,008       11   25,136       43       fixed  0.000   0.000  exact
random.bin        200,008  200,266  200,136  200,532       store  8.000   8.032  exact
squares.csv       200,008  100,022   89,987   88,968  arithmetic  3.559   3.558  exact
server.log        200,008  125,035  110,286  109,180  arithmetic  4.367   4.367  exact
edge cases: exact

Step 4: read the table.

  • shakespeare.txt: arithmetic coding gives 666,539 bytes, 4.781 bits per byte, exactly stage 4's order-0 target and 5,208 bytes smaller than Huffman.
  • zeros.bin: the fixed-length code (11 bytes) still wins; the arithmetic coder's 43 bytes are mostly its table. Huffman's 25,136 bytes are gone for good: the chooser never picks it here.
  • random.bin: every coder makes it bigger, so the chooser stores it: 200,008 bytes, 8 bytes of header on 200,000.
  • squares.csv and server.log: arithmetic coding wins and matches the order-0 targets (3.559 and 4.367 bits per byte). The remaining gap to lzma (1.61 and 0.51) is all model: order-0 can't see that these files repeat whole lines.

Senior and architect lens

  • Always have a store mode. Every robust format (ZIP, PNG, Zstandard) can store data uncompressed, so incompressible input costs only a header. Without it, a compressor that's sometimes clever is sometimes harmful.
  • Choosing is a cost. Trying every method multiplies encoding time. Real compressors choose with cheap estimates (sample a block, compute an entropy estimate, check for runs) or per block, and keep the expensive tries for archival settings. Decoding stays fast either way: it runs one method.
  • The coder is finished; the model isn't. With arithmetic coding, every remaining gap is a modelling gap. From here, every improvement Squeeze makes will come from predicting better, which is where chapters 7 and 11 take it.

Evidence

  • arith.py, squeeze.py and your run's table, every file "exact".
  • The command-line round trip on one file: python3 squeeze.py pack shakespeare.txt s.sqz then unpack s.sqz back.txt and a byte comparison.
  • Answers to the four theory questions.

Carry forward

Stage 7, after chapter 7, gives Squeeze its first model with memory: an order-1 arithmetic coder that predicts each byte from the one before it, adaptively, so no table of 65,536 counts has to be sent. Stage 4's order-1 targets say it should beat order-0 on every text file, and the server log by more than half.