What Compression Can and Cannot Do
A compressor maps files to shorter files, and a decompressor maps them back. Before building one, it helps to know the hard limits: no lossless compressor can shrink every file, and the files it can shrink are exactly the ones that are predictable. Entropy measures how predictable a source is.
Lossless and lossy
- Lossless compression (zip, PNG, FLAC) must reproduce the input exactly. Its limit is the entropy (The Source Coding Theorem).
- Lossy compression (JPEG, MP3, video codecs) may change the input within some tolerance. Its limit is the rate-distortion function (Rate-Distortion Theory).
This chapter is about lossless compression, except for a counting argument in Raw Bit Content and Lossy Counting.
The counting argument
There are files of bits, but only files that are strictly shorter. So no lossless compressor can shrink every -bit file: at least one must stay the same length or grow (the pigeonhole principle).
n = 10
files = 2**n
shorter = sum(2**k for k in range(n))
print("files of", n, "bits:", files, " strictly shorter files:", shorter)
# how many files can be shrunk by at least 3 bits?
at_most = sum(2**k for k in range(n - 2))
print("at most", at_most, f"files ({at_most / files:.1%}) can lose 3 or more bits")files of 10 bits: 1024 strictly shorter files: 1023
at most 255 files (24.9%) can lose 3 or more bits
In general at most a fraction of files can be compressed by or more bits. Compression works only because real data are not uniformly random.
Random data do not compress
Real compressors confirm this. Uniform random bytes have entropy 8 bits per byte and do not shrink; text with patterns does:
import numpy as np
import zlib, bz2, lzma
rng = np.random.default_rng(0)
random_bytes = rng.integers(0, 256, 100_000, dtype=np.uint8).tobytes()
text = (" ".join(["the quick brown fox jumps over the lazy dog"] * 2300)).encode()[:100_000]
for name, data in [("random bytes", random_bytes), ("repetitive text", text)]:
sizes = {m.__name__: len(m.compress(data)) for m in (zlib, bz2, lzma)}
print(f"{name:16s} original {len(data)} ", sizes)random bytes original 100000 {'zlib': 100041, 'bz2': 100797, 'lzma': 100064}
repetitive text original 100000 {'zlib': 358, 'bz2': 171, 'lzma': 192}
The random bytes even grew a little: every format adds headers. Already-compressed or encrypted data look random, which is why zipping a zip file gains nothing.
Modelling and coding
Every lossless compressor has two parts:
- A model that assigns probabilities to the next symbol (fixed frequencies, context statistics, a dictionary of previous strings, or a neural network).
- A coder that turns probabilities into bits, using about bits for each symbol (Huffman or arithmetic coding).
The coder is a solved problem: arithmetic coding is within a fraction of a bit of the model's cross-entropy for the whole file (Arithmetic Coding). All the remaining progress is in the model. Better prediction means shorter files, which is why large language models are also very strong compressors.
import numpy as np
text = "abracadabra abracadabra abracadabra"
symbols, counts = np.unique(list(text), return_counts=True)
p = counts / counts.sum()
H0 = -np.sum(p * np.log2(p))
print(f"order-0 model: {H0:.3f} bits/char -> about {H0 * len(text):.0f} bits for {len(text)} chars")
# order-1 model: predict each character from the previous one
pairs = {}
for a, b in zip(text, text[1:]):
pairs.setdefault(a, []).append(b)
bits = 0.0
for a, nxt in pairs.items():
_, c = np.unique(nxt, return_counts=True); q = c / c.sum()
bits += len(nxt) * -np.sum(q * np.log2(q))
print(f"order-1 model: {bits / (len(text) - 1):.3f} bits/char")order-0 model: 2.240 bits/char -> about 78 bits for 35 chars
order-1 model: 0.773 bits/char
Predicting from the previous character cuts the cost sharply: after b the next letter is always r.
In software
- Python's
zlib(DEFLATE: LZ77 plus Huffman),bz2(Burrows-Wheeler transform) andlzma(LZ77 plus range coding) are three classic designs (Compression in Practice). - Always compress before encrypting, never after: encrypted data look random.
Exercises
Exercise 1: Compress everything?
A vendor claims their tool compresses every file by at least 1 bit. Why is that impossible?
Answer
There are fewer shorter files than files.
Solution
files of length would map one-to-one into at most shorter files, so two inputs would share an output and could not both be decompressed.
Exercise 2: Fraction compressible
What fraction of all 1000-bit files can be compressed to 990 bits or fewer?
Answer
Less than .
Solution
There are fewer than files of length at most 990, out of .
Exercise 3: Compressing a biased source (code)
Generate 100,000 bits with , pack them into bytes and compress with lzma. Compare bits per input bit with .
Answer
About 0.37 bits per input bit versus the entropy 0.286.
Solution
import numpy as np
import lzma
rng = np.random.default_rng(1)
bits = (rng.random(100_000) < 0.05).astype(np.uint8)
size = len(lzma.compress(np.packbits(bits).tobytes()))
H2 = -0.05 * np.log2(0.05) - 0.95 * np.log2(0.95)
print(f"lzma: {8 * size / bits.size:.3f} bits per bit, entropy {H2:.3f}")lzma: 0.374 bits per bit, entropy 0.286
General-purpose compressors see bytes, not bits, so they model this source imperfectly. An arithmetic coder with the right probability would get within a fraction of a percent of 0.286.
Test yourself
Why can no lossless compressor shrink every file?
- There are fewer short files than long files
- Compression is too slow
- Files contain headers
- Entropy is always 8 bits per byte
A lossless compressor consists of…
- a model of probabilities and a coder that turns them into bits
- only a dictionary
- a quantizer and a transform
- an encryption step
Why should you compress before encrypting?
- Encrypted data look random and do not compress
- Encryption needs compressed input
- It is faster to encrypt first
- Compression is a form of encryption