phasespace 1.10.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- phasespace/__init__.py +33 -0
- phasespace/_version.py +24 -0
- phasespace/backend.py +23 -0
- phasespace/fromdecay/__init__.py +28 -0
- phasespace/fromdecay/genmultidecay.py +340 -0
- phasespace/fromdecay/mass_functions.py +109 -0
- phasespace/kinematics.py +188 -0
- phasespace/phasespace.py +841 -0
- phasespace/random.py +40 -0
- phasespace-1.10.4.dist-info/METADATA +342 -0
- phasespace-1.10.4.dist-info/RECORD +14 -0
- phasespace-1.10.4.dist-info/WHEEL +4 -0
- phasespace-1.10.4.dist-info/licenses/AUTHORS.rst +20 -0
- phasespace-1.10.4.dist-info/licenses/LICENSE +24 -0
phasespace/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Top-level package for TensorFlow PhaseSpace."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("phasespace")
|
|
7
|
+
except PackageNotFoundError:
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
__author__ = """Albert Puig Navarro"""
|
|
11
|
+
__email__ = "apuignav@gmail.com"
|
|
12
|
+
__maintainer__ = "zfit"
|
|
13
|
+
|
|
14
|
+
__credits__ = ["Jonas Eschle <Jonas.Eschle@cern.ch>"]
|
|
15
|
+
|
|
16
|
+
__all__ = ["nbody_decay", "GenParticle", "random", "to_vectors", "numpy"]
|
|
17
|
+
|
|
18
|
+
import tensorflow.experimental.numpy as numpy
|
|
19
|
+
|
|
20
|
+
from . import random
|
|
21
|
+
from .phasespace import GenParticle, nbody_decay, to_vectors
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _set_eager_mode():
|
|
25
|
+
import os
|
|
26
|
+
|
|
27
|
+
import tensorflow as tf
|
|
28
|
+
|
|
29
|
+
is_eager = bool(os.environ.get("PHASESPACE_EAGER"))
|
|
30
|
+
tf.config.run_functions_eagerly(is_eager)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
_set_eager_mode()
|
phasespace/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '1.10.4'
|
|
22
|
+
__version_tuple__ = version_tuple = (1, 10, 4)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
phasespace/backend.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""TensorFlow backend function decorators for phasespace.
|
|
2
|
+
|
|
3
|
+
This module provides standardized TensorFlow function decorators for different compilation and optimization
|
|
4
|
+
strategies used throughout the phasespace package.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import tensorflow as tf
|
|
8
|
+
|
|
9
|
+
#: Whether to enable shape relaxation for JIT-compiled functions
|
|
10
|
+
RELAX_SHAPES = True
|
|
11
|
+
|
|
12
|
+
#: Standard TensorFlow function wrapper without JIT compilation
|
|
13
|
+
function = tf.function(autograph=False, jit_compile=False)
|
|
14
|
+
|
|
15
|
+
#: JIT-compiled TensorFlow function with shape relaxation enabled
|
|
16
|
+
function_jit = tf.function(
|
|
17
|
+
autograph=False, reduce_retracing=RELAX_SHAPES, jit_compile=True
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
#: JIT-compiled TensorFlow function without shape relaxation
|
|
21
|
+
function_jit_fixedshape = tf.function(
|
|
22
|
+
autograph=False, reduce_retracing=False, jit_compile=True
|
|
23
|
+
)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""This submodule makes it possible for `phasespace` and `DecayLanguage` to work together.
|
|
2
|
+
|
|
3
|
+
More generally, the `GenMultiDecay` object can also be used as a high-level interface for simulating particles
|
|
4
|
+
that can decay in multiple different ways.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from .genmultidecay import GenMultiDecay # noqa: F401
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
import zfit # noqa: F401
|
|
15
|
+
import zfit_physics as zphys # noqa: F401
|
|
16
|
+
from particle import Particle # noqa: F401
|
|
17
|
+
except ModuleNotFoundError as error:
|
|
18
|
+
raise ModuleNotFoundError(
|
|
19
|
+
"The fromdecay functionality in phasespace requires particle and zfit-physics. "
|
|
20
|
+
"Either install phasespace[fromdecay] or particle and zfit-physics.",
|
|
21
|
+
file=sys.stderr,
|
|
22
|
+
) from error
|
|
23
|
+
|
|
24
|
+
__all__ = ("GenMultiDecay",)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def __dir__() -> tuple[str, ...]:
|
|
28
|
+
return __all__
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
|
|
6
|
+
import tensorflow as tf
|
|
7
|
+
import tensorflow.experimental.numpy as tnp
|
|
8
|
+
from particle import Particle
|
|
9
|
+
from phasespace import GenParticle
|
|
10
|
+
|
|
11
|
+
from .mass_functions import DEFAULT_CONVERTER
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class GenMultiDecay:
|
|
15
|
+
MASS_WIDTH_TOLERANCE = 0.01
|
|
16
|
+
DEFAULT_MASS_FUNC = "relbw"
|
|
17
|
+
|
|
18
|
+
def __init__(self, gen_particles: list[tuple[float, GenParticle]]):
|
|
19
|
+
"""A ``GenParticle``-type container that can handle multiple decays.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
gen_particles: All the GenParticles and their corresponding probabilities.
|
|
23
|
+
The list must be of the format [[probability, GenParticle instance], [probability, ...
|
|
24
|
+
"""
|
|
25
|
+
self.gen_particles = gen_particles
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def from_dict(
|
|
29
|
+
cls,
|
|
30
|
+
dec_dict: dict,
|
|
31
|
+
mass_converter: dict[str, Callable] = None,
|
|
32
|
+
tolerance: float = None,
|
|
33
|
+
particle_model_map: dict[str, str] = None,
|
|
34
|
+
):
|
|
35
|
+
"""Create a ``GenMultiDecay`` instance from a dict in the ``DecayLanguage`` package format.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
dec_dict: The input dict from which the GenMultiDecay object will be created from.
|
|
39
|
+
A dec_dict has the same structure as the dicts used in DecayLanguage, see the examples below.
|
|
40
|
+
mass_converter: A dict with mass function names and their corresponding mass functions.
|
|
41
|
+
These functions should take the particle mass and the mass width as inputs
|
|
42
|
+
and return a mass function that phasespace can understand.
|
|
43
|
+
This dict will be combined with the predefined mass functions in this package.
|
|
44
|
+
See the Example below or the tutorial for how to use this parameter.
|
|
45
|
+
tolerance: Minimum mass width of the particle to use a mass function instead of
|
|
46
|
+
assuming the mass to be constant. If None, the default value, defined by the class variable
|
|
47
|
+
``MASS_WIDTH_TOLERANCE``, will be used. This value can be customized if desired.
|
|
48
|
+
particle_model_map: A dict where the key is a particle name and the value is a mass function name.
|
|
49
|
+
If a particle is specified in the particle_model_map, then all appearances of this particle
|
|
50
|
+
in dec_dict will get the same mass function. This way, one doesn't have to manually add the
|
|
51
|
+
zfit parameter to every place where this particle appears in dec_dict. If the zfit parameter
|
|
52
|
+
is specified for a particle which is also included in particle_model_map, the zfit parameter
|
|
53
|
+
mass function name will be prioritized.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
The created GenMultiDecay object.
|
|
57
|
+
|
|
58
|
+
Examples:
|
|
59
|
+
**Basic Usage**
|
|
60
|
+
|
|
61
|
+
DecayLanguage is usually used to create a dict that can be understood by GenMultiDecay:
|
|
62
|
+
|
|
63
|
+
.. code-block:: python
|
|
64
|
+
|
|
65
|
+
from decaylanguage import DecFileParser
|
|
66
|
+
from phasespace.fromdecay import GenMultiDecay
|
|
67
|
+
|
|
68
|
+
# Parse a .dec file to create a DecayLanguage dict describing a D*+ particle
|
|
69
|
+
# that can decay in 2 different ways: D*+ -> D0(->K- pi+) pi+ or D*+ -> D+ gamma
|
|
70
|
+
parser = DecFileParser('example_decays.dec')
|
|
71
|
+
parser.parse()
|
|
72
|
+
dst_chain = parser.build_decay_chains("D*+")
|
|
73
|
+
# dst_chain will be:
|
|
74
|
+
# {'D*+': [{'bf': 0.984,
|
|
75
|
+
# 'fs': [{'D0': [{'bf': 1.0,
|
|
76
|
+
# 'fs': ['K-', 'pi+']}]},
|
|
77
|
+
# 'pi+']},
|
|
78
|
+
# {'bf': 0.016,
|
|
79
|
+
# 'fs': ['D+', 'gamma']}]}
|
|
80
|
+
|
|
81
|
+
**Using particle_model_map**
|
|
82
|
+
|
|
83
|
+
If the D0 particle should have a mass distribution of a gaussian when it decays, one can pass
|
|
84
|
+
the ``particle_model_map`` parameter to ``from_dict``:
|
|
85
|
+
|
|
86
|
+
.. code-block:: python
|
|
87
|
+
|
|
88
|
+
dst_gen = GenMultiDecay.from_dict(dst_chain, particle_model_map={"D0": "gauss"})
|
|
89
|
+
|
|
90
|
+
This will then set the mass function of D0 to a gaussian for all its decays.
|
|
91
|
+
|
|
92
|
+
**Using the zfit parameter**
|
|
93
|
+
|
|
94
|
+
If more custom control is required, e.g., if D0 can decay in multiple ways and one of the decays
|
|
95
|
+
should have a specific mass function, a ``zfit`` parameter can be added to its decay dict:
|
|
96
|
+
|
|
97
|
+
.. code-block:: python
|
|
98
|
+
|
|
99
|
+
dst_chain["D*+"][0]["fs"][0]["D0"][0]["zfit"] = "gauss"
|
|
100
|
+
dst_gen = GenMultiDecay.from_dict(dst_chain)
|
|
101
|
+
|
|
102
|
+
This will now make the D0 particle have a gaussian mass function, only when it decays into
|
|
103
|
+
K- and pi+. In this case, there are no other ways that D0 can decay, so using
|
|
104
|
+
``particle_model_map`` is a cleaner and easier option.
|
|
105
|
+
|
|
106
|
+
**Custom Mass Functions**
|
|
107
|
+
|
|
108
|
+
If the decay of the D0 particle should be modelled by a mass distribution that does not
|
|
109
|
+
come with the package, a custom distribution can be created:
|
|
110
|
+
|
|
111
|
+
.. code-block:: python
|
|
112
|
+
|
|
113
|
+
def custom_gauss(mass, width):
|
|
114
|
+
particle_mass = tf.cast(mass, tf.float64)
|
|
115
|
+
particle_width = tf.cast(width, tf.float64)
|
|
116
|
+
def mass_func(min_mass, max_mass, n_events):
|
|
117
|
+
min_mass = tf.cast(min_mass, tf.float64)
|
|
118
|
+
max_mass = tf.cast(max_mass, tf.float64)
|
|
119
|
+
# Use a zfit PDF
|
|
120
|
+
pdf = zfit.pdf.Gauss(mu=particle_mass, sigma=particle_width, obs="")
|
|
121
|
+
iterator = tf.stack([min_mass, max_mass], axis=-1)
|
|
122
|
+
return tf.vectorized_map(
|
|
123
|
+
lambda lim: pdf.sample(1, limits=(lim[0], lim[1])), iterator
|
|
124
|
+
)
|
|
125
|
+
return mass_func
|
|
126
|
+
|
|
127
|
+
# Change the distribution in the dst_chain dict
|
|
128
|
+
dst_chain["D*+"][0]["fs"][0]["D0"][0]["zfit"] = "custom_gauss"
|
|
129
|
+
|
|
130
|
+
# Pass the custom_gauss function to from_dict
|
|
131
|
+
dst_gen = GenMultiDecay.from_dict(dst_chain, mass_converter={"custom_gauss": custom_gauss})
|
|
132
|
+
|
|
133
|
+
Notes:
|
|
134
|
+
For a more in-depth tutorial, see the tutorial on GenMultiDecay in the
|
|
135
|
+
`documentation <https://phasespace.readthedocs.io/en/stable/GenMultiDecay_Tutorial.html>`__.
|
|
136
|
+
"""
|
|
137
|
+
if tolerance is None:
|
|
138
|
+
tolerance = cls.MASS_WIDTH_TOLERANCE
|
|
139
|
+
if particle_model_map is None:
|
|
140
|
+
particle_model_map = {}
|
|
141
|
+
if mass_converter is None:
|
|
142
|
+
total_mass_converter = DEFAULT_CONVERTER
|
|
143
|
+
else:
|
|
144
|
+
# Combine the default mass functions specified with the mass functions from input.
|
|
145
|
+
total_mass_converter = {**DEFAULT_CONVERTER, **mass_converter}
|
|
146
|
+
|
|
147
|
+
gen_particles = _recursively_traverse(
|
|
148
|
+
dec_dict,
|
|
149
|
+
total_mass_converter,
|
|
150
|
+
particle_model_map=particle_model_map,
|
|
151
|
+
tolerance=tolerance,
|
|
152
|
+
)
|
|
153
|
+
return cls(gen_particles)
|
|
154
|
+
|
|
155
|
+
def generate(
|
|
156
|
+
self, n_events: int, normalize_weights: bool = True, **kwargs
|
|
157
|
+
) -> (
|
|
158
|
+
tuple[list[tf.Tensor], list[tf.Tensor]]
|
|
159
|
+
| tuple[list[tf.Tensor], list[tf.Tensor], list[tf.Tensor]]
|
|
160
|
+
):
|
|
161
|
+
"""Generate four-momentum vectors from the decay(s).
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
n_events: Total number of events combined, for all the decays.
|
|
165
|
+
normalize_weights: Normalize weights according to all events generated.
|
|
166
|
+
This also changes the return values. See the phasespace documentation for more details.
|
|
167
|
+
kwargs: Additional parameters passed to all calls of ``GenParticle.generate``
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
The arguments returned by ``GenParticle.generate`` are returned. See the phasespace documentation for
|
|
171
|
+
details. However, instead of being 2 or 3 tensors, it is 2 or 3 lists of tensors,
|
|
172
|
+
each entry in the lists corresponding to the return arguments from the corresponding GenParticle
|
|
173
|
+
instances in ``self.gen_particles``. Note that when ``normalize_weights`` is True,
|
|
174
|
+
the weights are normalized to the maximum of all returned events.
|
|
175
|
+
"""
|
|
176
|
+
# Input to tf.random.categorical must be 2D
|
|
177
|
+
rand_i = tf.random.categorical(
|
|
178
|
+
tnp.log([[dm[0] for dm in self.gen_particles]]), n_events
|
|
179
|
+
)
|
|
180
|
+
# Input to tf.unique_with_counts must be 1D
|
|
181
|
+
dec_indices, _, counts = tf.unique_with_counts(rand_i[0])
|
|
182
|
+
counts = tf.cast(counts, tf.int64)
|
|
183
|
+
weights, max_weights, events = [], [], []
|
|
184
|
+
for i, n in zip(dec_indices, counts):
|
|
185
|
+
weight, max_weight, four_vectors = self.gen_particles[i][1].generate(
|
|
186
|
+
n, normalize_weights=False, **kwargs
|
|
187
|
+
)
|
|
188
|
+
weights.append(weight)
|
|
189
|
+
max_weights.append(max_weight)
|
|
190
|
+
events.append(four_vectors)
|
|
191
|
+
|
|
192
|
+
if normalize_weights:
|
|
193
|
+
total_max = tnp.max([tnp.max(mw) for mw in max_weights])
|
|
194
|
+
normed_weights = [w / total_max for w in weights]
|
|
195
|
+
return normed_weights, events
|
|
196
|
+
|
|
197
|
+
return weights, max_weights, events
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _unique_name(name: str, preexisting_particles: set[str]) -> str:
|
|
201
|
+
"""Create a string that does not exist in preexisting_particles based on name.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
name: Original name
|
|
205
|
+
preexisting_particles: Names that the particle cannot have as name.
|
|
206
|
+
|
|
207
|
+
Returns:
|
|
208
|
+
name: Will be ``name`` if ``name`` is not in preexisting_particles or of the format "name [i]" where i
|
|
209
|
+
begins at 0 and increases until the name is not preexisting_particles.
|
|
210
|
+
"""
|
|
211
|
+
if name not in preexisting_particles:
|
|
212
|
+
preexisting_particles.add(name)
|
|
213
|
+
return name
|
|
214
|
+
|
|
215
|
+
name += " [0]"
|
|
216
|
+
i = 1
|
|
217
|
+
while name in preexisting_particles:
|
|
218
|
+
name = name[: name.rfind("[")] + f"[{str(i)}]"
|
|
219
|
+
i += 1
|
|
220
|
+
preexisting_particles.add(name)
|
|
221
|
+
return name
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _get_particle_mass(
|
|
225
|
+
name: str,
|
|
226
|
+
mass_converter: dict[str, Callable],
|
|
227
|
+
mass_func: str,
|
|
228
|
+
tolerance: float,
|
|
229
|
+
) -> Callable | float:
|
|
230
|
+
"""Get mass or mass function of particle using the particle package.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
name: Name of the particle. Name must be recognizable by the particle package.
|
|
234
|
+
mass_converter: See ``_recursively_traverse``
|
|
235
|
+
mass_func: See the name of the mass function, e.g., 'rel-bw'. Must be a valid key for mass_converter.
|
|
236
|
+
tolerance: See ``_recursively_traverse``
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
A function if the mass has a width smaller than tolerance. Otherwise, return a constant mass.
|
|
240
|
+
|
|
241
|
+
Notes:
|
|
242
|
+
TODO try to cache results for this function in the future for speedup.
|
|
243
|
+
"""
|
|
244
|
+
particle = Particle.from_evtgen_name(name)
|
|
245
|
+
|
|
246
|
+
if particle.width <= tolerance:
|
|
247
|
+
return tf.cast(particle.mass, tf.float64)
|
|
248
|
+
# If name does not exist in the predefined mass distributions, use Breit-Wigner
|
|
249
|
+
return mass_converter[mass_func](mass=particle.mass, width=particle.width)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _recursively_traverse(
|
|
253
|
+
decaychain: dict,
|
|
254
|
+
mass_converter: dict[str, Callable],
|
|
255
|
+
particle_model_map: dict[str, str],
|
|
256
|
+
tolerance: float,
|
|
257
|
+
preexisting_particles: set[str] = None,
|
|
258
|
+
) -> list[tuple[float, GenParticle]]:
|
|
259
|
+
"""Create all possible GenParticles by recursively traversing a dict from DecayLanguage, see Examples.
|
|
260
|
+
|
|
261
|
+
Args:
|
|
262
|
+
decaychain: Decay chain with the format from DecayLanguage
|
|
263
|
+
mass_converter: Maps from mass function names to the actual callable mass function.
|
|
264
|
+
particle_model_map: See ``GenMultiDecay.from_dict``.
|
|
265
|
+
preexisting_particles: Names of all particles that have already been created.
|
|
266
|
+
tolerance: Minimum mass width for a particle to set a non-constant mass to a particle.
|
|
267
|
+
If None, set to default value, given by ``GenMultiDecay.MASS_WIDTH_TOLERANCE``
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
The generated GenParticle instances, one for each possible way of the decay.
|
|
271
|
+
"""
|
|
272
|
+
if tolerance is None:
|
|
273
|
+
tolerance = GenMultiDecay.MASS_WIDTH_TOLERANCE
|
|
274
|
+
# Get the only key inside the decaychain dict
|
|
275
|
+
(original_mother_name,) = decaychain.keys()
|
|
276
|
+
|
|
277
|
+
if preexisting_particles is None:
|
|
278
|
+
preexisting_particles = set()
|
|
279
|
+
is_top_particle = True
|
|
280
|
+
else:
|
|
281
|
+
is_top_particle = False
|
|
282
|
+
|
|
283
|
+
# This is in the form of dicts
|
|
284
|
+
decay_modes = decaychain[original_mother_name]
|
|
285
|
+
mother_name = _unique_name(original_mother_name, preexisting_particles)
|
|
286
|
+
# This will contain GenParticle instances and their probabilities
|
|
287
|
+
all_decays = []
|
|
288
|
+
for dm in decay_modes:
|
|
289
|
+
dm_probability = dm["bf"]
|
|
290
|
+
daughter_particles = dm["fs"]
|
|
291
|
+
daughter_gens = []
|
|
292
|
+
|
|
293
|
+
for daughter_name in daughter_particles:
|
|
294
|
+
if isinstance(daughter_name, str):
|
|
295
|
+
# Always use constant mass for stable particles
|
|
296
|
+
daughter = GenParticle(
|
|
297
|
+
_unique_name(daughter_name, preexisting_particles),
|
|
298
|
+
Particle.from_evtgen_name(daughter_name).mass,
|
|
299
|
+
)
|
|
300
|
+
daughter = [(1.0, daughter)]
|
|
301
|
+
elif isinstance(daughter_name, dict):
|
|
302
|
+
daughter = _recursively_traverse(
|
|
303
|
+
daughter_name,
|
|
304
|
+
mass_converter,
|
|
305
|
+
particle_model_map,
|
|
306
|
+
tolerance,
|
|
307
|
+
preexisting_particles,
|
|
308
|
+
)
|
|
309
|
+
else:
|
|
310
|
+
raise TypeError(
|
|
311
|
+
f'Expected elements in decaychain["fs"] to only be str or dict '
|
|
312
|
+
f"but found an instance of type {type(daughter_name)}"
|
|
313
|
+
)
|
|
314
|
+
daughter_gens.append(daughter)
|
|
315
|
+
|
|
316
|
+
for daughter_combination in itertools.product(*daughter_gens):
|
|
317
|
+
p = tnp.prod([decay[0] for decay in daughter_combination]) * dm_probability
|
|
318
|
+
if is_top_particle:
|
|
319
|
+
mother_mass = Particle.from_evtgen_name(original_mother_name).mass
|
|
320
|
+
else:
|
|
321
|
+
if "zfit" in dm:
|
|
322
|
+
mass_func = dm["zfit"]
|
|
323
|
+
elif original_mother_name in particle_model_map:
|
|
324
|
+
mass_func = particle_model_map[original_mother_name]
|
|
325
|
+
else:
|
|
326
|
+
mass_func = GenMultiDecay.DEFAULT_MASS_FUNC
|
|
327
|
+
|
|
328
|
+
mother_mass = _get_particle_mass(
|
|
329
|
+
original_mother_name,
|
|
330
|
+
mass_converter=mass_converter,
|
|
331
|
+
mass_func=mass_func,
|
|
332
|
+
tolerance=tolerance,
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
one_decay = GenParticle(mother_name, mother_mass).set_children(
|
|
336
|
+
*(decay[1] for decay in daughter_combination)
|
|
337
|
+
)
|
|
338
|
+
all_decays.append((p, one_decay))
|
|
339
|
+
|
|
340
|
+
return all_decays
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Mass distribution functions for resonant particles.
|
|
2
|
+
|
|
3
|
+
This module provides factory functions that create mass distribution functions for resonant particles. These
|
|
4
|
+
functions use zfit PDFs to sample masses from various distributions (Gaussian, Breit-Wigner, etc.) within
|
|
5
|
+
specified limits.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import tensorflow as tf
|
|
9
|
+
import zfit
|
|
10
|
+
import zfit_physics as zphys
|
|
11
|
+
|
|
12
|
+
# TODO refactor these mass functions using e.g. a decorator.
|
|
13
|
+
# Right now there is a lot of code repetition.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def gauss_factory(mass, width):
|
|
17
|
+
"""Create a Gaussian mass distribution function.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
mass: Mean mass of the particle.
|
|
21
|
+
width: Width (sigma) of the Gaussian distribution.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
Callable that generates masses from a Gaussian distribution.
|
|
25
|
+
The returned function accepts ``min_mass``, ``max_mass``, and ``n_events``
|
|
26
|
+
parameters and returns sampled masses as a tensor of shape ``(n_events,)``.
|
|
27
|
+
"""
|
|
28
|
+
particle_mass = tf.cast(mass, tf.float64)
|
|
29
|
+
particle_width = tf.cast(width, tf.float64)
|
|
30
|
+
|
|
31
|
+
def gauss(min_mass, max_mass, n_events):
|
|
32
|
+
min_mass = tf.cast(min_mass, tf.float64)
|
|
33
|
+
max_mass = tf.cast(max_mass, tf.float64)
|
|
34
|
+
pdf = zfit.pdf.Gauss(mu=particle_mass, sigma=particle_width, obs="")
|
|
35
|
+
iterator = tf.stack([min_mass, max_mass], axis=-1)
|
|
36
|
+
return tf.vectorized_map(
|
|
37
|
+
lambda lim: pdf.sample(1, limits=(lim[0], lim[1])).unstack_x(), iterator
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
return gauss
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def breitwigner_factory(mass, width):
|
|
44
|
+
"""Create a Breit-Wigner (Cauchy) mass distribution function.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
mass: Central mass (m) of the particle.
|
|
48
|
+
width: Width (gamma) of the Breit-Wigner distribution.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
Callable that generates masses from a Breit-Wigner distribution.
|
|
52
|
+
The returned function accepts ``min_mass``, ``max_mass``, and ``n_events``
|
|
53
|
+
parameters and returns sampled masses as a tensor of shape ``(n_events,)``.
|
|
54
|
+
"""
|
|
55
|
+
particle_mass = tf.cast(mass, tf.float64)
|
|
56
|
+
particle_width = tf.cast(width, tf.float64)
|
|
57
|
+
|
|
58
|
+
def bw(min_mass, max_mass, n_events):
|
|
59
|
+
min_mass = tf.cast(min_mass, tf.float64)
|
|
60
|
+
max_mass = tf.cast(max_mass, tf.float64)
|
|
61
|
+
pdf = zfit.pdf.Cauchy(m=particle_mass, gamma=particle_width, obs="")
|
|
62
|
+
iterator = tf.stack([min_mass, max_mass], axis=-1)
|
|
63
|
+
return tf.vectorized_map(
|
|
64
|
+
lambda lim: pdf.sample(1, limits=(lim[0], lim[1])).unstack_x(), iterator
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
return bw
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def relativistic_breitwigner_factory(mass, width):
|
|
71
|
+
"""Create a relativistic Breit-Wigner mass distribution function.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
mass: Central mass (m) of the particle.
|
|
75
|
+
width: Width (gamma) of the relativistic Breit-Wigner distribution.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
Callable that generates masses from a relativistic Breit-Wigner distribution.
|
|
79
|
+
The returned function accepts ``min_mass``, ``max_mass``, and ``n_events``
|
|
80
|
+
parameters and returns sampled masses as a tensor of shape ``(n_events,)``.
|
|
81
|
+
|
|
82
|
+
Notes:
|
|
83
|
+
This uses ``tf.map_fn`` instead of ``tf.vectorized_map`` as no analytic
|
|
84
|
+
sampling is available for the relativistic Breit-Wigner distribution.
|
|
85
|
+
"""
|
|
86
|
+
particle_mass = tf.cast(mass, tf.float64)
|
|
87
|
+
particle_width = tf.cast(width, tf.float64)
|
|
88
|
+
|
|
89
|
+
def relbw(min_mass, max_mass, n_events):
|
|
90
|
+
min_mass = tf.cast(min_mass, tf.float64)
|
|
91
|
+
max_mass = tf.cast(max_mass, tf.float64)
|
|
92
|
+
pdf = zphys.pdf.RelativisticBreitWigner(
|
|
93
|
+
m=particle_mass, gamma=particle_width, obs=""
|
|
94
|
+
)
|
|
95
|
+
iterator = tf.stack([min_mass, max_mass], axis=-1)
|
|
96
|
+
|
|
97
|
+
# this works with map_fn but not with vectorized_map as no analytic sampling is available.
|
|
98
|
+
return tf.map_fn(
|
|
99
|
+
lambda lim: pdf.sample(1, limits=(lim[0], lim[1])).unstack_x(), iterator
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
return relbw
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
DEFAULT_CONVERTER = {
|
|
106
|
+
"gauss": gauss_factory,
|
|
107
|
+
"bw": breitwigner_factory,
|
|
108
|
+
"relbw": relativistic_breitwigner_factory,
|
|
109
|
+
}
|