Workbench / Squeeze: the Information Theory Capstone
S2 · B1·02
The Bit Writer and a Fixed-Length Code
Stage 2 of Squeeze, after chapter 2: a bit writer and reader that pack values of any width into bytes, tested on 2,000 random sequences; a fixed-length code that numbers a file's distinct bytes and stores each in ⌈log₂ K⌉ binary digits, with a small header so the file can be unpacked alone; and the corpus packed and restored exactly, from 11 bytes for the zeros to 976,045 for Shakespeare.
Stage 2: the bit writer and a fixed-length code
The brief
What you'll build. Two modules every later stage uses. bits.py has a BitWriter that appends values of any width (3 bits, 7 bits, 13 bits) to a stream of bytes, and a BitReader that reads them back. fixed.py uses them for Squeeze's first real compression method: find the file's distinct bytes, number them, and store each byte as its number in exactly binary digits, behind a header that records what the decoder needs.
Why a compressor needs this. Every code in this book produces binary digits, not bytes: 7 per character here, a variable number per symbol in chapter 5, fractions of a digit in chapter 6. Something has to pack them into bytes and unpack them exactly, and get the edge cases right (the last partial byte, zero-width values, values too big for their width). Building it once, with tests, means every later stage can trust it.
Why now. Chapter 2 gives exactly this stage's ideas: digits for symbols, the waste that rounding causes, and that a fixed-length code can be decoded by cutting the stream every digits.
What you'll have at the end. bits.py, fixed.py, test_stage2.py, and a new column in your results: the size of each corpus file under a fixed-length code, with a round-trip check.
Theory to own
- Exact width. Why is
(K - 1).bit_length()the right number of binary digits for symbols, and why ismath.ceil(math.log2(K))risky? (Chapter: "One symbol at a time"; companion, drill D1.) - The header's job. What must the decoder know that the packed digits don't tell it? Why can't it work out the original length from the number of packed bytes? (Chapter: Experiment 4; exercises, P3.)
- What this can and can't do. Why does a fixed-length code bring Shakespeare only from 8 to 7 bits per byte, when lzma reached 2.6? (Chapter: "The model to keep"; Deeper page, "Where the boundary is".)
- Zero symbols' worth. A file of one repeated byte needs 0 binary digits per byte. Why is that right, and what still has to be stored? (Chapter 1: a certain outcome carries 0 bits.)
Build it
Step 1: the bit writer and reader. The writer keeps an accumulator of pending bits; each write(value, width) shifts the value in, and whenever 8 or more bits are waiting it emits a byte. getvalue() pads the last byte with zeros. The reader does the reverse. Refuse values that don't fit their width: silently truncating them is the classic bug.
"""Squeeze, stage 2: write and read values of any width as a stream of bits."""
class BitWriter:
def __init__(self):
self.out, self.acc, self.n = bytearray(), 0, 0 # n bits waiting in acc
def write(self, value, width):
if width and not 0 <= value < (1 << width):
raise ValueError(f"{value} doesn't fit in {width} bits")
self.acc, self.n = (self.acc << width) | value, self.n + width
while self.n >= 8:
self.n -= 8
self.out.append((self.acc >> self.n) & 0xFF)
self.acc &= (1 << self.n) - 1
def getvalue(self):
"""The bytes so far, with the last byte padded with zeros."""
return bytes(self.out) + (bytes([(self.acc << (8 - self.n)) & 0xFF]) if self.n else b"")
class BitReader:
def __init__(self, data):
self.data, self.pos, self.acc, self.n = data, 0, 0, 0
def read(self, width):
while self.n < width:
if self.pos >= len(self.data):
raise EOFError("ran out of bits")
self.acc, self.n, self.pos = (self.acc << 8) | self.data[self.pos], self.n + 8, self.pos + 1
self.n -= width
v = (self.acc >> self.n) & ((1 << width) - 1)
self.acc &= (1 << self.n) - 1
return v
Step 2: the fixed-length code. The file format is a 4-byte signature (SQZ and method number 1), the original length, the alphabet size and the alphabet itself, then the packed codes.
"""Squeeze, stage 2: a fixed-length code. Format: b'SQZ', method 1, length (4 bytes), alphabet size (2 bytes), alphabet, packed codes."""
from bits import BitWriter, BitReader
def pack(data):
alphabet = sorted(set(data))
width = (len(alphabet) - 1).bit_length() # exact ceil(log2 K); 0 when there's one symbol
index = {b: i for i, b in enumerate(alphabet)}
w = BitWriter()
for b in data:
w.write(index[b], width)
header = b"SQZ" + bytes([1]) + len(data).to_bytes(4, "big") + len(alphabet).to_bytes(2, "big") + bytes(alphabet)
return header + w.getvalue()
def unpack(blob):
if blob[:4] != b"SQZ\x01":
raise ValueError("not a Squeeze fixed-length file")
n, k = int.from_bytes(blob[4:8], "big"), int.from_bytes(blob[8:10], "big")
alphabet = blob[10:10 + k]
width = (k - 1).bit_length()
r = BitReader(blob[10 + k:])
return bytes(alphabet[r.read(width)] if width else alphabet[0] for _ in range(n))
Step 3: test it. Round-trip 2,000 random sequences of values with random widths from 0 to 20, then the edge cases: an empty file, one byte, one repeated byte, all 256 byte values, a file of three symbols.
import random
from bits import BitWriter, BitReader
from fixed import pack, unpack
random.seed(2)
for _ in range(2000): # random widths and values round-trip
items = [(w, random.randrange(1 << w) if w else 0) for w in (random.randint(0, 20) for _ in range(random.randint(0, 50)))]
bw = BitWriter()
for w, v in items:
bw.write(v, w)
br = BitReader(bw.getvalue())
assert [br.read(w) for w, _ in items] == [v for _, v in items]
for data in (b"", b"a", b"aaaa", bytes(range(256)), bytes(random.randrange(3) for _ in range(1001))):
assert unpack(pack(data)) == data
try:
BitWriter().write(8, 3)
except ValueError as e:
print("refused:", e)
print("bit writer: 2,000 random sequences round-trip; fixed-length pack: edge cases round-trip")
Step 4: pack the corpus. Pack each file, unpack it, compare, and record the sizes.
import subprocess, time
from pathlib import Path
from fixed import pack, unpack
print(subprocess.run(["python3", "test_stage2.py"], capture_output=True, text=True, check=True).stdout, end="")
print(f"{'file':<16}{'bytes':>10}{'symbols':>9}{'fixed file':>12}{'b/B':>7} round trip")
for name in ("shakespeare.txt", "zeros.bin", "random.bin", "squares.csv", "server.log"):
data = Path(name).read_bytes()
blob = pack(data)
ok = unpack(blob) == data
print(f"{name:<16}{len(data):>10,}{len(set(data)):>9}{len(blob):>12,}{8 * len(blob) / len(data):>7.3f} {'exact' if ok else 'FAILED'}")
refused: 8 doesn't fit in 3 bits
bit writer: 2,000 random sequences round-trip; fixed-length pack: edge cases round-trip
file bytes symbols fixed file b/B round trip
shakespeare.txt 1,115,394 65 976,045 7.001 exact
zeros.bin 200,000 1 11 0.000 exact
random.bin 200,000 256 200,266 8.011 exact
squares.csv 200,000 12 100,022 4.001 exact
server.log 200,000 25 125,035 5.001 exact
Every file comes back exactly. Shakespeare's 65 symbols take 7 digits each; the log's 25 take 5 and the table's 12 take 4, halving it. The zeros need no digits at all, so the whole file is its 11-byte header. Random bytes use all 256 values, so the code saves nothing, and the 266-byte header (which lists the alphabet) makes the file slightly bigger: a fixed-length code can't compress what has no unused symbols. Compare with stage 1's table: lzma beats this on every file except zeros, because it uses frequencies and context.
Senior and architect lens
- Formats outlive code. The signature and method byte let a future Squeeze reject files it doesn't understand, and add methods without breaking old files. Every real format (PNG, ZIP, gzip) starts this way.
- Edge cases are where codecs break. Empty input, a single symbol (zero width), the final partial byte and values too wide for their field are the bugs that reach production; the tests target them first, and random round trips catch the rest.
- The header is part of the cost. For small files a header can outweigh the saving (random.bin grew by 266 bytes). Real formats keep headers compact and sometimes choose "store uncompressed" when coding doesn't help; Squeeze will add that choice in stage 6.
Evidence
bits.py,fixed.pyandtest_stage2.py, with the tests passing.- The table above from your own run, every file marked "exact".
- A note answering the four theory questions.
Carry forward
Stage 3, after chapter 3, counts how often each byte appears, and which bytes follow which, and turns the counts into probabilities: the model that every later code will be built from. Keep bits.py; from stage 5 on, codes of different lengths will be written with it.