Workbench / Squeeze: the Information Theory Capstone
S10 · B1·10
Real Data
Stage 10 of Squeeze, after chapter 10: the compressor meets real data of very different kinds (a genome, brain recordings, a compiled program, an MRI scan, an already-compressed file, a declaration in five scripts) and each result is set against the data's order-0 entropy and lzma; Squeeze beats lzma on DNA (1.93 bits per base against 2.16), loses badly on the program (4.32 against 3.07), and gains a quarter on the MRI scan from one transform, storing each sample as its difference from the one before.
Stage 10: real data
The brief
What you'll build. make_real.py, which gathers six files of real data, and realtest.py, which packs each with Squeeze (checking the round trip), and reports, in bits per byte, the file's order-0 entropy, Squeeze's result and method, and lzma's. Then one transform: the MRI scan's 16-bit samples rewritten as differences between neighbouring samples, packed the same way.
Why a compressor needs this. Squeeze was built and tuned on four test files. Real data comes in kinds its order-1 byte model wasn't designed for: two-byte numbers, floating-point measurements, machine code, data that's already compressed. Chapter 10 showed that each kind of source has its own structure and that a model's figure is an upper bound that depends on what it can see. This stage finds where Squeeze's model fits and where it doesn't.
Why now. The chapter supplies the measurements (entropy against what models achieve), the warning that general methods miss specialised structure (DNA's reverse complements), and the idea of measuring real sources rather than assumed ones.
What you'll have at the end. A table for eight files, a transform that helps one of them, and a list of what a better model would need for each kind.
Theory to own
- Bits per byte isn't bits per symbol. Why does Squeeze's 1.93 bits per byte on the genome mean 1.93 bits per base, but its 2.21 on the MRI mean about 4.4 bits per sample? (Chapter: "The same text in many languages".)
- What order-1 can and can't see. Which structure in machine code or in 16-bit samples is invisible to a model that looks only one byte back? (Chapter 7: "Markov models of text".)
- Transforms. Why can rewriting the data before modelling (differences, as here, or reverse complements, as in the exercises' C2) help a model that's otherwise unchanged? (Chapter: "DNA"; exercises C2.)
- Compressed input. What should any compressor do with data that's already compressed, and why? (Chapter 6: "the source coding theorem"; chapter 8: "Damage in compressed data".)
Build it
Step 1: gather the data. The MRI slice and EEG recordings come from Matplotlib's sample data (installed with it), the program is the system's ls, the genome is chapter 10's, the plays are gzipped, and the declaration's first 10,000 bytes in five scripts are joined into one UTF-8 file.
"""Gather stage 10's real data into ./real (run once)."""
import gzip, shutil, zlib
from pathlib import Path
import matplotlib.cbook
out = Path("real"); out.mkdir(exist_ok=True)
sample = Path(matplotlib.cbook._get_data_path("sample_data"))
(out / "mri.raw").write_bytes(gzip.decompress((sample / "s1045.ima.gz").read_bytes())) # a 256 x 256 MRI slice, 16-bit
shutil.copy(sample / "eeg.dat", out / "eeg.dat") # EEG recordings, 16-bit samples
shutil.copy("/usr/bin/ls", out / "ls.bin") # a compiled program
shutil.copy("chloroplast.txt", out / "chloroplast.txt") # DNA, one letter per base
(out / "plays.gz").write_bytes(gzip.compress(Path("shakespeare.txt").read_bytes(), 9)) # already compressed
langs = ["English-Latin1", "Russian-UTF8", "Hindi-UTF8", "Chinese_Mandarin-UTF8", "Japanese_Nihongo-UTF8"]
udhr = Path("udhr")
text = "\n".join(" ".join((udhr / f).read_bytes().decode("latin-1" if "Latin1" in f else "utf-8", errors="ignore").split()) for f in langs)
(out / "udhr5.txt").write_text(text, encoding="utf-8") # five scripts in UTF-8
for f in sorted(out.iterdir()):
print(f"{f.name:<16}{f.stat().st_size:>10,} bytes")
Step 2: pack everything and compare.
"""Squeeze on real data: each file's order-0 entropy, what Squeeze achieves, and what lzma achieves."""
import lzma, math, time
from collections import Counter
from pathlib import Path
import numpy as np
import squeeze
def h0(data):
n = len(data)
return -sum(c / n * math.log2(c / n) for c in Counter(data).values())
def row(name, data):
t = time.perf_counter()
blob = squeeze.pack(data)
assert squeeze.unpack(blob) == data
xz = len(lzma.compress(data, preset=9 | lzma.PRESET_EXTREME))
print(f"{name:<22}{len(data):>9,}{h0(data):>9.3f}{8 * len(blob) / len(data):>9.3f} {squeeze.METHODS[blob[3]][0]:<11}"
f"{8 * xz / len(data):>7.3f}{time.perf_counter() - t:>7.1f}s")
print(f"{'file':<22}{'bytes':>9}{'order-0':>9}{'Squeeze':>9} {'method':<11}{'lzma':>7} (bits per byte)")
for f in sorted(Path("real").iterdir()):
row(f.name, f.read_bytes())
row("shakespeare.txt", Path("shakespeare.txt").read_bytes())
# The MRI's 16-bit samples, stored as the difference from the previous sample: a transform before the model
mri = np.frombuffer(Path("real/mri.raw").read_bytes(), dtype=">u2").astype(np.int32)
delta = np.diff(mri, prepend=0).astype(">i2").tobytes()
row("mri.raw, differences", delta)
assert np.array_equal(np.cumsum(np.frombuffer(delta, dtype=">i2").astype(np.int32)), mri) # and back again
file bytes order-0 Squeeze method lzma (bits per byte)
chloroplast.txt 154,478 1.945 1.930 order-1 2.164 1.3s
eeg.dat 25,600 7.614 7.692 huffman 7.598 0.3s
ls.bin 142,312 5.935 4.320 order-1 3.065 1.4s
mri.raw 131,072 2.380 2.209 order-1 1.556 1.1s
plays.gz 434,714 7.999 8.000 store 8.002 3.7s
udhr5.txt 49,359 5.795 3.494 order-1 2.442 0.5s
shakespeare.txt 1,115,394 4.779 3.531 order-1 2.614 10.9s
mri.raw, differences 131,072 2.335 1.659 order-1 1.410 0.8s
Step 3: read the table.
- The genome: Squeeze 1.930 bits per byte, one byte per base, so 1.93 bits per base, the chapter's best context figure and better than lzma (2.164). DNA's little structure is local, which an adaptive order-1 model captures and lzma's search for long repeats doesn't.
- The EEG recordings are 64-bit floating-point numbers: the low bytes of each are nearly random, so nothing helps much (7.69 bits per byte for Squeeze, 7.60 for lzma, against 8). Measurements stored as floats carry many bits of noise.
- The program (
ls): Squeeze 4.32, lzma 3.07. Machine code repeats instructions, addresses and strings at distances order-1 can't see; lzma's long-range matches find them. - The MRI scan: 2.21 bits per byte, but its samples are 16-bit with values up to 215, so the high byte of each is almost always 0, and order-1 learns that cheaply. lzma does better (1.56) because it finds the scan's repeated rows of background.
- The gzipped plays: 8.000 bits per byte, stored as is; lzma makes them slightly larger (8.002). Compressing compressed data gains nothing.
- Five scripts in one file: order-0 entropy 5.80 bits per byte, Squeeze 3.49, lzma 2.44. Each script has its own byte statistics, and a short sample of each gives an order-1 model little to learn from.
- The transform: storing each MRI sample as its difference from the previous one leaves the data exactly recoverable (checked by
assert) but makes neighbouring values cluster near zero; Squeeze drops from 2.209 to 1.659 bits per byte (25 % smaller), with no change to the model. PNG's filters, audio's predictive coding and video's motion compensation all do the same: transform so that a simple model sees simple data.
Senior and architect lens
- Measure on the data you'll have. Squeeze looked respectable on its four test files and is beaten by a factor of 1.4 on a program; formats chosen from a benchmark that doesn't resemble production data disappoint in production. Keep a corpus of real samples and rerun it whenever the compressor changes.
- Detect, don't fight, incompressible data. The store method costs nothing on the gzipped file; general-purpose systems (zstd, storage layers, HTTP servers) do the same, skipping compression for media types that are already compressed, because trying costs CPU for no gain.
- Model the structure, or transform it away. Two routes to better compression: a richer model (longer contexts, models of 16-bit numbers, of machine code), or a transform that turns the data's structure into something the existing model sees (differences, reverse complements, splitting fields into columns). Transforms are often cheaper, and they're how specialised formats beat general ones.
- Know what the numbers mean. Bits per byte is only comparable for data whose bytes are its symbols; for 16-bit samples or floats, report bits per sample, and for DNA, bits per base.
Evidence
make_real.py,realtest.pyand your table, every round trip checked.- For each of the eight rows, one sentence on what structure Squeeze's order-1 model can or can't see.
- The MRI transform, with the result, and one other transform you'd try for another file in the table (and why).
Carry forward
Stage 11, after chapter 11, turns the table's lesson into a better model: Squeeze will mix the predictions of several context orders, as chapter 10's blended model did, weight them by how well each has been predicting, and be measured by cross-entropy against lzma.