Skip to main content

6  Dictionaries: LZ77, LZ78 and LZW

6.1 Introduction

A Huffman code looks at one symbol at a time. Give it the string ABCABCABCABC and it sees three letters, each a third of the time, and spends about 1.6 bits on each, even though the string is completely predictable after the first three letters. To capture structure longer than one symbol you need a different idea.

Abraham Lempel and Jacob Ziv, working at the Technion in Haifa, supplied it in two papers, in 1977 and 1978 (Ziv and Lempel 1977, 1978): replace a string you have seen before with a reference to the earlier copy. Their methods need no table of probabilities and no knowledge of the source in advance; they learn the structure from the data as they go. Ziv and Lempel proved that for long inputs these “universal” methods compress as well as any method designed with full knowledge of the source’s statistics. Nearly every compressor in use today, from gzip to Zstandard, is built on one of their two ideas.

Physics data is full of repeats for these methods to find: zero-suppressed detector readouts that are mostly empty, pulses of the same shape, periodic signals, and simulations whose configurations change little from one step to the next.

Prerequisites

library(tidyverse)

6.2 LZ77: point back into the past

The 1977 method, now called LZ77, keeps a sliding window over the most recent part of the input. At each position it looks back through the window for the longest string that matches what comes next, and emits a token of three parts: how far back the match starts (the offset), how long it is (the length), and the next character after it. A token with length zero is just a literal character.

Here is a direct, slow implementation. It is written for clarity, with loops, because each token depends on where the previous one ended:

lz77_encode <- function(text, window = 4096) {
  x <- strsplit(text, "")[[1]]
  n <- length(x)
  tokens <- vector("list", n)
  n_tokens <- 0
  i <- 1
  while (i <= n) {
    best_length <- 0
    best_offset <- 0
    if (i > 1) {
      for (j in max(1, i - window):(i - 1)) {
        len <- 0
        while (i + len < n && x[j + len] == x[i + len]) len <- len + 1
        if (len > best_length) {
          best_length <- len
          best_offset <- i - j
        }
      }
    }
    n_tokens <- n_tokens + 1
    tokens[[n_tokens]] <- tibble(
      offset = best_offset,
      length = best_length,
      next_char = x[i + best_length]
    )
    i <- i + best_length + 1
  }
  bind_rows(tokens[seq_len(n_tokens)])
}

Take a digitizer channel that reads zero most of the time and records two identical pulses, each three samples long. Written as one character per sample:

readout <- "000000000000000037100000000000000000000371000000000000"
nchar(readout)
#> [1] 54

readout_tokens <- lz77_encode(readout)
readout_tokens
#> # A tibble: 6 × 3
#>   offset length next_char
#>    <dbl>  <dbl> <chr>    
#> 1      0      0 0        
#> 2      1     15 3        
#> 3      0      0 7        
#> 4      0      0 1        
#> 5     19     16 0        
#> 6     23     17 0

54 characters became 6 tokens. The first run of zeros collapses into a single reference one character back, with a length of 15: a match may run past its own starting point and into the text it is still describing, which is how LZ77 codes a run. The second pulse, 371, is never spelled out. The last token copies 17 characters from 23 positions back, a stretch that takes in the first pulse and the zeros on either side of it.

Decoding is simpler than encoding, and much faster, which is a property every LZ77 descendant shares: copy length characters starting offset characters back, one at a time, then append the next character. Copying one character at a time is what makes overlapping matches work.

lz77_decode <- function(tokens) {
  out <- character(sum(tokens$length + 1))
  pos <- 0
  for (k in seq_len(nrow(tokens))) {
    for (m in seq_len(tokens$length[k])) {
      out[pos + 1] <- out[pos + 1 - tokens$offset[k]]
      pos <- pos + 1
    }
    pos <- pos + 1
    out[pos] <- tokens$next_char[k]
  }
  paste(out, collapse = "")
}

identical(lz77_decode(readout_tokens), readout)
#> [1] TRUE

Real implementations differ from this one in the details. They find matches with hash tables instead of a search through the whole window, they emit literals and matches as separate kinds of token rather than always attaching a next character, and they compress the tokens themselves with an entropy coder. DEFLATE, the subject of Chapter 7, does exactly that with Huffman codes. But the idea is the one above, and the size of the window is the parameter that matters most: a repeat further back than the window is invisible. DEFLATE’s window is 32 kilobytes; xz’s can be more than a gigabyte (Chapter 9).

6.3 LZ78 and LZW: build a dictionary

The 1978 method, LZ78, takes the other approach. Instead of a window of raw text, it builds an explicit dictionary of phrases. It reads the input as a sequence of phrases, each of which is the longest phrase already in the dictionary plus one new character, and that new phrase becomes the next dictionary entry. In 1984 Terry Welch published a variant, LZW (Welch 1984), that starts the dictionary with every single character and emits nothing but dictionary indices. It was simple and fast, and it became the compressor in the Unix compress program and in the GIF image format.

An encoder needs fast lookups in a growing dictionary. An R environment can serve as one: like a hash table, it finds a name without searching through all the others.

lzw_encode <- function(text) {
  x <- strsplit(text, "")[[1]]
  dictionary <- new.env(hash = TRUE)
  for (ch in sort(unique(x))) assign(ch, length(dictionary) + 1L, envir = dictionary)

  codes <- integer(length(x))
  n_codes <- 0
  phrase <- ""
  for (ch in x) {
    candidate <- paste0(phrase, ch)
    if (exists(candidate, envir = dictionary, inherits = FALSE)) {
      phrase <- candidate
    } else {
      n_codes <- n_codes + 1
      codes[n_codes] <- get(phrase, envir = dictionary)
      assign(candidate, length(dictionary) + 1L, envir = dictionary)
      phrase <- ch
    }
  }
  n_codes <- n_codes + 1
  codes[n_codes] <- get(phrase, envir = dictionary)

  phrases <- as.list(dictionary)
  list(
    codes = codes[seq_len(n_codes)],
    dictionary = tibble(phrase = names(phrases), index = unlist(phrases)) |>
      arrange(index)
  )
}

A good physical test is a one-dimensional Ising chain at low temperature: spins pointing up (U) or down (D), arranged in long domains with an occasional domain wall. In a simple model of such a chain, each spin flips relative to its neighbour with a small probability, here 2%. The entropy rate of that chain is the binary entropy of the flip probability, about 0.14 bits per spin, so a perfect compressor would store each spin in a seventh of a bit.

set.seed(1925)                     # Ising's thesis year
n_spins <- 50000
flips <- runif(n_spins) < 0.02
spins <- c("U", "D")[(cumsum(flips) %% 2) + 1]
chain <- paste(spins, collapse = "")

substr(chain, 1, 80)
#> [1] "UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"
chain_lzw <- lzw_encode(chain)
length(chain_lzw$codes)
#> [1] 1234

LZW turned 50,000 spins into 1,234 codes. Look at the dictionary it built along the way. Early entries are short; later ones are long runs of one spin, because each new phrase extends an old one:

chain_lzw$dictionary |>
  mutate(length = nchar(phrase)) |>
  ggplot(aes(x = index, y = length)) +
  geom_point(alpha = 0.25, size = 0.8) +
  labs(x = "Dictionary entry", y = "Phrase length (spins)")
A scatter plot of phrase length against dictionary entry for about 1,200 phrases. Lengths start at one or two spins and spread upward. The upper edge, made of pure runs of one spin, rises steadily to about 125 spins by the last entry.
Figure 6.1: LZW learns: the phrases it adds to its dictionary grow longer as it reads more of the Ising chain.

How good is it? Each code must be written with enough bits to address the dictionary at the time it is sent; with k entries that is log2 k bits. Summing that over the codes, and comparing with the entropy rate and with two modern compressors run on the same text:

lzw_bits <- sum(ceiling(log2(seq_along(chain_lzw$codes) + 2)))

chain_compression <- tibble(
  method = c("entropy rate", "LZW", "gzip", "xz"),
  bits_per_spin = c(
    -0.02 * log2(0.02) - 0.98 * log2(0.98),
    lzw_bits / n_spins,
    8 * length(memCompress(chain, "gzip")) / n_spins,
    8 * length(memCompress(chain, "xz")) / n_spins
  )
)

chain_compression
#> # A tibble: 4 × 2
#>   method       bits_per_spin
#>   <chr>                <dbl>
#> 1 entropy rate         0.141
#> 2 LZW                  0.231
#> 3 gzip                 0.222
#> 4 xz                   0.211

LZW comes within a factor of 1.6 of the entropy rate, with no knowledge of the chain at all, from a few dozen lines of code. gzip and xz, for all their refinements, do only a little better on input this short. Every one of them improves on a longer chain: a universal method converges only as it learns, and a chain of 50,000 spins contains only about a thousand domains to learn from.

6.4 A lesson about lasting

LZW’s history carries a lesson for anyone who wants their data readable in the future. Welch’s algorithm was patented, in the United States in 1985. When Jean-loup Gailly released gzip in 1992 (Chapter 7), he designed it to replace compress, and listed freedom from patented algorithms among its main advantages. At the end of 1994 the patent holder, Unisys, began asking for licence fees from software that wrote GIF images, and a group of programmers responded by designing PNG as a free replacement for GIF. Both gzip and PNG use DEFLATE. The LZW patents expired in 2003 and 2004, but by then the world had moved on, and the most widely used compression format on Earth is the one nobody could charge for.

6.5 Summary

The Lempel–Ziv methods compress by reference: LZ77 points back into a sliding window of recent input, and LZ78 and its variant LZW build a dictionary of phrases as they go. Both learn the structure of the data without being told its statistics, and both approach the entropy rate on long inputs. You built an LZ77 encoder and decoder and watched it compress the empty stretches and repeated pulses of a detector readout, and an LZW encoder that learned ever longer phrases from an Ising chain. In practice, LZ77’s descendants won: DEFLATE, LZ4, Snappy, LZMA and Zstandard are all LZ77 at heart, differing in their window sizes, their match finders and the entropy coders they put on top.

6.6 Exercises

  1. Encode a string of twenty As with lz77_encode(). How many tokens does it produce, and why does the second token’s length exceed its offset?
  2. Encode readout with window = 4. Which repeats can the encoder still find, and which can it not? How many tokens do you get?
  3. Run the Ising-chain comparison with flip probabilities of 0.2 and 0.002. For each, compute the entropy rate and the bits per spin of LZW, gzip and xz. Which method is closest to the floor, and does it depend on the temperature?
  4. Write lzw_decode(), which rebuilds the text from the codes alone. The decoder can rebuild the dictionary as it goes, except in one tricky case: a code that refers to the entry being created at that very step. Work out what the missing phrase must be.
  5. Lengthen the Ising chain to 200,000 spins. Does LZW get closer to the entropy rate? How does the length of the longest dictionary phrase grow with the length of the chain?