library(tidyverse)4 Entropy and the limits of compression
4.1 Introduction
In 1948 Claude Shannon published “A Mathematical Theory of Communication” (Shannon 1948), and with it gave a precise answer to a question that sounds vague: how much information is in a message? His answer is a number, the entropy, measured in bits. For a source that emits symbol i with probability pi,
\[ H = -\sum_i p_i \log_2 p_i \quad \text{bits per symbol.} \]
Any physicist will recognise the formula. It is the Gibbs entropy of statistical mechanics, \(S = -k_B \sum_i p_i \ln p_i\), with the logarithm taken to base 2 and Boltzmann’s constant dropped; the two differ only by the factor \(k_B \ln 2\). The connection is more than notation. Rolf Landauer showed that erasing one bit of information in any physical device must dissipate at least \(k_B T \ln 2\) of heat (Landauer 1961), and he spent years arguing that information is physical (Landauer 1991).
Shannon also proved the result that governs every compressor in this book, his source coding theorem: no lossless code can use fewer than H bits per symbol on average, and codes exist that come as close to H as you like. Entropy is the floor. This chapter measures it with dplyr, shows real compressors pressing against it, and draws the practical lesson that matters most to physicists: noise does not compress, so digits beyond the precision of your instrument cost real disk space.
Prerequisites
4.2 Measuring entropy
Start with a photon counter: a detector that reports how many photons arrived in each millisecond. With a steady source, the counts follow a Poisson distribution, here with a mean of 2.5. A million readings:
set.seed(1948)
photons <- tibble(count = rpois(1e6, lambda = 2.5))
photons |>
count(count) |>
mutate(p = n / sum(n))
#> # A tibble: 14 × 3
#> count n p
#> <int> <int> <dbl>
#> 1 0 82325 0.0823
#> 2 1 205055 0.205
#> 3 2 256451 0.256
#> 4 3 214543 0.215
#> 5 4 132865 0.133
#> 6 5 67085 0.0671
#> 7 6 27722 0.0277
#> 8 7 9802 0.00980
#> 9 8 3064 0.00306
#> 10 9 829 0.000829
#> 11 10 186 0.000186
#> 12 11 64 0.000064
#> 13 12 8 0.000008
#> 14 13 1 0.000001The entropy is a short pipeline: estimate each probability from its frequency, then apply Shannon’s formula.
photons |>
count(count) |>
mutate(p = n / sum(n)) |>
summarise(entropy_bits = -sum(p * log2(p)))
#> # A tibble: 1 × 1
#> entropy_bits
#> <dbl>
#> 1 2.64We will want this often, so here it is as a function. Inside a function, base R’s table() does the counting in one step:
entropy_bits <- function(x) {
p <- table(x) / length(x)
-sum(p * log2(p))
}
entropy_bits(photons$count)
#> [1] 2.639837For a Poisson distribution the probabilities are known exactly, so the true entropy is a sum over dpois(). The estimate from a million samples agrees with it to three decimal places:
p_exact <- dpois(0:40, lambda = 2.5)
-sum(p_exact * log2(p_exact))
#> [1] 2.64118So each reading carries about 2.6 bits of information, yet a computer stores it in a byte, 8 bits, or more often in a 4-byte integer.
4.3 Pressing against the floor
If each count occupies one byte, a million counts take a million bytes. The counts are independent of each other, so Shannon’s theorem says no lossless compressor can make them smaller than a million times 2.64 bits, or about 330 kilobytes. Base R’s memCompress() gives us four real compressors to try, each covered in a later chapter; "none" returns the input unchanged:
counts_raw <- as.raw(photons$count)
compression <- tibble(method = c("none", "gzip", "bzip2", "xz", "zstd")) |>
mutate(
bytes = map_dbl(method, \(m) length(memCompress(counts_raw, type = m))),
bits_per_count = 8 * bytes / length(counts_raw)
)
compression
#> # A tibble: 5 × 3
#> method bytes bits_per_count
#> <chr> <dbl> <dbl>
#> 1 none 1000000 8
#> 2 gzip 370944 2.97
#> 3 bzip2 369615 2.96
#> 4 xz 357452 2.86
#> 5 zstd 412363 3.30None of them beats the entropy of 2.64 bits per count, and none can. The best, xz, comes within about 8% of it. zstd, at the default setting memCompress() uses, is furthest away, because it is tuned for speed rather than for the last few percent (Chapter 10). All four are general-purpose tools that have to discover the statistics of the data as they go; Chapter 5 builds a code from the known probabilities and gets closer than any of them.
4.4 The binary entropy curve
The simplest source of all emits 1 with probability p and 0 otherwise. Its entropy,
\[ H(p) = -p \log_2 p - (1 - p) \log_2 (1 - p), \]
is 1 bit when the two outcomes are equally likely and falls to zero as one becomes certain. A rare event, like a hit in a mostly empty detector channel, carries little information on average, because most of the time it does not happen.
To compare real compressors with the curve, draw a million random bits, pack them eight to a byte with packBits(), compress them, and count the bits per original bit:
binary_entropy <- function(p) -p * log2(p) - (1 - p) * log2(1 - p)
compressed_bits <- function(p, method, n = 2^20) {
bits <- runif(n) < p
packed <- packBits(bits, type = "raw")
8 * length(memCompress(packed, type = method)) / n
}
set.seed(1951)
measured <- expand_grid(
p = c(0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5),
method = c("gzip", "bzip2", "xz")
) |>
mutate(bits_per_symbol = map2_dbl(p, method, compressed_bits))ggplot(measured, aes(x = p, y = bits_per_symbol)) +
geom_function(fun = binary_entropy, n = 400, colour = "grey30") +
geom_point(aes(colour = method, shape = method), size = 2.2) +
scale_x_log10(breaks = c(0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5)) +
labs(
x = "Probability of a 1",
y = "Bits per symbol",
colour = "Compressor",
shape = "Compressor"
)
Every point lies on or above the curve. Where the curve is low, at small p, the compressors have the most room to work and the differences between them show most clearly. At p = 0.5 the bits are pure noise, the entropy is 1 bit per bit, and nothing can be squeezed out at all; the compressors there produce slightly more than they were given, because they add headers and bookkeeping to data they cannot shrink.
4.5 Noise does not compress
Real data is mostly signal plus noise, and the noise is where the bits go. The magnetometer from Chapter 2 records the field to 0.01 nT once a second, but the instrument’s noise is several times larger than that:
magnetometer <- read_csv("data/magnetometer.csv.gz")
bx <- magnetometer$bx_ntConsider three ways to store the bx column. As R stores it, each reading is an 8-byte double. Since every reading is a whole number of hundredths of a nanotesla, it could equally be a 4-byte integer count of 0.01 nT. And since the field changes slowly, we could store the first reading and then only the difference between each reading and the one before; this is delta encoding, and the original values come back with a cumulative sum. All three hold exactly the same information:
bx_counts <- as.integer(round(bx * 100)) # units of 0.01 nT
bx_deltas <- c(bx_counts[1], diff(bx_counts))
identical(cumsum(bx_deltas), bx_counts)
#> [1] TRUETheir entropies per reading are very different. The values themselves wander over thousands of distinct levels during the day; the differences are dominated by the noise, which spreads over only a few dozen:
tibble(
representation = c("values", "differences"),
distinct_levels = c(n_distinct(bx_counts), n_distinct(bx_deltas)),
entropy_bits = c(entropy_bits(bx_counts), entropy_bits(bx_deltas))
)
#> # A tibble: 2 × 3
#> representation distinct_levels entropy_bits
#> <chr> <int> <dbl>
#> 1 values 5702 12.2
#> 2 differences 77 5.14Here is what the compressors make of each representation. writeBin() turns a vector into the raw bytes a computer would store:
representations <- list(
doubles = writeBin(bx, raw()),
integers = writeBin(bx_counts, raw()),
deltas = writeBin(bx_deltas, raw())
)
storage <- expand_grid(
representation = names(representations),
method = c("none", "gzip", "xz", "zstd")
) |>
mutate(
bytes = map2_dbl(
representation, method,
\(r, m) length(memCompress(representations[[r]], type = m))
),
bits_per_reading = 8 * bytes / length(bx)
)
storage |>
select(!bytes) |>
pivot_wider(names_from = method, values_from = bits_per_reading)
#> # A tibble: 3 × 5
#> representation none gzip xz zstd
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 doubles 64 12.3 7.85 12.4
#> 2 integers 32 9.47 6.25 10.4
#> 3 deltas 32 7.80 5.87 7.83Several lessons sit in that table. First, compressors see bytes, not numbers. The doubles and the integers hold the same information, but the doubles compress worse with every method, because the 52-bit fraction of a double like 20452.37 is a long, irregular string of bits that the compressors cannot connect to the simple integer underneath. Second, the representation that exposes the structure wins: the differences compress best with every method, and by a wide margin with the fast ones, gzip and zstd. xz, which models its input more thoroughly, finds much of the same structure on its own.
Third, look at xz on the integers: about 6.3 bits per reading, half the 12.2-bit entropy of the values. That does not break Shannon’s theorem, because the per-reading entropy of the values is the wrong floor. It treats each reading as if it arrived alone, but neighbouring readings are nearly equal, so a new reading tells you little that the previous one did not. Shannon’s floor is the entropy rate, the information each symbol adds given everything before it. For the magnetometer, the entropy of the differences, 5.1 bits, is a good estimate of that rate, and no compressor gets below it. That floor is set by the noise, and only changing the data can lower it.
4.6 Precision is a choice
How much of that noise do you need? The magnetometer’s random noise is about 0.06 nT per reading, so the last digit of a reading to 0.01 nT is mostly noise. Rounding to a coarser resolution throws information away, which makes it lossy compression, and it adds an error of its own: rounding to a step r adds a uniformly distributed error with standard deviation \(r/\sqrt{12}\), which combines with the instrument noise in quadrature. Here is the trade at four resolutions: the entropy of the differences, the size of the compressed column, and the total noise afterwards.
precision <- tibble(resolution_nt = c(0.01, 0.02, 0.05, 0.1)) |>
mutate(
deltas = map(resolution_nt, \(r) as.integer(diff(round(bx / r)))),
entropy_bits = map_dbl(deltas, entropy_bits),
xz_kb = map_dbl(deltas, \(d) length(memCompress(writeBin(d, raw()), "xz")) / 1e3),
total_noise_nt = sqrt(0.06^2 + resolution_nt^2 / 12)
) |>
select(!deltas)
precision
#> # A tibble: 4 × 4
#> resolution_nt entropy_bits xz_kb total_noise_nt
#> <dbl> <dbl> <dbl> <dbl>
#> 1 0.01 5.14 63.5 0.0601
#> 2 0.02 4.14 50.2 0.0603
#> 3 0.05 2.86 33.6 0.0617
#> 4 0.1 1.98 22.0 0.0666Each factor of two in resolution saves about a bit per reading, as it must: halving the number of distinguishable levels removes one yes-or-no question from each measurement. At 0.02 nT the file shrinks by a fifth and the noise grows by less than one percent, which is free. At 0.1 nT the file is about a third of its original size, but the noise has grown by about ten percent, which may or may not matter for your science. The slow variations, the sudden impulse and the quiet-day curve survive all four, because they are tens of nanotesla tall.
This is the most useful fact in this part of the book: store the precision you measured, not the precision your computer offers. A double has 15 to 16 significant digits. A detector, a thermometer or a magnetometer has three to six. Climate scientists have shown that most of the bits in typical atmospheric model output carry no real information, and that removing them before compression shrinks the data many times over while keeping the information that is there (Klöwer et al. 2021). Astronomers have done the same for decades. The FITS tile-compression convention quantizes floating-point images in steps set by their noise before applying Rice coding, an algorithm Robert Rice developed at the Jet Propulsion Laboratory for spacecraft data (Rice 1979; Pence et al. 2009).
Where exactly to round is a scientific decision, not a technical one. A safe rule of thumb is to keep the resolution several times finer than the noise: fine enough that rounding adds a negligible amount to it, coarse enough that you are not paying to store noise in high fidelity. Whatever you choose, write it down next to the data.
4.7 Summary
Shannon’s entropy, the same function as the Gibbs entropy, measures the information in a source in bits per symbol, and his source coding theorem makes it a hard floor: no lossless compressor can beat it. You estimated entropy with a three-line dplyr pipeline, watched gzip, bzip2, xz and zstd approach the floor for Poisson counts and random bits but never cross it, and saw that random noise cannot be compressed at all. When neighbouring values are correlated, the floor is the entropy rate, the new information per symbol, which can be far below the entropy of one value taken alone. For real measurements, the representation matters, because compressors see bytes: integers beat doubles, and differences beat values. And the precision you choose to keep sets the entropy itself, which makes rounding to your instrument’s real resolution the most effective compression step you can take.
4.8 Exercises
- Compute
entropy_bits()for therun,mu1_chargeandmu1_ptcolumns of the dimuon data. Explain the three answers. Why is the entropy ofmu1_ptclose to the logarithm of the number of distinct values it takes? - Repeat the photon-counter calculation for means of 0.1, 1, 10 and 100. Plot the entropy against the mean on a logarithmic axis and compare it with the large-mean approximation \(H \approx \tfrac{1}{2} \log_2 (2 \pi e \lambda)\).
- Compressors struggle with doubles because the bytes of each number are interleaved. Reorder them so that all the first bytes come first, then all the second bytes, and so on:
matrix(writeBin(bx, raw()), nrow = 8) |> t() |> as.vector(). How much better doesmemCompress()do on the result? (HDF5’s shuffle filter and Parquet’sBYTE_STREAM_SPLITencoding apply the same trick.) - Use Landauer’s bound to estimate the minimum heat dissipated in erasing one terabyte at room temperature. How does it compare with the energy a real hard drive uses to do the same?
- Find the resolution at which the entropy of the magnetometer differences falls below one bit per reading. Plot the reconstructed
bxat that resolution withcumsum(). What has been lost?