TExcelTAD
Home › Information Theory › Lempel-Ziv Coding

Lempel-Ziv Coding

Huffman and arithmetic coding need a probability model. Lempel-Ziv (LZ) methods need none: they replace repeated strings by references to earlier occurrences, learning the "model" implicitly from the data. They are universal: for any stationary source, their rate approaches the entropy rate as the data grow. LZ variants are inside zip, gzip, PNG, 7z, Zstandard and many more.

LZ77: sliding-window references

LZ77 (Lempel and Ziv, 1977) scans the input and, at each position, looks for the longest match in a window of recent text. It outputs either a literal character or a pair (distance back, length).

python · try it yourself
def lz77_encode(s, window=255, min_len=3):
    i, out = 0, []
    while i < len(s):
        best_len, best_dist = 0, 0
        for j in range(max(0, i - window), i):
            k = 0
            while i + k < len(s) and s[j + k] == s[i + k] and k < 255:
                k += 1                                     # matches may overlap the current position
            if k > best_len:
                best_len, best_dist = k, i - j
        if best_len >= min_len:
            out.append((best_dist, best_len)); i += best_len
        else:
            out.append(s[i]); i += 1
    return out

def lz77_decode(tokens):
    out = []
    for t in tokens:
        if isinstance(t, tuple):
            d, n = t
            for _ in range(n):
                out.append(out[-d])
        else:
            out.append(t)
    return "".join(out)

text = "abracadabra abracadabra abracadabra!"
tokens = lz77_encode(text)
print(tokens)
print("round trip ok:", lz77_decode(tokens) == text, " tokens:", len(tokens), "for", len(text), "chars")
['a', 'b', 'r', 'a', 'c', 'a', 'd', (7, 4), ' ', (12, 23), '!']
round trip ok: True  tokens: 11 for 36 chars

The token (12, 23) copies 23 characters from only 12 back: the copy overlaps its own output, which is how LZ77 encodes repeats longer than the distance. In the same way (1, 10) after an a produces ten more as, so run-length encoding comes for free.

LZ78 and LZW: a growing dictionary

LZ78 (1978) builds a dictionary of phrases. Each output is (index of the longest known phrase, next character), and that extended phrase is added to the dictionary. LZW, a variant used in GIF and Unix compress, outputs only indices.

python · try it yourself
import math

def lz78_parse(s):
    dictionary, phrase, out = {"": 0}, "", []
    for ch in s:
        if phrase + ch in dictionary:
            phrase += ch
        else:
            out.append((dictionary[phrase], ch))
            dictionary[phrase + ch] = len(dictionary)
            phrase = ""
    if phrase:
        out.append((dictionary[phrase], ""))
    return out

pairs = lz78_parse("abababababababab")
print(pairs)
[(0, 'a'), (0, 'b'), (1, 'b'), (3, 'a'), (2, 'a'), (5, 'b'), (4, 'b')]

The phrases grow longer as the dictionary learns the data: a, b, ab, aba, ba, bab, ...

Universality

For a source with entropy rate HH, the number of LZ78 phrases c(n)c(n) in nn symbols satisfies c(n)log⁡2c(n)n→H\frac{c(n)\log_2 c(n)}{n} \to H. Each phrase costs about log⁡2c(n)\log_2 c(n) bits for the index plus a few for the character, so the rate approaches the entropy rate, without knowing the source. The convergence is slow, which is why practical compressors add entropy coding on top.

python · try it yourself
import math
import numpy as np

def lz78_bits(s):
    dictionary, phrase, bits = {"": 0}, "", 0
    for ch in s:
        if phrase + ch in dictionary:
            phrase += ch
        else:
            bits += math.ceil(math.log2(len(dictionary))) + 1      # index + one binary character
            dictionary[phrase + ch] = len(dictionary); phrase = ""
    return bits

rng = np.random.default_rng(0)
p = 0.1
H = -p * math.log2(p) - (1 - p) * math.log2(1 - p)
for n in [1_000, 10_000, 100_000, 1_000_000]:
    s = "".join(np.where(rng.random(n) < p, "1", "0"))
    print(f"n = {n:8d}: LZ78 {lz78_bits(s) / n:.4f} bits/symbol   (H = {H:.4f})")
n =     1000: LZ78 0.6890 bits/symbol   (H = 0.4690)
n =    10000: LZ78 0.6468 bits/symbol   (H = 0.4690)
n =   100000: LZ78 0.5904 bits/symbol   (H = 0.4690)
n =  1000000: LZ78 0.5589 bits/symbol   (H = 0.4690)

Sources with memory

LZ shines when the data have long-range structure that a symbol-by-symbol model misses. Text with repeated words compresses far below its single-letter entropy:

python · try it yourself
import numpy as np
import zlib

rng = np.random.default_rng(1)
words = ["information", "theory", "entropy", "channel", "code", "bit", "noise", "capacity"]
text = " ".join(rng.choice(words, size=20_000)).encode()
_, counts = np.unique(np.frombuffer(text, dtype=np.uint8), return_counts=True)
q = counts / counts.sum()
print(f"letter entropy: {-np.sum(q * np.log2(q)):.3f} bits/char")
print(f"zlib (LZ77 + Huffman): {8 * len(zlib.compress(text, 9)) / len(text):.3f} bits/char")
print(f"word entropy / avg chars per word: {np.log2(len(words)) / (len(text) / 20_000):.3f} bits/char")
letter entropy: 3.860 bits/char
zlib (LZ77 + Huffman): 0.735 bits/char
word entropy / avg chars per word: 0.406 bits/char

The true entropy rate is log⁡28=3\log_2 8 = 3 bits per word, divided by the average word length (including the space). zlib discovers the words on its own and gets well below the letter entropy.

In software

  • zlib/gzip use LZ77 with a 32 KB window plus Huffman coding; lzma uses LZ77 with a huge window plus a range coder; Zstandard and LZ4 tune LZ77 for speed.
  • Decompression of LZ77 is just copying, so it is extremely fast; compression speed depends on how hard the encoder searches for matches (hash chains, suffix arrays).

Exercises

Exercise 1: Decode LZ77

Decode the tokens a, b, (2, 6), c.

Answer

abababab followed by c: ababababc.

Solution

(2, 6) copies 6 characters starting 2 back, one at a time: a b a b a b, overlapping its own output.

Exercise 2: LZ78 by hand

Parse aaaaaa with LZ78.

Answer

(0, a), (1, a), (2, a): the phrases a, aa, aaa.

Solution

Each step extends the longest known phrase by one character, so a run of length nn takes about 2n\sqrt{2n} phrases.

Exercise 3: Compress your own data (code)

Compare zlib, bz2 and lzma on 50,000 bytes from a binary Markov source that repeats the previous bit with probability 0.95 (packed into bytes).

Answer

All three need well under 1 bit per bit; the entropy rate is 0.286.

Solution
python · try it yourself
import numpy as np
import zlib, bz2, lzma

rng = np.random.default_rng(2)
n = 400_000
switch = rng.random(n) < 0.05
bits = (np.cumsum(switch) % 2).astype(np.uint8)
data = np.packbits(bits).tobytes()
for m in (zlib, bz2, lzma):
    print(f"{m.__name__:5s}: {8 * len(m.compress(data)) / n:.3f} bits per bit")
zlib : 0.391 bits per bit
bz2  : 0.370 bits per bit
lzma : 0.366 bits per bit

Test yourself

LZ77 replaces a repeated string by…

  1. a (distance, length) reference to an earlier occurrence
  2. its Huffman codeword
  3. its hash
  4. its probability

Lempel-Ziv codes are called universal because…

  1. they approach the entropy rate of any stationary source without knowing its statistics
  2. they work on every file type at the same ratio
  3. they are used everywhere
  4. they never expand data

Why do zip and gzip add Huffman coding after LZ77?

  1. LZ77 output tokens still have skewed frequencies that entropy coding can exploit
  2. LZ77 is lossy
  3. Huffman makes LZ77 universal
  4. to encrypt the output