Workbench / Squeeze: the Information Theory Capstone
S1 · B1·01
The Information Meter
Stage 1 of Squeeze, the information theory capstone, after chapter 1: a test corpus of five very different files (Shakespeare, zeros, pseudo-random bytes, a table of numbers and a server log) and a meter that reports each one's stored bits, distinct bytes, the cost of a fixed-length code, and what zlib and lzma achieve, saved as the baseline every later stage must beat or explain.
Stage 1: the information meter
The brief
What you'll build. Squeeze is a compressor you'll build one chapter at a time, ending with a working, tested tool that beats zlib on text and can say, for any file, how close it got to the limit. This first stage builds the two things everything else is measured against: a corpus of test files that behave very differently, and a meter, squeeze.py measure, that reports how many bits each file stores and how small the standard compressors can make it.
Why a compressor needs this first. Chapter 1's central distinction is between stored binary digits and bits of information. You can't improve a compressor you can't measure, and a single test file hides everything: a method that's brilliant on text can be useless on logs, and every method fails on random data. The corpus makes those differences visible from the start.
Why now. Chapter 1 gives you exactly what this stage needs: that a file's size counts stored digits, not information; that compressed size is an upper bound on information; that binary digits pick one of symbols; and that random data can't be shrunk.
What you'll have at the end. A folder squeeze/ with five corpus files, make_corpus.py, squeeze.py with a measure command, and baseline.json: the numbers each later stage will be compared with.
Theory to own
Answer these in your own words before you build. Each points to where the book explains it.
- Stored against carried. Why can two files of exactly 200,000 bytes carry wildly different amounts of information? (Chapter: "Stored bits and information bits".)
- Upper bound, not measurement. Why is a compressor's output size an upper bound on the information in a file, and not the information itself? (Chapter: Experiment 4; companion, "What the chapter oversimplifies", point 2.)
- The fixed-length cost. If a file uses only 12 different byte values, why do binary digits per byte suffice to store it, without any cleverness? (Chapter: "Bits as yes-or-no questions".)
- The random file. Why must a good compressor make
random.binslightly bigger, never smaller? And why is "random" in quotation marks for this file? (Chapter: Experiment 4; companion, interview question Q6.)
Build it
Step 1: make the corpus. Put Chapter 1's shakespeare.txt in the folder, then generate four more files of 200,000 bytes each: all zeros, pseudo-random bytes from a fixed seed (so everyone's corpus is identical), a table of numbers and their squares, and a server log with timestamps, paths and mostly-200 status codes.
"""Squeeze, stage 1: build the test corpus every later stage is measured on."""
import random
random.seed(1948)
n = 200_000
files = {
"zeros.bin": bytes(n),
"random.bin": random.randbytes(n), # pseudo-random: chapter 1's companion explains the catch
"squares.csv": "".join(f"{i},{i * i}\n" for i in range(1, 25_000)).encode()[:n],
"server.log": "".join(f"2026-11-27T09:{(i // 60) % 60:02d}:{i % 60:02d} GET /api/items/{random.randint(1, 500)} "
f"{random.choices(['200', '404', '500'], [97, 2, 1])[0]}\n" for i in range(5000)).encode()[:n],
}
for name, data in files.items():
open(name, "wb").write(data)
print(f"wrote {name:<12} {len(data):>9,} bytes")
Step 2: write the meter. For each file, report its size, the number of distinct byte values, the binary digits per byte a fixed-length code would need, and the compressed bits per byte with zlib and lzma. Save the numbers as JSON.
"""Squeeze, stage 1: the information meter. Usage: python3 squeeze.py measure FILE..."""
import json, lzma, math, sys, zlib
from pathlib import Path
def measure(path):
data = Path(path).read_bytes()
n = len(data)
distinct = len(set(data))
return {"file": Path(path).name, "bytes": n, "stored_bits": 8 * n, "distinct_bytes": distinct,
# a fixed-length code for one of `distinct` symbols needs ceil(log2 distinct) binary digits each
"fixed_bits_per_byte": math.ceil(math.log2(distinct)) if distinct > 1 else 0,
"zlib": len(zlib.compress(data, 9)), "lzma": len(lzma.compress(data, preset=9))}
def show(rows):
print(f"{'file':<16}{'bytes':>10}{'distinct':>9}{'fixed b/B':>10}{'zlib b/B':>10}{'lzma b/B':>10}")
for r in rows:
print(f"{r['file']:<16}{r['bytes']:>10,}{r['distinct_bytes']:>9}{r['fixed_bits_per_byte']:>10}"
f"{8 * r['zlib'] / r['bytes']:>10.3f}{8 * r['lzma'] / r['bytes']:>10.3f}")
if __name__ == "__main__":
if len(sys.argv) < 3 or sys.argv[1] != "measure":
sys.exit(__doc__)
rows = [measure(p) for p in sys.argv[2:]]
show(rows)
Path("baseline.json").write_text(json.dumps(rows, indent=1))
print("saved baseline.json: the numbers every later stage must beat or explain")
Step 3: run it.
$ python3 make_corpus.py
wrote zeros.bin 200,000 bytes
wrote random.bin 200,000 bytes
wrote squares.csv 200,000 bytes
wrote server.log 200,000 bytes
$ python3 squeeze.py measure shakespeare.txt zeros.bin random.bin squares.csv server.log
file bytes distinct fixed b/B zlib b/B lzma b/B
shakespeare.txt 1,115,394 65 7 3.118 2.611
zeros.bin 200,000 1 0 0.009 0.007
random.bin 200,000 256 8 8.003 8.003
squares.csv 200,000 12 4 3.539 1.610
server.log 200,000 25 5 0.862 0.509
saved baseline.json: the numbers every later stage must beat or explain
Step 4: read the table before moving on. Write two or three sentences about each row:
- shakespeare.txt uses only 65 different bytes, so a fixed-length code already needs only 7 binary digits per byte instead of 8; lzma gets to 2.61, using patterns between letters.
- zeros.bin has one symbol and no information; both compressors get to under a hundredth of a bit per byte.
- random.bin uses all 256 values and doesn't compress: both compressors are over 8 bits per byte.
- squares.csv uses 12 symbols (ten digits, a comma, a newline), so 4 binary digits per byte suffice; lzma finds much more structure (1.61), and the true information is far smaller still, since the whole file is generated by one line of code.
- server.log looks varied but is very repetitive: lzma gets it to about half a bit per byte.
Senior and architect lens
- Benchmarks decide arguments. A compression idea without a corpus is an opinion. Choose test files that represent the data you'll really meet, include the cases where every method fails (random) or wins trivially (zeros), and keep the corpus fixed so that numbers from different stages are comparable.
- Two baselines, not one. A fixed-length code is the "no cleverness" baseline;
zlibandlzmaare the "what the industry already does" baseline. A new method has to be judged against both: beating fixed-length is easy, beating lzma on text is hard. - Upper bounds are not truths. Every number in the table is an upper bound on information relative to some model.
squares.csvis the warning: its real information is a few dozen bytes of program, and no general-purpose compressor sees that.
Evidence
Keep these in your folder:
- The five corpus files and
make_corpus.py. squeeze.pyand its output table, matching the one above (yourrandom.binwill match exactly because of the fixed seed).baseline.json.- Your notes on each row, in your own words.
Carry forward
Stage 2, after chapter 2, turns the fixed-length column into real code: a bit writer that packs each byte of a file into binary digits, where is the number of distinct bytes, and a reader that unpacks them exactly. Keep the corpus and the meter: every later stage adds a column to the table.