EvtGen API#

Besides the convenience class Generator, pyevtgen exposes the classes of the EvtGen C++ library with the same names and methods, such as EvtGen, EvtParticle, and EvtPDL. Code and documentation written for EvtGen in C++ therefore carry over directly. This page shows the C++ workflow in Python and the features that go beyond Generator: polarized decays, the decay table, and changing particle properties.

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")

Setting up EvtGen#

In C++, EvtGen is typically set up with a random engine and the external generators, as in EvtGen’s examples:

EvtRandomEngine* engine = new EvtMTRandomEngine(42);
EvtExternalGenList genList(false, pythiaXmlDir, "gamma", true);
std::list<EvtDecayBase*> models = genList.getListOfModels();
EvtGen evtgen("DECAY.DEC", "evt.pdl", engine, nullptr, &models, 1);

The same in Python, with the decay and particle tables that ship with pyevtgen. Creating a EvtGen 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 (
    DECAY_FILE,
    PARTICLE_TABLE,
    PYTHIA8_XML_DIR,
    EvtExternalGenList,
    EvtGen,
    EvtMTRandomEngine,
)

engine = EvtMTRandomEngine(42)
gen_list = EvtExternalGenList(
    convertPythiaCodes=False,
    pythiaXmlDir=str(PYTHIA8_XML_DIR),
    photonType="gamma",
    useEvtGenRandom=True,
)
models = gen_list.getListOfModels()
evtgen = EvtGen([str(DECAY_FILE)], str(PARTICLE_TABLE), engine, None, models, 1)

Generator does exactly this, and exposes the result as Generator.evtgen, so the two styles can be combined.

Generating a decay#

As in C++, EvtParticleFactory.particleFactory() creates a particle, EvtGen.generateDecay() decays it, and EvtParticle.deleteTree() releases the tree:

EvtId id = EvtPDL::getId("D*+");
EvtVector4R p4(EvtPDL::getMeanMass(id), 0.0, 0.0, 0.0);
EvtParticle* parent = EvtParticleFactory::particleFactory(id, p4);
parent->setDiagonalSpinDensity();
evtgen.generateDecay(parent);
parent->printTree();
parent->deleteTree();
from pyevtgen import EvtParticleFactory, EvtPDL, EvtVector4R

evt_id = EvtPDL.getId("D*+")
p4 = EvtVector4R(EvtPDL.getMeanMass(evt_id), 0.0, 0.0, 0.0)
parent = EvtParticleFactory.particleFactory(evt_id, p4)
parent.setDiagonalSpinDensity()
evtgen.generateDecay(parent)
print(parent.treeStr())
D*+ -> D+ (K_S0 (pi+ pi-) pi+ pi+ pi-) pi0 (gamma gamma) 

The tree is navigated with getNDaug() and getDaug(). Four-momenta are EvtVector4R objects, which also behave as sequences of \((E, p_x, p_y, p_z)\):

def print_daughters(particle, indent: int = 0) -> None:
    for i in range(particle.getNDaug()):
        daughter = particle.getDaug(i)
        p4 = daughter.getP4Lab()
        print(f"{' ' * indent}{daughter.getName():<6} m = {p4.mass():.4f} GeV")
        print_daughters(daughter, indent + 2)


print_daughters(parent)
parent.deleteTree()
D+     m = 1.8697 GeV
  K_S0   m = 0.4976 GeV
    pi+    m = 0.1396 GeV
    pi-    m = 0.1396 GeV
  pi+    m = 0.1396 GeV
  pi+    m = 0.1396 GeV
  pi-    m = 0.1396 GeV
pi0    m = 0.1350 GeV
  gamma  m = 0.0000 GeV
  gamma  m = 0.0000 GeV

Warning

As in C++, Python does not own the particles of a tree. Release every tree with deleteTree(), and do not use its particles afterwards, because that crashes the program. Generator copies the trees into Particle objects, which avoids this.

Decay tables#

EvtDecayTable gives access to the decay channels that EvtGen read from the decay files, including their branching fractions and decay models. The channels of a particle are looked up with its alias index:

from pyevtgen import EvtDecayTable

table = EvtDecayTable.getInstance()
d0 = EvtPDL.getId("D0")
channels = []
for imode in range(table.getNMode(d0.getAlias())):
    decay = table.getDecay(d0.getAlias(), imode)
    daughters = [EvtPDL.name(decay.getDaug(i)) for i in range(decay.getNDaug())]
    channels.append((
        decay.getBranchingFraction(),
        " ".join(daughters),
        decay.getModelName(),
    ))
channels.sort(reverse=True)
print(
    f"{len(channels)} channels, sum of branching fractions: {sum(c[0] for c in channels):.3f}"
)
for fraction, daughters, model in channels[:5]:
    print(f"{fraction:6.3f}  {daughters:<20} {model}")
137 channels, sum of branching fractions: 1.000
 0.139  K- pi+ pi0           D_DALITZ
 0.078  a_1+ K-              SVS
 0.068  K*- rho+             SVV_HELAMP
 0.054  K_S0 pi+ pi- pi0     PHSP
 0.040  anti-K0 pi0 pi0 pi0  PHSP

Hide code cell content

fractions, labels, _ = zip(*channels[:15], strict=True)
fig, ax = plt.subplots(figsize=(6, 4.5))
ax.barh(range(len(labels)), fractions)
ax.set_yticks(range(len(labels)), labels, fontsize=8)
ax.invert_yaxis()
ax.set_xlabel("branching fraction")
ax.set_title("Most frequent $D^0$ decays in the decay table")
fig.tight_layout()
plt.show()
../_images/34861aa1d65c62b7662dcd4b6f49f4051f39fc1515962d5f69becde9723b4eca.svg

Polarized decays#

Generator decays unpolarized particles, with setDiagonalSpinDensity(). With a EvtSpinDensity matrix, a particle can be prepared in any spin state instead. Here, a \(J/\psi\) at rest decays to \(\mu^+\mu^-\) in each of its three helicity states along the \(z\) axis. Helicity \(\pm1\) gives an angular distribution of \(1+\cos^2\theta\) for the muons, helicity 0 gives \(\sin^2\theta\).

from pathlib import Path
from tempfile import mkdtemp

from pyevtgen import EvtSpinDensity

decay_file = Path(mkdtemp()) / "jpsi.dec"
decay_file.write_text("""
Decay J/psi
1.0 mu+ mu- VLL;
Enddecay
End
""")
evtgen.readUDecay(str(decay_file))
jpsi = EvtPDL.getId("J/psi")
p4 = EvtVector4R(EvtPDL.getMeanMass(jpsi), 0.0, 0.0, 0.0)
cos_theta = {}
for state in range(3):
    rho = EvtSpinDensity()
    rho.setDim(3)
    rho.set(state, state, 1.0)
    values = []
    for _ in range(20_000):
        parent = EvtParticleFactory.particleFactory(jpsi, p4)
        parent.setSpinDensityForwardHelicityBasis(rho)
        evtgen.generateDecay(parent)
        muon = parent.getDaug(0).getP4Lab()
        values.append(muon.get(3) / muon.d3mag())
        parent.deleteTree()
    cos_theta[state] = np.array(values)

Hide code cell content

fig, ax = plt.subplots(figsize=(6, 3.5))
x = np.linspace(-1, 1, num=100)
for state, label in [(0, "helicity +1"), (1, "helicity 0"), (2, "helicity -1")]:
    ax.hist(
        cos_theta[state],
        bins=40,
        range=(-1, 1),
        density=True,
        histtype="step",
        label=label,
    )
ax.plot(
    x,
    3 / 8 * (1 + x**2),
    color="gray",
    linestyle="dotted",
    label=r"$\frac{3}{8}(1+\cos^2\theta)$",
)
ax.plot(
    x,
    3 / 4 * (1 - x**2),
    color="black",
    linestyle="dotted",
    label=r"$\frac{3}{4}\sin^2\theta$",
)
ax.set_xlabel(r"$\cos\theta(\mu^+)$")
ax.legend(fontsize=8)
plt.show()
../_images/7f8edf0c8c8877601e3c13591cb0c2e0300b732f6771a719ac4ca96d7632eb2b.svg

Changing particle properties#

EvtPDL reads and changes the particle table at runtime, for instance with reSetMass(). Here, the \(\rho^+\) in \(D^0 \to \rho^+K^-\) is shifted to a higher mass, which moves the peak in the \(\pi^+\pi^0\) invariant mass:

decay_file = Path(mkdtemp()) / "krho.dec"
decay_file.write_text("""
Decay D0
1.0 rho+ K- SVS;
Enddecay
Decay rho+
1.0 pi+ pi0 VSS;
Enddecay
End
""")
evtgen.readUDecay(str(decay_file))
def generate_pipi_mass(n: int) -> np.ndarray:
    p4 = EvtVector4R(EvtPDL.getMeanMass(d0), 0.0, 0.0, 0.0)
    masses = []
    for _ in range(n):
        parent = EvtParticleFactory.particleFactory(d0, p4)
        parent.setDiagonalSpinDensity()
        evtgen.generateDecay(parent)
        masses.append(parent.getDaug(0).getP4Lab().mass())
        parent.deleteTree()
    return np.array(masses)


rho_plus = EvtPDL.getId("rho+")
nominal = generate_pipi_mass(20_000)
EvtPDL.reSetMass(rho_plus, 0.9)
shifted = generate_pipi_mass(20_000)
print(f"rho+ mass is now {EvtPDL.getMeanMass(rho_plus)} GeV")
rho+ mass is now 0.9 GeV

Hide code cell content

fig, ax = plt.subplots(figsize=(6, 3.5))
ax.hist(
    nominal, bins=80, range=(0.3, 1.4), histtype="step", label=r"nominal $\rho^+$ mass"
)
ax.hist(
    shifted,
    bins=80,
    range=(0.3, 1.4),
    histtype="step",
    label=r"$\rho^+$ mass set to 0.9 GeV",
)
ax.set_xlabel(r"$m(\pi^+\pi^0)$ [GeV]")
ax.legend(fontsize=8)
plt.show()
../_images/978d0337a604252aa60f243fc6bea1657f5cc303b5fcadb3f5e2cd6620199bf9.svg

Four-vectors#

EvtVector4R supports the same operations as in C++. The product of two four-vectors is the Minkowski scalar product, and boostTo() boosts a four-vector into the frame of another one:

from pyevtgen import boostTo

pion = EvtVector4R(0.14, 0.0, 0.0, 0.0)
frame = EvtVector4R(10.0, 0.0, 0.0, 9.8)
print("p.p      =", frame * frame)
print("mass     =", frame.mass())
print("boosted  =", boostTo(pion, frame))
p.p      = 3.9599999999999795
mass     = 1.9899748742132348
boosted  = EvtVector4R(0.703526, 0, 0, 0.689456)

The complete list of classes and methods is on the API page. Classes and methods follow the EvtGen documentation, apart from adaptations to Python: EvtGenKine.PhaseSpace() returns the four-momenta instead of writing them into an array argument, and complex numbers are Python complex values.