Generating decays#

This page shows the basic workflow: create a Generator, generate decay trees, and turn them into four-momentum arrays.

Hide code cell content

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

set_matplotlib_formats("svg")

Creating a generator#

The default Generator uses the decay table (DECAY_FILE) and particle table (PARTICLE_TABLE) that ship with the package. A seed makes the generated events reproducible. Creating a Generator reads the decay and particle tables and initializes Pythia8, which prints a lot of log output. That output is hidden on this page.

from pyevtgen import Generator

generator = Generator(seed=42)

EvtGen keeps its tables and random engine in global state. A process can therefore hold only one Generator, and creating a second one raises an error:

try:
    Generator()
except RuntimeError as error:
    print(error)
EvtGen has global state and can only be initialized once per process. Reuse the existing EvtGen instance.
EvtMTRandomEngine:Mersenne-Twister random number generator with seed = 1476487407
EvtGen:Defining EvtPythiaEngine: data tables defined in /home/runner/work/pyevtgen-test/pyevtgen-test/.venv/lib/python3.14/site-packages/pyevtgen/data/pythia8/xmldoc
EvtGen:Pythia 8 codes need to be used in decay files
EvtGen:Using EvtGen random engine for Pythia 8 as well
EvtGen:Creating generic Pythia generator

 *------------------------------------------------------------------------------------* 
 |                                                                                    | 
 |  *------------------------------------------------------------------------------*  | 
 |  |                                                                              |  | 
 |  |                                                                              |  | 
 |  |   PPP   Y   Y  TTTTT  H   H  III    A      Welcome to the Lund Monte Carlo!  |  | 
 |  |   P  P   Y Y     T    H   H   I    A A     This is PYTHIA version 8.318      |  | 
 |  |   PPP     Y      T    HHHHH   I   AAAAA    Last date of change: 16 Sep 2026  |  | 
 |  |   P       Y      T    H   H   I   A   A                                      |  | 
 |  |   P       Y      T    H   H  III  A   A    Now is 09 Nov 2026 at 10:48:26    |  | 
 |  |                                                                              |  | 
 |  |   Program documentation and an archive of historic versions is found on:     |  | 
 |  |                                                                              |  | 
 |  |                               https://pythia.org/                            |  | 
 |  |                                                                              |  | 
 |  |   PYTHIA is authored by a collaboration consisting of:                       |  | 
 |  |                                                                              |  | 
 |  |   Javira Altmann, Christian Bierlich, Naomi Cooke, Nishita Desai,            |  | 
 |  |   Ilkka Helenius, Philip Ilten, Joni Laulainen, Leif Lonnblad,               |  | 
 |  |   Stephen Mrenna, Christian Preuss, Torbjorn Sjostrand, and Peter Skands.    |  | 
 |  |                                                                              |  | 
 |  |   The complete list of authors, including contact information and            |  | 
 |  |   affiliations, can be found on https://pythia.org/.                         |  | 
 |  |   Problems or bugs should be reported on email at authors@pythia.org.        |  | 
 |  |                                                                              |  | 
 |  |   The main program reference is C. Bierlich et al,                           |  | 
 |  |   'A comprehensive guide to the physics and usage of Pythia 8.3',            |  | 
 |  |   SciPost Phys. Codebases 8-r8.3 (2022) [arXiv:2203.11601 [hep-ph]]          |  | 
 |  |                                                                              |  | 
 |  |   PYTHIA is released under the GNU General Public Licence version 2          |  | 
 |  |   or later. Please respect the MCnet Guidelines for Generator Authors        |  | 
 |  |   and Users.                                                                 |  | 
 |  |                                                                              |  | 
 |  |   Disclaimer: this program comes without any guarantees.                     |  | 
 |  |   Beware of errors and use common sense when interpreting results.           |  | 
 |  |                                                                              |  | 
 |  |   Copyright (C) 2026 Torbjorn Sjostrand                                      |  | 
 |  |                                                                              |  | 
 |  |                                                                              |  | 
 |  *------------------------------------------------------------------------------*  | 
 |                                                                                    | 
 *------------------------------------------------------------------------------------* 

EvtGen:Creating alias Pythia generator

The package records which versions of EvtGen, HepMC3 and Pythia8 it was built with, and where its data files are:

EvtGen  R03-01-00
HepMC3  3.3.1
Pythia8 8318
DECAY.DEC evt.pdl

Decay trees#

Generator.decay() decays a particle, given by its EvtGen name or PDG ID, and returns the root Particle of the decay tree. Each Particle holds its name, PDG ID, four-momentum \((E, p_x, p_y, p_z)\) in GeV, and its daughters.

Hide code cell content

def print_tree(particle, indent: int = 0) -> None:
    energy = particle.p4[0]
    print(f"{' ' * indent}{particle.name:<10} E = {energy:.3f} GeV")
    for daughter in particle.daughters:
        print_tree(daughter, indent + 2)
event = generator.decay("D*+")
print_tree(event)
D*+        E = 2.010 GeV
  D+         E = 1.870 GeV
    K_S0       E = 0.755 GeV
      pi+        E = 0.250 GeV
      pi-        E = 0.505 GeV
    pi+        E = 0.555 GeV
    pi+        E = 0.203 GeV
    pi-        E = 0.357 GeV
  pi0        E = 0.140 GeV
    gamma      E = 0.067 GeV
    gamma      E = 0.073 GeV

The stable particles at the leaves of the tree are returned by Particle.final_state(). Their four-momenta add up to that of the parent:

final_state = event.final_state()
[particle.name for particle in final_state]
['pi+', 'pi-', 'pi+', 'pi+', 'pi-', 'gamma', 'gamma']
np.sum([particle.p4 for particle in final_state], axis=0)
array([2.01026000e+00, 9.02056208e-17, 4.51028104e-17, 1.80411242e-16])

Event samples#

Generator.generate() produces many decays at once. When all events have the same final state, final_state_momenta() stacks them into a NumPy array of shape (n_events, n_final_state, 4). Here, the \(D^0\) decays according to the full decay table, so we first select one decay channel:

events = generator.generate("D0", n=20_000)
channel = ["K-", "pi+"]
selected = [e for e in events if [p.name for p in e.final_state()] == channel]
len(selected)
811
from pyevtgen import final_state_momenta

momenta = final_state_momenta(selected)
momenta.shape
(811, 2, 4)

In this two-body decay at rest, both daughters have a fixed momentum, while their directions are distributed uniformly over all directions:

np.linalg.norm(momenta[:, :, 1:], axis=2).std(axis=0)
array([1.87667091e-15, 1.87667091e-15])

Hide code cell content

p_kaon = momenta[:, 0, 1:]
cos_theta = p_kaon[:, 2] / np.linalg.norm(p_kaon, axis=1)
phi = np.arctan2(p_kaon[:, 1], p_kaon[:, 0])

fig, axes = plt.subplots(ncols=2, figsize=(8, 3))
axes[0].hist(cos_theta, bins=50)
axes[0].set_xlabel(r"$\cos\theta_{K^-}$")
axes[1].hist(phi, bins=50)
axes[1].set_xlabel(r"$\phi_{K^-}$")
fig.tight_layout()
plt.show()
../_images/4c2998a3e143e1cd1e9340159bc5aeb1bbd7381b96199041e5e49f7b7849c3bc.svg

Without selecting a channel, the sample contains all \(D^0\) decays from the decay table. The final-state multiplicity and the momentum spectra of the most common particles illustrate this:

Hide code cell content

from collections import Counter

multiplicities = [len(event.final_state()) for event in events]
spectra = {name: [] for name in ["pi+", "pi-", "K-", "gamma"]}
for event in events:
    for particle in event.final_state():
        if particle.name in spectra:
            spectra[particle.name].append(np.linalg.norm(particle.p4[1:]))

fig, axes = plt.subplots(ncols=2, figsize=(9, 3.2))
counts = Counter(multiplicities)
axes[0].bar(list(counts), list(counts.values()))
axes[0].set_xlabel("final-state multiplicity")
axes[0].set_ylabel("events")
for name, momenta in spectra.items():
    axes[1].hist(momenta, bins=60, range=(0, 1), histtype="step", label=name)
axes[1].set_xlabel("$|p|$ [GeV]")
axes[1].set_yscale("log")
axes[1].legend()
fig.tight_layout()
plt.show()
../_images/18f994c5202803a397c99f5158b4ebc7a3deb3cf712f81860f3bf7d231065e84.svg

Moving parents#

By default, the parent decays at rest. Pass its four-momentum to generate decays in flight, for instance a \(D^0\) with an energy of 10 GeV along the \(z\) axis:

mass = generator.properties("D0").mass
energy = 10.0
p4 = [energy, 0.0, 0.0, np.sqrt(energy**2 - mass**2)]
event = generator.decay("D0", p4=p4)
np.sum([particle.p4 for particle in event.final_state()], axis=0)
array([ 1.00000000e+01,  0.00000000e+00, -6.93889390e-18,  9.82458188e+00])

Reproducibility#

The seed property reseeds the random engine, so the same seed gives the same events:

generator.seed = 7
first = generator.decay("D0").final_state()[0].p4
generator.seed = 7
second = generator.decay("D0").final_state()[0].p4
first == second
True