Skip to main content

1  The whole game

1.1 Introduction

This chapter takes one data set from a compressed file on disk to a figure you could put in a paper, and it uses every idea in the book along the way. It moves fast and explains little. Each step gets a chapter of its own later, and the cross-references tell you where. For now, watch the shape of the work: a short chain of verbs, each doing one thing, with physics at the end.

The data come from a collider detector (a simulated one; see the Preface). When a heavy, short-lived particle decays to a muon and an antimuon, the detector records the two muons. From their momenta you can compute the mass of whatever produced them. Plot those masses for a hundred thousand pairs, and the particles appear as peaks.

Prerequisites

The tidyverse packages read, transform and plot the data. The arrow package writes and reads Parquet files and handles data too big for memory.

library(tidyverse)
library(arrow)

1.2 Import

The muon pairs live in a gzip-compressed CSV file. readr’s read_csv() sees the .gz ending and decompresses the file as it reads, so there is nothing extra to do:

dimuon <- read_csv("data/dimuon.csv.gz")
dimuon
#> # A tibble: 119,528 × 10
#>      run event mu1_pt mu1_eta mu1_phi mu1_charge mu2_pt mu2_eta mu2_phi
#>    <dbl> <dbl>  <dbl>   <dbl>   <dbl>      <dbl>  <dbl>   <dbl>   <dbl>
#>  1  2301     1  11.3    1.49    1.64           1   5.53   1.96    1.86 
#>  2  2301     2  24.3    0.286  -0.640          1   4.77   0.223  -0.357
#>  3  2301     3  13.4   -1.45   -3.01           1  12.0   -1.59    2.89 
#>  4  2301     4  19.1    0.149   1.72           1  16.6   -0.034   1.93 
#>  5  2301     5  11.8   -2.21    2.19           1   7.29  -2.26    1.97 
#>  6  2301     6  11.1    1.39    1.08           1   4.57   1.37    0.635
#>  7  2301     7  14.5   -0.637   2.99           1   5.03  -0.813  -3.11 
#>  8  2301     8  16.7    0.246   1.60           1  11.4    0.391   1.32 
#>  9  2301     9   6.92   0.113   1.25          -1   4.55  -0.432   1.50 
#> 10  2301    10  16.4    2.35   -2.08          -1  12.7    2.17   -1.95 
#> # ℹ 119,518 more rows
#> # ℹ 1 more variable: mu2_charge <dbl>

Each row is one event: one pair of muons seen together. run and event identify it. For each muon there are four columns: pt, the transverse momentum in GeV (the part of the momentum perpendicular to the beam); eta, the pseudorapidity, which encodes the angle to the beam; phi, the azimuthal angle around the beam in radians; and charge, either +1 or −1. mu1 is the muon with the larger transverse momentum.

gzip is one of the oldest compressors still in daily use, and Chapter 7 explains how it works. Reading a compressed file directly like this is the normal way to work. There is no reason to keep an uncompressed copy.

1.3 Transform

A muon’s momentum is large compared with its mass, so treating both muons as massless costs almost nothing. With that approximation, special relativity gives the invariant mass of the pair from the columns we have:

\[ M^2 = 2\,p_{T1}\,p_{T2}\left[\cosh(\eta_1 - \eta_2) - \cos(\phi_1 - \phi_2)\right] \]

mutate() adds it as a new column. The formula in the code looks like the formula on the page:

dimuon <- dimuon |>
  mutate(
    mass_gev = sqrt(
      2 * mu1_pt * mu2_pt * (cosh(mu1_eta - mu2_eta) - cos(mu1_phi - mu2_phi))
    )
  )

A neutral particle decays to one positive and one negative muon, so the pairs with matching charges cannot come from such a decay. They are background: two unrelated muons that happened to be recorded together. count() shows how many of each there are:

dimuon |>
  count(opposite_sign = mu1_charge != mu2_charge)
#> # A tibble: 2 × 2
#>   opposite_sign      n
#>   <lgl>          <int>
#> 1 FALSE           3594
#> 2 TRUE          115934

filter() keeps the opposite-sign pairs:

pairs <- dimuon |>
  filter(mu1_charge != mu2_charge)

1.4 Visualize

A histogram of the mass is the first thing any particle physicist would draw. The masses span nearly two orders of magnitude, so both axes go on a logarithmic scale:

ggplot(pairs, aes(x = mass_gev)) +
  geom_histogram(bins = 300) +
  scale_x_log10() +
  scale_y_log10()
A histogram on log-log axes of dimuon invariant mass from 2 to 150 GeV. The counts fall steadily with mass, with sharp peaks near 3.1, 3.7 and 9.5 to 10.4 GeV and a broad peak near 91 GeV.
Figure 1.1: The invariant mass of opposite-sign muon pairs, on logarithmic axes. Every peak is a particle.

Every peak is a particle that decays to two muons, sitting on a smooth continuum of pairs that come from no particle in particular. The tall spike near 3.1 GeV is the J/ψ, a bound state of a charm quark and its antiquark; the small one beside it is its excited state, the ψ(2S). The cluster near 10 GeV is the Υ family, bound states of a bottom quark and its antiquark. The broad peak near 91 GeV is the Z boson. The width of each peak tells you something too, either about the particle’s lifetime or about the detector’s resolution, and Chapter 17 measures it.

1.5 Store

The data deserve a better home than a CSV file. Parquet is an open file format that stores a table column by column, records each column’s type, and compresses each column separately (Chapter 13). arrow writes it in one line. This chapter writes its files into a folder called scratch:

dir.create("scratch", showWarnings = FALSE)

dimuon |>
  select(!mass_gev) |>
  write_parquet("scratch/dimuon.parquet")

The mass is left out on purpose: it is computed from the other columns, and storing only what was measured keeps the file honest. Here are the sizes of the two files:

tibble(
  file = c("data/dimuon.csv.gz", "scratch/dimuon.parquet"),
  megabytes = file.size(file) / 1e6
)
#> # A tibble: 2 × 2
#>   file                   megabytes
#>   <chr>                      <dbl>
#> 1 data/dimuon.csv.gz          2.53
#> 2 scratch/dimuon.parquet      3.02

The Parquet file is a little bigger than the gzipped CSV. That surprises most people, who expect a modern binary format to win easily. Part of the reason is the compressor: arrow’s default, Snappy, gives up some compression in exchange for speed (Chapter 10). Most of the reason is the numbers themselves. A momentum measured to a part in a thousand carries about ten bits of information however you store it, and no compressor can remove information; Chapter 4 explains why, and Chapter 13 shows how to store the same data in less space. What Parquet buys you here is everything else. It remembers that mu1_pt is a number, so nothing has to guess. It can read a single column without touching the others. And above all, it lets you scale.

1.6 Scale

Real experiments write data run by run, and a year of running is far too much to load at once. arrow’s write_dataset() splits a table into one Parquet file per group, here one per run:

dimuon |>
  select(!mass_gev) |>
  group_by(run) |>
  write_dataset("scratch/dimuon")

list.files("scratch/dimuon", recursive = TRUE)
#> [1] "run=2301/part-0.parquet" "run=2302/part-0.parquet"
#> [3] "run=2303/part-0.parquet" "run=2304/part-0.parquet"
#> [5] "run=2305/part-0.parquet" "run=2306/part-0.parquet"
#> [7] "run=2307/part-0.parquet" "run=2308/part-0.parquet"

open_dataset() points at the whole folder. It reads the file layout and the column types, but none of the data:

events <- open_dataset("scratch/dimuon")
events
#> FileSystemDataset with 8 Parquet files
#> 10 columns
#> event: double
#> mu1_pt: double
#> mu1_eta: double
#> mu1_phi: double
#> mu1_charge: double
#> mu2_pt: double
#> mu2_eta: double
#> mu2_phi: double
#> mu2_charge: double
#> run: int32

Now the same verbs as before run inside arrow, not inside R. This pipeline computes the mass, puts it into bins equally spaced in its logarithm, and counts the pairs in each bin. collect() at the end is the only step that brings anything into R’s memory, and what it brings is the finished histogram, a few hundred rows:

spectrum <- events |>
  filter(mu1_charge != mu2_charge) |>
  mutate(
    mass_gev = sqrt(
      2 * mu1_pt * mu2_pt * (cosh(mu1_eta - mu2_eta) - cos(mu1_phi - mu2_phi))
    ),
    log_bin = floor(log10(mass_gev) / 0.005)
  ) |>
  count(log_bin) |>
  arrange(log_bin) |>
  collect()

spectrum
#> # A tibble: 381 × 2
#>    log_bin     n
#>      <dbl> <int>
#>  1      55     2
#>  2      56     2
#>  3      57    13
#>  4      58    51
#>  5      59   203
#>  6      60   480
#>  7      61   698
#>  8      62   740
#>  9      63   739
#> 10      64   734
#> # ℹ 371 more rows

With 120,000 events this makes no practical difference. With 120 billion it is the difference between an analysis and a crash, and the code would not change at all. Chapter 14 and Chapter 15 show how far this goes.

1.7 Communicate

A figure for other people needs more care than one for yourself. Physicists draw histograms as steps, label their axes with units and name the peaks. Each bin is 0.005 in log10 of the mass, so the centre of bin k is at 100.005(k + ½) GeV:

spectrum <- spectrum |>
  mutate(mass_gev = 10^(0.005 * (log_bin + 0.5)))

peaks <- tribble(
  ~label,               ~mass_gev, ~n,    ~hjust,
  "J/ψ",                 3.10, 25000,  0.5,
  "ψ(2S)",               3.85,  1300,  0,
  "Υ(1S, 2S, 3S)",       9.90,  5200,  0.5,
  "Z",                       91.2,  1900,  0.5
)
ggplot(spectrum, aes(x = mass_gev, y = n)) +
  geom_step(direction = "mid", colour = "#1d3557", linewidth = 0.4) +
  geom_text(
    data = peaks,
    aes(label = label, hjust = hjust),
    size = 3.6,
    vjust = 0
  ) +
  scale_x_log10(breaks = c(2, 3, 5, 10, 20, 50, 100)) +
  scale_y_log10(
    breaks = 10^(0:4),
    labels = scales::label_number(big.mark = ","),
    expand = expansion(mult = c(0.02, 0.12))
  ) +
  labs(
    x = "Dimuon invariant mass (GeV)",
    y = "Opposite-sign pairs per bin",
    caption = "Bins are 0.005 wide in log10 of the mass."
  )
A step histogram of dimuon invariant mass on log-log axes, from 2 to 150 GeV. Labelled peaks: J/psi near 3.1 GeV, psi(2S) near 3.7 GeV, the three Upsilon states near 10 GeV and the Z boson near 91 GeV.
Figure 1.2: The dimuon mass spectrum, ready for a paper.

ggsave() writes the last figure to a file, here a PDF the width of a two-column journal page. The cairo_pdf device embeds the fonts and copes with the Greek letters:

ggsave(
  "scratch/dimuon-spectrum.pdf",
  width = 17.8, height = 10, units = "cm",
  device = cairo_pdf
)

That is the whole game: import a compressed file, compute a physical quantity, look at it, store it in a format that will last, scale the same code to data of any size, and draw a figure for others. Chapter 16 returns to making figures like this one, and Chapter 17 turns the peak near 10 GeV into a measurement.

1.8 Summary

In a few dozen lines of code you read a gzip-compressed file, computed an invariant mass with mutate(), removed background with filter(), drew a histogram, wrote the data to Parquet, split it into a dataset of one file per run, histogrammed it without loading it into memory, and made a figure fit for publication. You met the main verbs of the tidyverse, filter(), mutate(), count(), group_by() and arrange(), and the main functions of arrow: write_parquet(), write_dataset(), open_dataset() and collect().

Two things are worth carrying forward. First, every step was a description of a result, not a loop; Chapter 3 makes that contrast explicit. Second, the Parquet file was no smaller than the gzipped CSV, because the numbers themselves carry the information. Part II explains why, and what you can do about it.

1.9 Exercises

  1. Make the same spectrum for the same-sign pairs. Which peaks disappear, and why? Is anything left near 91 GeV?
  2. Change the bin width from 0.005 to 0.02 and then to 0.001 in log10 of the mass. What do you gain and lose each way? Which peaks are hardest to see with wide bins?
  3. Using the dataset in scratch/dimuon, find the number of opposite-sign pairs between 80 and 100 GeV in each run. Are the runs consistent with each other, given that each count has a Poisson uncertainty of about its square root?
  4. Read only the four mu1_ columns from scratch/dimuon.parquet with read_parquet(col_select = starts_with("mu1_")). How much smaller is the result in memory than the full table? (object.size() will tell you.)
  5. Write the data as a dataset partitioned by both run and mu1_charge. How many files do you get, and what do the folder names look like?