Phase space generators#

Amplitude analysis needs samples of four-momenta that are distributed uniformly over the phase space of a decay. TFPhaseSpaceGenerator produces such samples with phasespace. That package generates weighted events, so TFPhaseSpaceGenerator turns them into unweighted events with a hit-and-miss step: an event is kept if a uniform random number is below its weight. This page shows how the adaptive_max_weight option makes that step faster without changing the generated distribution.

Hide code cell content

import logging
import os

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from matplotlib_inline.backend_inline import set_matplotlib_formats

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
logging.getLogger("tensorwaves").setLevel(logging.ERROR)
tf.get_logger().setLevel(logging.ERROR)
set_matplotlib_formats("svg")

Hit-and-miss against an estimated maximum weight#

By default, the random numbers of the hit-and-miss step are drawn up to \(1\), the upper bound of the normalized weights that phasespace guarantees. The weights that actually occur are often far below that bound, especially for decays into many particles, so most events are rejected. With adaptive_max_weight=True, the random numbers are drawn up to an estimate of the maximum weight instead. The estimate is the largest weight seen so far plus a margin of 5%. If a later bunch contains a larger weight, the estimate is raised and the sample is generated anew, so that the result remains unbiased.

The option is keyword-only and is off by default, so existing code keeps producing the same events for the same seed.

The following plots illustrate this for a \(5\,\mathrm{GeV}\) particle that decays into an increasing number of pions. The left panel shows the weight distributions relative to the largest weight in each sample. The right panel shows the fraction of events that survive the hit-and-miss step: with the default setting, this is the mean weight, while with adaptive_max_weight=True it is the mean weight divided by the estimated maximum.

Hide code cell source

from tensorwaves.data import TFUniformRealNumberGenerator, TFWeightedPhaseSpaceGenerator

n_particles = list(range(3, 9))
weights = {}
for n in n_particles:
    weighted_generator = TFWeightedPhaseSpaceGenerator(
        initial_state_mass=5.0,
        final_state_masses=dict.fromkeys(range(n), 0.13957),
    )
    rng = TFUniformRealNumberGenerator(seed=0)
    weights[n] = weighted_generator.generate(100_000, rng)["weights"]

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 3.8), layout="constrained")
for n, w in weights.items():
    ax1.hist(w / w.max(), bins=60, histtype="step", density=True, label=f"{n} pions")
ax1.set_xlabel("Weight / maximum weight in sample")
ax1.set_yticks([])
ax1.legend()
ax2.plot(n_particles, [w.mean() for w in weights.values()], "o-", label="Default")
ax2.plot(
    n_particles,
    [w.mean() / (1.05 * w.max()) for w in weights.values()],
    "s-",
    label="adaptive_max_weight=True",
)
ax2.set_xlabel("Number of pions")
ax2.set_ylabel("Fraction of accepted events")
ax2.set_yscale("log")
ax2.legend()
plt.show()
../_images/fb4feda49d53d89777ee33b5e60be68824306fca8a29d0ef9166c13de5aa74aa.svg

The shape of the weight distribution relative to its maximum changes only moderately with more particles, but the mean weight relative to the bound of \(1\) drops by several orders of magnitude. With the estimated maximum, the fraction of accepted events stays above 10%. The gain in speed grows accordingly: for five or more pions, generation is orders of magnitude faster. TR-038 benchmarks this and confirms with statistical tests that both settings produce the same distributions.

Usage#

The option is a keyword argument of TFPhaseSpaceGenerator. The following example generates a sample of a three-body decay with both settings. The events differ, because the hit-and-miss step consumes the random numbers differently, but both samples are distributed uniformly over phase space: the events fill the kinematically allowed region of the Dalitz plot evenly.

from tensorwaves.data import TFPhaseSpaceGenerator, TFUniformRealNumberGenerator

initial_state_mass = 3.0969
final_state_masses = {0: 0.1350, 1: 0.1396, 2: 0.4937}
default_generator = TFPhaseSpaceGenerator(initial_state_mass, final_state_masses)
adaptive_generator = TFPhaseSpaceGenerator(
    initial_state_mass, final_state_masses, adaptive_max_weight=True
)
size = 500_000
default_generator.show_progress = False
adaptive_generator.show_progress = False
samples = {
    "Default": default_generator.generate(size, TFUniformRealNumberGenerator(seed=0)),
    "adaptive_max_weight=True": adaptive_generator.generate(
        size, TFUniformRealNumberGenerator(seed=0)
    ),
}

Hide code cell source

def invariant_mass_squared(*momenta: np.ndarray) -> np.ndarray:
    p = np.sum(momenta, axis=0)
    return p[:, 0] ** 2 - np.sum(p[:, 1:] ** 2, axis=1)


variables = {
    label: (
        invariant_mass_squared(sample["p0"], sample["p1"]),
        invariant_mass_squared(sample["p1"], sample["p2"]),
    )
    for label, sample in samples.items()
}

fig, axes = plt.subplots(1, 2, figsize=(10, 4.5), sharey=True, layout="constrained")
for ax, (label, (m12, m23)) in zip(axes, variables.items(), strict=True):
    ax.hist2d(m12, m23, bins=150, cmin=1, rasterized=True)
    ax.set_title(label)
    ax.set_xlabel(R"$m^2_{12}$ [GeV$^2$]")
axes[0].set_ylabel(R"$m^2_{23}$ [GeV$^2$]")
fig.colorbar(axes[0].collections[0], ax=axes, label="Events")
plt.show()
../_images/f5ad7ba963779359594315fca1b19de57e0afc4341843da35e2a404c5fa9ad84.svg

When to use the option#

The option pays off for decays into five or more particles, where the default setting rejects most events. Keep the default when samples have to be identical to those of earlier versions for the same seed, for instance when tests compare against stored values. A small bunch_size makes the estimate of the maximum weight less accurate and leads to more restarts, so the option works best with the default bunch size.