Tutorial for GenMultiDecay class

This tutorial shows how phasespace.fromdecay.GenMultiDecay can be used.

In order to use this functionality, you need to install the extra dependencies, for example through pip install phasespace[fromdecay].

This submodule makes it possible for phasespace and DecayLanguage to work together. More generally, GenMultiDecay can also be used as a high-level interface for simulating particles that can decay in multiple different ways.

# Import libraries
from pprint import pprint

import zfit
from particle import Particle
from decaylanguage import DecFileParser, DecayChainViewer, DecayChain, DecayMode
import tensorflow as tf

from phasespace.fromdecay import GenMultiDecay
/home/docs/checkouts/readthedocs.org/user_builds/phasespace/envs/1.9.0/lib/python3.8/site-packages/zfit/__init__.py:63: UserWarning: TensorFlow warnings are by default suppressed by zfit. In order to show them, set the environment variable ZFIT_DISABLE_TF_WARNINGS=0. In order to suppress the TensorFlow warnings AND this warning, set ZFIT_DISABLE_TF_WARNINGS=1.
  warnings.warn(
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[1], line 6
      4 import zfit
      5 from particle import Particle
----> 6 from decaylanguage import DecFileParser, DecayChainViewer, DecayChain, DecayMode
      7 import tensorflow as tf
      9 from phasespace.fromdecay import GenMultiDecay

File ~/checkouts/readthedocs.org/user_builds/phasespace/envs/1.9.0/lib/python3.8/site-packages/decaylanguage/__init__.py:12
      9 from ._version import version as __version__
     11 # Direct access to decay file parsing tools
---> 12 from .dec import DecFileParser
     14 # Direct access to decay chain representation classes and visualization tools
     15 from .decay import DaughtersDict, DecayChain, DecayChainViewer, DecayMode

File ~/checkouts/readthedocs.org/user_builds/phasespace/envs/1.9.0/lib/python3.8/site-packages/decaylanguage/dec/__init__.py:8
      1 # Copyright (c) 2018-2023, Eduardo Rodrigues and Henry Schreiner.
      2 #
      3 # Distributed under the 3-clause BSD license, see accompanying file LICENSE
      4 # or https://github.com/scikit-hep/decaylanguage for details.
      6 from __future__ import annotations
----> 8 from .dec import DecFileParser
      9 from .enums import known_decay_models
     11 __all__ = ("DecFileParser", "known_decay_models")

File ~/checkouts/readthedocs.org/user_builds/phasespace/envs/1.9.0/lib/python3.8/site-packages/decaylanguage/dec/dec.py:56
     53 from particle import Particle
     54 from particle.converters import PDG2EvtGenNameMap
---> 56 from .. import data
     57 from ..decay.decay import _expand_decay_modes
     58 from ..utils import charge_conjugate_name

File ~/checkouts/readthedocs.org/user_builds/phasespace/envs/1.9.0/lib/python3.8/site-packages/decaylanguage/data/__init__.py:21
     13 __all__ = ["basepath", "open_text"]
     16 basepath = resources.files(__name__)
     19 open_text = deprecated(
     20     version="0.12.0", reason="Use decaylanguage.data.basepath instead."
---> 21 )(resources.open_text)

AttributeError: module 'importlib_resources' has no attribute 'open_text'

Quick Intro to DecayLanguage

DecayLanguage can be used to parse and view .dec files. These files contain information about how a particle decays and with which probability. For more information about DecayLanguage and .dec files, see the DecayLanguage documentation.

We will begin by parsing a .dec file using DecayLanguage:

parser = DecFileParser('../tests/fromdecay/example_decays.dec')
parser.parse()

From the parser variable, one can access a certain decay for a particle using parser.build_decay_chains. This will be a dict that contains all information about how the mother particle, daughter particles etc. decay.

pi0_chain = parser.build_decay_chains("pi0")
pprint(pi0_chain)

This dict can also be displayed in a more human-readable way using DecayChainViewer:

DecayChainViewer(pi0_chain)

You can also create a decay using the DecayChain and DecayMode classes. However, a DecayChain can only contain one chain, i.e., a particle cannot decay in multiple ways.

dplus_decay = DecayMode(1, "K- pi+ pi+ pi0", model="PHSP")
pi0_decay = DecayMode(1, "gamma gamma")
dplus_single = DecayChain("D+", {"D+": dplus_decay, "pi0": pi0_decay})
DecayChainViewer(dplus_single.to_dict())

Creating a GenMultiDecay object

A regular phasespace.GenParticle instance would not be able to simulate this decay, since the \(\pi^0\) particle can decay in four different ways. However, a GenMultiDecay object can be created directly from a DecayLanguage dict:

pi0_decay = GenMultiDecay.from_dict(pi0_chain)

When creating a GenMultiDecay object, the DecayLanguage dict is “unpacked” into separate GenParticle instances, where each GenParticle instance corresponds to one way that the particle can decay.

These GenParticle instances and the probabilities of that decay mode can be accessed via GenMultiDecay.gen_particles. This is a list of tuples, where the first element in the tuple is the probability and the second element is the GenParticle.

for probability, particle in pi0_decay.gen_particles:
    print(f"There is a probability of {probability} "
          f"that pi0 decays into {', '.join(child.name for child in particle.children)}")

One can simulate this decay using the .generate method, which works the same as the GenParticle.generate method.

When calling the GenMultiDecay.generate method, it internally calls the generate method on the of the GenParticle instances in GenMultiDecay.gen_particles. The outputs are placed in a list, which is returned.

weights, events = pi0_decay.generate(n_events=10_000)
print("Number of events for each decay mode:", ", ".join(str(len(w)) for w in weights))

We can confirm that the counts above are close to the expected counts based on the probabilities.

Changing mass settings

Since DecayLanguage dicts do not contain any information about the mass of a particle, the fromdecay submodule uses the particle package to find the mass of a particle based on its name. The mass can either be a constant value or a function (besides the top particle, which is always a constant). These settings can be modified by passing in additional parameters to GenMultiDecay.from_dict. There are two optional parameters that can be passed to GenMultiDecay.from_dict: tolerance and mass_converter.

Constant vs variable mass

If a particle has a width less than tolerance, its mass is set to a constant value. This will be demonsttrated with the decay below:

dsplus_chain = parser.build_decay_chains("D*+", stable_particles=["D+"])
DecayChainViewer(dsplus_chain)
print(f"pi0 width = {Particle.from_evtgen_name('pi0').width}\n"
      f"D0 width = {Particle.from_evtgen_name('D0').width}")

\(\pi^0\) has a greater width than \(D^0\). If the tolerance is set to a value between their widths, the \(D^0\) particle will have a constant mass while \(\pi^0\) will not.

dstar_decay = GenMultiDecay.from_dict(dsplus_chain, tolerance=1e-8)
# Loop over D0 and pi+ particles, see graph above
for particle in dstar_decay.gen_particles[0][1].children:
    # If a particle width is less than tolerance or if it does not have any children, its mass will be fixed.
    assert particle.has_fixed_mass

# Loop over D+ and pi0. See above.
for particle in dstar_decay.gen_particles[1][1].children:
    if particle.name == "pi0":
        assert not particle.has_fixed_mass

Configuring mass functions

By default, the mass function used for variable mass is the relativistic Breit-Wigner distribution. This can however be changed. If you want the mother particle to have a specific mass function for a specific decay, you can add a zfit parameter to the DecayLanguage dict. Consider for example the previous \(D^{*+}\) example:

dsplus_custom_mass_func = dsplus_chain.copy()
dsplus_chain_subset = dsplus_custom_mass_func["D*+"][1]["fs"][1]
print("Before:")
pprint(dsplus_chain_subset)
# Set the mass function of pi0 to a gaussian distribution when it decays into two photons (gamma)
dsplus_chain_subset["pi0"][0]["zfit"] = "gauss"
print("After:")
pprint(dsplus_chain_subset)

Notice the added zfit field to the first decay mode of the \(\pi^0\) particle. This dict can then be passed to GenMultiDecay.from_dict, like before.

GenMultiDecay.from_dict(dsplus_custom_mass_func)

If you want all \(\pi^0\) particles to decay with the same mass function, you do not need to specify the zfit parameter for each decay in the dict. Instead, one can pass the particle_model_map parameter to the constructor:

GenMultiDecay.from_dict(dsplus_chain, particle_model_map={'pi0': 'gauss'})    # pi0 always decays with a gaussian mass distribution.

When using DecayChains, the syntax for specifying the mass function becomes cleaner:

dplus_decay = DecayMode(1, "K- pi+ pi+ pi0", model="PHSP")  # The model parameter will be ignored by GenMultiDecay
pi0_decay = DecayMode(1, "gamma gamma", zfit="gauss")   # Make pi0 have a gaussian mass distribution
dplus_single = DecayChain("D+", {"D+": dplus_decay, "pi0": pi0_decay})
GenMultiDecay.from_dict(dplus_single.to_dict())

Custom mass functions

The built-in supported mass function names are gauss, bw, and relbw, with gauss being the gaussian distribution, bw being the Breit-Wigner distribution, and relbw being the relativistic Breit-Wigner distribution.

If a non-supported value for the zfit parameter is not specified, it will automatically use the relativistic Breit-Wigner distribution. This behavior can be changed by changing the value of GenMultiDecay.DEFAULT_MASS_FUNC to a different string, e.g., "gauss". If an invalid value for the zfit parameter is used, a KeyError is raised.

It is also possible to add your own mass functions besides the built-in ones. You should then create a function that takes the mass and width of a particle and returns a mass function which with the format that is used for all phasespace mass functions. Below is an example of a custom gaussian distribution (implemented in the same way as the built-in gaussian distribution), which uses zfit PDFs:

def custom_gauss(mass, width):
    particle_mass = tf.cast(mass, tf.float64)
    particle_width = tf.cast(width, tf.float64)

    # This is the actual mass function that will be returned
    def mass_func(min_mass, max_mass, n_events):
        min_mass = tf.cast(min_mass, tf.float64)
        max_mass = tf.cast(max_mass, tf.float64)
        # Use a zfit PDF
        pdf = zfit.pdf.Gauss(mu=particle_mass, sigma=particle_width, obs="")
        iterator = tf.stack([min_mass, max_mass], axis=-1)
        return tf.vectorized_map(
            lambda lim: pdf.sample(1, limits=(lim[0], lim[1])), iterator
        )

    return mass_func

This function can then be passed to GenMultiDecay.from_dict as a dict, where the key specifies the zfit parameter name. In the example below, it is set to "custom_gauss". However, this name can be chosen arbitrarily and does not need to be the same as the function name.

dsplus_chain_subset = dsplus_custom_mass_func["D*+"][1]["fs"][1]
print("Before:")
pprint(dsplus_chain_subset)

# Set the mass function of pi0 to the custom gaussian distribution
#  when it decays into an electron-positron pair and a photon (gamma)
dsplus_chain_subset["pi0"][1]["zfit"] = "custom_gauss"
print("After:")
pprint(dsplus_chain_subset)
GenMultiDecay.from_dict(dsplus_custom_mass_func, {"custom_gauss": custom_gauss})