library(tidyverse)8 bzip2 and the Burrows–Wheeler transform
8.1 Introduction
Every method so far compresses data in the order it arrives. In 1983 David Wheeler, at the Cambridge Computer Laboratory, had a stranger idea: first rearrange the data so that it compresses better, in a way that can be undone. He and Michael Burrows published the method in 1994 as a research report from Digital Equipment Corporation’s Systems Research Center (Burrows and Wheeler 1994), and Julian Seward built the bzip2 compressor on it, first released in July 1996.
The rearrangement, now called the Burrows–Wheeler transform (BWT), sorts every rotation of a block of text and keeps only the last column of the sorted table. Characters that are followed by similar text end up next to each other, so the output is full of long runs of the same character, which are easy to compress. That the transform can be reversed at all, with no information beyond the transformed text and an end marker, looks like a magic trick the first time you see it. This chapter builds it, undoes it, and then uses the real bzip2.
Prerequisites
8.2 The transform
Take a short string and add an end marker, $, that appears nowhere else. List every rotation of it, sort the rotations, and read off the last character of each:
word <- "positron_proton"
s <- paste0(word, "$")
n <- nchar(s)
rotations <- vapply(0:(n - 1), \(i) paste0(substring(s, i + 1), substr(s, 1, i)), character(1))
table_sorted <- tibble(rotation = sort(rotations, method = "radix")) |>
mutate(
first = substr(rotation, 1, 1),
last = substr(rotation, n, n)
)
table_sorted
#> # A tibble: 16 × 3
#> rotation first last
#> <chr> <chr> <chr>
#> 1 $positron_proton $ n
#> 2 _proton$positron _ n
#> 3 itron_proton$pos i s
#> 4 n$positron_proto n o
#> 5 n_proton$positro n o
#> 6 on$positron_prot o t
#> 7 on_proton$positr o r
#> 8 ositron_proton$p o p
#> 9 oton$positron_pr o r
#> 10 positron_proton$ p $
#> 11 proton$positron_ p _
#> 12 ron_proton$posit r t
#> 13 roton$positron_p r p
#> 14 sitron_proton$po s o
#> 15 ton$positron_pro t o
#> 16 tron_proton$posi t isort(method = "radix") sorts by raw character codes, the same on every computer, so $ sorts before _, which sorts before the letters. The transform is the last column read top to bottom:
paste(table_sorted$last, collapse = "")
#> [1] "nnsootrpr$_tpooi"Look at why letters cluster. The two rotations that begin with n sit next to each other in the sorted table, so their last characters, the letters that come just before each n in the original, sit next to each other too. Both are o, because both ns in “positron_proton” end an on. Likewise, both the $ and the _ follow an n, so the transform begins nn. In a long text the effect is much stronger. Nearly every occurrence of he in English is preceded by t, s or a space, so the rotations beginning with he contribute a long stretch made mostly of those few letters.
Here is the transform as a function:
bwt <- function(text) {
s <- paste0(text, "$")
n <- nchar(s)
rotations <- vapply(0:(n - 1), \(i) paste0(substring(s, i + 1), substr(s, 1, i)), character(1))
sorted <- sort(rotations, method = "radix")
paste(substr(sorted, n, n), collapse = "")
}Real implementations never build the table of rotations, which would take memory proportional to the square of the block length. They sort the starting positions of the rotations directly, with algorithms related to the suffix arrays of computational biology, where the BWT also turns up in software that aligns DNA sequences.
8.3 Undoing it
The reverse transform rests on one observation. The first column is just the last column sorted, so the decoder knows both. And because every row is a rotation, the last character of each row comes immediately before its first character in the original text. With a little bookkeeping about which occurrence of each letter is which, that is enough to walk backwards through the text one character at a time, starting from the row that ends in $:
inverse_bwt <- function(transformed) {
last <- strsplit(transformed, "")[[1]]
n <- length(last)
# Where does each row go when its last character moves to the front?
# A stable sort of the last column answers that.
step_back <- integer(n)
step_back[order(last, method = "radix")] <- seq_len(n)
out <- character(n)
row <- which(last == "$")
for (k in n:1) {
out[k] <- last[row]
row <- step_back[row]
}
paste(out[-n], collapse = "")
}
inverse_bwt(bwt(word))
#> [1] "positron_proton"The key is that a stable sort keeps equal letters in their original order, so the third o in the last column is the third o in the first column. Advanced R would call step_back a lookup table built by subsetting (Wickham 2019, chap. 4): one line of vectorised R replaces the bookkeeping.
8.4 Why it compresses
On a few words the transform is a curiosity. On a page of text it is powerful. Here is a paragraph of physics prose, transformed:
paragraph <- paste(
"the muon is an unstable particle with the same charge as the electron",
"but about two hundred times the mass. the muon decays to an electron",
"and two neutrinos with a mean lifetime of about two microseconds, and",
"the muons made by cosmic rays in the upper atmosphere reach the ground",
"only because time dilation stretches that lifetime in the frame of the",
"earth. the same muons are a background in every underground detector,",
"and the deeper the detector the fewer the muons that reach it."
)
paragraph <- gsub(" ", "_", paragraph)
transformed <- bwt(paragraph)
substr(transformed, 1, 120)
#> [1] ".rstshehtfos,,nserayneeynedeeeneneeeodesnhtnseaoeeeeeoeedecteeenssdrfsrnhs.drh.nedsttdynese__t__eebmssr_e_____hep_mhhl_c"Runs of e, t, _ and h appear everywhere. consecutive_id() from dplyr numbers the runs, which makes them easy to count:
run_lengths <- function(text) {
tibble(char = strsplit(text, "")[[1]]) |>
mutate(run = consecutive_id(char)) |>
count(run)
}
tibble(
version = c("original", "transformed"),
mean_run_length = c(
mean(run_lengths(paragraph)$n),
mean(run_lengths(transformed)$n)
)
)
#> # A tibble: 2 × 2
#> version mean_run_length
#> <chr> <dbl>
#> 1 original 1.01
#> 2 transformed 1.52bzip2 then turns the runs into small numbers with move-to-front coding. Keep a list of the alphabet; for each character, output its current position in the list and move it to the front. A run of identical characters becomes a run of zeros after its first character, and characters that were used recently get small numbers:
move_to_front <- function(chars, alphabet) {
out <- integer(length(chars))
for (i in seq_along(chars)) {
position <- match(chars[i], alphabet)
out[i] <- position - 1L
alphabet <- c(chars[i], alphabet[-position])
}
out
}
transformed_chars <- strsplit(transformed, "")[[1]]
mtf <- move_to_front(transformed_chars, sort(unique(transformed_chars), method = "radix"))
head(mtf, 40)
#> [1] 2 19 20 21 1 14 12 1 3 13 20 5 9 0 20 2 7 8 12 25 5 4 0 2
#> [25] 2 2 16 1 0 0 2 1 1 1 0 0 8 3 2 7
mean(mtf == 0)
#> [1] 0.3409091About a third of the output is zero, and small numbers dominate the rest. Compare the entropy of the original characters with the entropy of the move-to-front numbers, using the function from Chapter 4:
entropy_bits <- function(x) {
p <- table(x) / length(x)
-sum(p * log2(p))
}
c(
original_characters = entropy_bits(strsplit(paragraph, "")[[1]]),
after_bwt_and_mtf = entropy_bits(mtf)
)
#> original_characters after_bwt_and_mtf
#> 4.015115 3.606446The transform did not remove any information; it can be undone exactly. It moved the information into a form whose single-symbol statistics a Huffman code can exploit. The gain on one paragraph is modest, because a paragraph offers few repeated contexts. It grows with the length of the block. To show that, we need a faster transform. Because the end marker is unique and sorts first, sorting the rotations gives the same order as sorting the suffixes, the tails of the text starting at each position, and R can sort those directly. Each output character is then the one just before its suffix:
bwt_fast <- function(text) {
s <- paste0(text, "$")
n <- nchar(s)
starts <- order(substring(s, 1:n), method = "radix")
chars <- strsplit(s, "")[[1]]
paste(chars[ifelse(starts == 1, n, starts - 1)], collapse = "")
}
identical(bwt_fast(paragraph), bwt(paragraph))
#> [1] TRUENow take a longer text, the source of this very chapter. Keep only its plain ASCII characters, so that every character is one byte, and remove its $ signs, so that the end marker stays unique. Then transform blocks of increasing length:
chapter <- readLines("08-bzip2.qmd", encoding = "UTF-8") |>
paste(collapse = "\n") |>
iconv(from = "UTF-8", to = "ASCII", sub = "") |>
gsub(pattern = "$", replacement = "", fixed = TRUE)
bits_after_bwt <- function(block_size) {
block <- substr(chapter, 1, block_size)
chars <- strsplit(bwt_fast(block), "")[[1]]
entropy_bits(move_to_front(chars, sort(unique(chars), method = "radix")))
}
tibble(block_size = c(500, 1000, 2000, 4000, 8000, 16000)) |>
mutate(
original_bits = map_dbl(block_size, \(b) entropy_bits(strsplit(substr(chapter, 1, b), "")[[1]])),
bwt_mtf_bits = map_dbl(block_size, bits_after_bwt)
)
#> # A tibble: 6 × 3
#> block_size original_bits bwt_mtf_bits
#> <dbl> <dbl> <dbl>
#> 1 500 4.77 4.58
#> 2 1000 4.65 4.25
#> 3 2000 4.72 3.93
#> 4 4000 4.67 3.51
#> 5 8000 4.73 3.24
#> 6 16000 4.81 3.19The longer the block, the more contexts repeat, and the further the entropy falls. That is why bzip2 uses blocks of up to 900 kilobytes. Its full pipeline adds two run-length encoding stages and a Huffman code, with several code tables chosen for different stretches of each block.
8.5 bzip2 in R
R has bzip2 built in. memCompress(x, "bzip2") compresses a raw vector, bzfile() opens a connection to a .bz2 file, and readr reads and writes .csv.bz2 by extension. Every bzip2 stream begins with the letters BZh and a digit giving the block size in hundreds of kilobytes; R uses the largest, 900 kB:
csv_bytes <- memDecompress(
readBin("data/dimuon.csv.gz", "raw", file.size("data/dimuon.csv.gz")),
type = "gzip"
)
bz <- memCompress(csv_bytes, type = "bzip2")
rawToChar(bz[1:4])
#> [1] "BZh9"Text made of digits suits the transform well. Here is the dimuon CSV compressed with gzip and bzip2, with the time each takes to compress and to decompress:
time_codec <- function(method) {
compress_s <- system.time(packed <- memCompress(csv_bytes, type = method))[["elapsed"]]
decompress_s <- system.time(memDecompress(packed, type = method))[["elapsed"]]
tibble(
method = method,
megabytes = length(packed) / 1e6,
compress_s = compress_s,
decompress_s = decompress_s
)
}
map(c("gzip", "bzip2"), time_codec) |>
list_rbind()
#> # A tibble: 2 × 4
#> method megabytes compress_s decompress_s
#> <chr> <dbl> <dbl> <dbl>
#> 1 gzip 2.47 0.100 0
#> 2 bzip2 2.09 0.35 0.27bzip2 makes the smaller file, and it pays for it in time, in both directions. Decompression is where it differs most from the Lempel–Ziv methods: an LZ77 decoder just copies bytes, while a BWT decoder must undo the sort, which is much more work. Because each 900 kB block is transformed independently, though, bzip2 is easy to parallelise, and tools like pbzip2 and lbzip2 compress and decompress on many cores at once.
bzip2 earned a place in many archives in the late 1990s and 2000s, including Linux source tarballs and the Wikipedia database dumps. For new work, xz and Zstandard usually beat it on both size and speed (Chapter 9, Chapter 10), and Parquet does not offer it at all. But its files remain readable everywhere, its format has not changed since version 1.0, and the idea at its heart, sorting to expose structure, is one of the most beautiful in the subject.
8.6 Summary
The Burrows–Wheeler transform sorts all rotations of a block and keeps the last column, which groups together characters that precede similar contexts. It is reversible from the transformed text alone, using a stable sort to track which occurrence of each character is which. Move-to-front coding turns its runs into mostly zeros, and a Huffman code finishes the job. In R, memCompress(), bzfile() and readr all speak bzip2. It compresses text more tightly than gzip, but it is slower, especially to decompress.
8.7 Exercises
- Apply
bwt()to"banana"and then to"abracadabra". Check thatinverse_bwt()recovers both. - The transform needs an end marker that does not occur in the text. What goes wrong in
inverse_bwt()if the text contains$? - Compute the mean run length after the transform for a string of random letters of the same length as
paragraph, made withsample(letters, 600, replace = TRUE). Why is there almost no improvement? - Compress the star catalog CSV with gzip, bzip2 and xz using
memCompress(). Which is smallest? Which is fastest to decompress? - Write the magnetometer data with
write_csv()to files ending in.csv.gzand.csv.bz2. Compare the sizes and the timeread_csv()takes to read each.