FairShip
Loading...
Searching...
No Matches
pythia8_conf_utils Namespace Reference

Functions

None addHNLtoROOT (int pid=9900015, float m=1.0, float g=3.654203020370371e-21)
 getbr_rpvsusy (h, histoname, mass, coupling)
 getmaxsumbrrpvsusy (h, histograms, mass, couplings)
float gettotalbrrpvsusy (h, histograms, mass, couplings)
None make_particles_stable (P8gen, above_lifetime)
 parse_histograms (filepath)
 make_interpolators (filepath, str kind="linear")
 get_br (histograms, channel, mass, couplings)
None add_particles (P8gen, particles, data)
None add_channel (P8gen, ch, histograms, mass, couplings, scale_factor)
None add_tau_channel (P8gen, ch, histograms, mass, couplings, scale_factor)
None fill_missing_channels (P8gen, max_total_br, decay_chains, float epsilon=1e-6)
None add_dummy_channel (P8gen, particle, remainder)
float compute_max_total_br (decay_chains)
float compute_total_br (particle, decay_chains)
 get_top_level_particles (decay_chains)
None exit_if_zero_br (max_total_br, selection, mass, str particle="HNL")
None print_scale_factor (scaling_factor)

Function Documentation

◆ add_channel()

None pythia8_conf_utils.add_channel ( P8gen,
ch,
histograms,
mass,
couplings,
scale_factor )

Definition at line 161 of file pythia8_conf_utils.py.

161def add_channel(P8gen, ch, histograms, mass, couplings, scale_factor) -> None:
162 "Add to PYTHIA a leptonic or semileptonic decay channel to HNL."
163 if "idlepton" in ch:
164 br = get_br(histograms, ch, mass, couplings)
165 if br <= 0: # Ignore kinematically closed channels
166 return
167 if "idhadron" in ch: # Semileptonic decay
168 P8gen.SetParameters(
169 "{}:addChannel 1 {:.17} 22 {} 9900015 {}".format(
170 ch["id"], br * scale_factor, ch["idlepton"], ch["idhadron"]
171 )
172 )
173 else: # Leptonic decay
174 P8gen.SetParameters(
175 "{}:addChannel 1 {:.17} 0 9900015 {}".format(
176 ch["id"], br * scale_factor, ch["idlepton"]
177 )
178 )
179 else: # Wrong decay
180 raise ValueError(f"Missing key 'idlepton' in channel {ch}")
181
182

◆ add_dummy_channel()

None pythia8_conf_utils.add_dummy_channel ( P8gen,
particle,
remainder )
Add a dummy channel to PYTHIA, with branching ratio equal to `remainder.`

The purpose of this function is to compensate for the absence of SM
channels, which are ignored when investigating rare processes. A dummy
decay channel is instead added to each particle in order to maintain the
correct ratios between the branching ratios of each particle to rare
processes. This is usually combined with a global reweighting of the
branching ratios.

In order to keep PYTHIA from complaining about charge conservation, a
suitable process is added which conserves electric charge.

All dummy channels can be identified by the presence of a photon among the
decay products.

Definition at line 225 of file pythia8_conf_utils.py.

225def add_dummy_channel(P8gen, particle, remainder) -> None:
226 """
227 Add a dummy channel to PYTHIA, with branching ratio equal to `remainder.`
228
229 The purpose of this function is to compensate for the absence of SM
230 channels, which are ignored when investigating rare processes. A dummy
231 decay channel is instead added to each particle in order to maintain the
232 correct ratios between the branching ratios of each particle to rare
233 processes. This is usually combined with a global reweighting of the
234 branching ratios.
235
236 In order to keep PYTHIA from complaining about charge conservation, a
237 suitable process is added which conserves electric charge.
238
239 All dummy channels can be identified by the presence of a photon among the
240 decay products.
241 """
242 pdg = P8gen.getPythiaInstance().particleData
243 charge = pdg.charge(particle)
244 if charge > 0:
245 P8gen.SetParameters(f"{particle}:addChannel 1 {remainder:.16} 0 22 -11")
246 elif charge < 0:
247 P8gen.SetParameters(f"{particle}:addChannel 1 {remainder:.16} 0 22 11")
248 else:
249 P8gen.SetParameters(f"{particle}:addChannel 1 {remainder:.16} 0 22 22")
250
251

◆ add_particles()

None pythia8_conf_utils.add_particles ( P8gen,
particles,
data )
Adds the corresponding particles to PYTHIA.

`particles` must be a list containing either the particles PDG IDs, or
their PYTHIA names. The commands needed to add the particles are queried
from `data`.

If the particle is not self-conjugate, the antiparticle is automatically
added by PYTHIA.

Definition at line 141 of file pythia8_conf_utils.py.

141def add_particles(P8gen, particles, data) -> None:
142 """
143 Adds the corresponding particles to PYTHIA.
144
145 `particles` must be a list containing either the particles PDG IDs, or
146 their PYTHIA names. The commands needed to add the particles are queried
147 from `data`.
148
149 If the particle is not self-conjugate, the antiparticle is automatically
150 added by PYTHIA.
151 """
152 for particle_id in particles:
153 # Find particle in database (None: particle not found)
154 particle = next((p for p in data["particles"] if particle_id in [p["id"], p["name"]]), None)
155 if particle is None:
156 raise ValueError(f"Could not find particle ID {particle_id} in particle database")
157 # Add the particle
158 P8gen.SetParameters(particle["cmd"])
159
160

◆ add_tau_channel()

None pythia8_conf_utils.add_tau_channel ( P8gen,
ch,
histograms,
mass,
couplings,
scale_factor )

Definition at line 183 of file pythia8_conf_utils.py.

183def add_tau_channel(P8gen, ch, histograms, mass, couplings, scale_factor) -> None:
184 "Add to PYTHIA a tau decay channel to HNL."
185 if "idhadron" in ch:
186 br = get_br(histograms, ch, mass, couplings)
187 if br <= 0: # Ignore kinematically closed channels
188 return
189 if "idlepton" in ch: # 3-body leptonic decay
190 P8gen.SetParameters(
191 "{}:addChannel 1 {:.16} 1531 9900015 {} {}".format(
192 ch["id"], br * scale_factor, ch["idlepton"], ch["idhadron"]
193 )
194 )
195 else: # 2-body semileptonic decay
196 P8gen.SetParameters(
197 "{}:addChannel 1 {:.16} 1521 9900015 {}".format(
198 ch["id"], br * scale_factor, ch["idhadron"]
199 )
200 )
201 else:
202 raise ValueError(f"Missing key 'idhadron' in channel {ch}")
203
204

◆ addHNLtoROOT()

None pythia8_conf_utils.addHNLtoROOT ( int pid = 9900015,
float m = 1.0,
float g = 3.654203020370371e-21 )

Definition at line 12 of file pythia8_conf_utils.py.

12def addHNLtoROOT(pid: int = 9900015, m: float = 1.0, g: float = 3.654203020370371e-21) -> None:
13 pdg = ROOT.TDatabasePDG.Instance()
14 pdg.AddParticle("N2", "HNL", m, False, g, 0.0, "N2", pid)
15
16

◆ compute_max_total_br()

float pythia8_conf_utils.compute_max_total_br ( decay_chains)
This function computes the maximum total branching ratio for all decay chains.

In order to make the event generation as efficient as possible when
studying very rare processes, it is necessary to rescale the branching
ratios, while enforcing the invariant that any total branching ratio must
remain lower that unity.

This is accomplished by computing, for each particle, the total branching
ratio to processes of interest, and then dividing all branching ratios by
the highest of those.

Note: the decay chain length must be at most 2.

Definition at line 252 of file pythia8_conf_utils.py.

252def compute_max_total_br(decay_chains) -> float:
253 """
254 This function computes the maximum total branching ratio for all decay chains.
255
256 In order to make the event generation as efficient as possible when
257 studying very rare processes, it is necessary to rescale the branching
258 ratios, while enforcing the invariant that any total branching ratio must
259 remain lower that unity.
260
261 This is accomplished by computing, for each particle, the total branching
262 ratio to processes of interest, and then dividing all branching ratios by
263 the highest of those.
264
265 Note: the decay chain length must be at most 2.
266 """
267 # For each top-level charmed particle, sum BR over all its decay chains
268 top_level_particles = get_top_level_particles(decay_chains)
269 total_branching_ratios = [compute_total_br(particle, decay_chains) for particle in top_level_particles]
270 # Find the maximum total branching ratio
271 return max(total_branching_ratios)
272
273

◆ compute_total_br()

float pythia8_conf_utils.compute_total_br ( particle,
decay_chains )
Returns the total branching ratio to HNLs for a given particle.

Definition at line 274 of file pythia8_conf_utils.py.

274def compute_total_br(particle, decay_chains) -> float:
275 """
276 Returns the total branching ratio to HNLs for a given particle.
277 """
278 return sum(float(np.prod(branching_ratios)) for (top, branching_ratios) in decay_chains if top == particle)
279
280

◆ exit_if_zero_br()

None pythia8_conf_utils.exit_if_zero_br ( max_total_br,
selection,
mass,
str particle = "HNL" )

Definition at line 288 of file pythia8_conf_utils.py.

288def exit_if_zero_br(max_total_br, selection, mass, particle: str = "HNL") -> None:
289 if max_total_br <= 0:
290 print(f"No phase space for {particle} from {selection} at this mass: {mass}. Quitting.")
291 sys.exit()
292
293

◆ fill_missing_channels()

None pythia8_conf_utils.fill_missing_channels ( P8gen,
max_total_br,
decay_chains,
float epsilon = 1e-6 )
Add dummy channels for correct rejection sampling.

Even after rescaling the branching ratios, they do not sum up to unity
for most particles since we are ignoring SM processes.

This function adds a "filler" channel for each particle, in order to
preserve the ratios between different branching ratios.

Definition at line 205 of file pythia8_conf_utils.py.

205def fill_missing_channels(P8gen, max_total_br, decay_chains, epsilon: float = 1e-6) -> None:
206 """
207 Add dummy channels for correct rejection sampling.
208
209 Even after rescaling the branching ratios, they do not sum up to unity
210 for most particles since we are ignoring SM processes.
211
212 This function adds a "filler" channel for each particle, in order to
213 preserve the ratios between different branching ratios.
214 """
215 top_level_particles = get_top_level_particles(decay_chains)
216 for particle in top_level_particles:
217 my_total_br = compute_total_br(particle, decay_chains)
218 remainder = 1 - my_total_br / max_total_br
219 assert remainder > -epsilon
220 assert remainder < 1 + epsilon
221 if remainder > epsilon:
222 add_dummy_channel(P8gen, particle, remainder)
223
224

◆ get_br()

pythia8_conf_utils.get_br ( histograms,
channel,
mass,
couplings )
Utility function used to reliably query the branching ratio for a given
channel at a given mass, taking into account the correct coupling.

Definition at line 130 of file pythia8_conf_utils.py.

130def get_br(histograms, channel, mass, couplings):
131 """
132 Utility function used to reliably query the branching ratio for a given
133 channel at a given mass, taking into account the correct coupling.
134 """
135 hist = histograms[channel["decay"]]
136 coupling = couplings[channel["coupling"]]
137 normalized_br = hist(mass)
138 return normalized_br * coupling
139
140

◆ get_top_level_particles()

pythia8_conf_utils.get_top_level_particles ( decay_chains)
Returns the set of particles which are at the top of a decay chain.

Definition at line 281 of file pythia8_conf_utils.py.

281def get_top_level_particles(decay_chains):
282 """
283 Returns the set of particles which are at the top of a decay chain.
284 """
285 return {top for (top, branching_ratios) in decay_chains}
286
287

◆ getbr_rpvsusy()

pythia8_conf_utils.getbr_rpvsusy ( h,
histoname,
mass,
coupling )

Definition at line 17 of file pythia8_conf_utils.py.

17def getbr_rpvsusy(h, histoname, mass, coupling):
18 if histoname in h:
19 normalized_br = h[histoname](mass)
20 br = normalized_br * coupling
21 else:
22 br = 0
23 return br
24
25

◆ getmaxsumbrrpvsusy()

pythia8_conf_utils.getmaxsumbrrpvsusy ( h,
histograms,
mass,
couplings )

Definition at line 26 of file pythia8_conf_utils.py.

26def getmaxsumbrrpvsusy(h, histograms, mass, couplings):
27 # 0 MeV< mass < 3.200 GeV
28 maxsumbr = 0.0
29 sumbrs = {}
30 for histoname in histograms:
31 item = histoname.split("_")
32 meson = item[0]
33 coupling = couplings[1]
34 try:
35 sumbrs[meson] += getbr_rpvsusy(h, histoname, mass, coupling)
36 except KeyError:
37 sumbrs[meson] = getbr_rpvsusy(h, histoname, mass, coupling)
38 print(list(sumbrs.values()))
39 maxsumbr = max(sumbrs.values())
40 return maxsumbr
41
42

◆ gettotalbrrpvsusy()

float pythia8_conf_utils.gettotalbrrpvsusy ( h,
histograms,
mass,
couplings )

Definition at line 43 of file pythia8_conf_utils.py.

43def gettotalbrrpvsusy(h, histograms, mass, couplings) -> float:
44 totalbr = 0.0
45 for histoname in histograms:
46 histoname.split("_")
47 coupling = couplings[1]
48 totalbr += getbr_rpvsusy(h, histoname, mass, coupling)
49 return totalbr
50
51

◆ make_interpolators()

pythia8_conf_utils.make_interpolators ( filepath,
str kind = "linear" )
This function reads a file containing branching ratio histograms, and
returns a dictionary of interpolators of the branching ratios, indexed by
the decay string.

Definition at line 115 of file pythia8_conf_utils.py.

115def make_interpolators(filepath, kind: str = "linear"):
116 """
117 This function reads a file containing branching ratio histograms, and
118 returns a dictionary of interpolators of the branching ratios, indexed by
119 the decay string.
120 """
121 histogram_data = parse_histograms(filepath)
122 histograms = {}
123 for hist_string, (masses, br) in histogram_data.items():
124 histograms[hist_string] = scipy.interpolate.interp1d(
125 masses, br, kind=kind, bounds_error=False, fill_value=0, assume_sorted=True
126 )
127 return histograms
128
129

◆ make_particles_stable()

None pythia8_conf_utils.make_particles_stable ( P8gen,
above_lifetime )
Make the particles with a lifetime above the specified one stable, to allow
them to decay in Geant4 instead.

Definition at line 52 of file pythia8_conf_utils.py.

52def make_particles_stable(P8gen, above_lifetime) -> None:
53 # FIXME: find time unit and add it to the docstring
54 """
55 Make the particles with a lifetime above the specified one stable, to allow
56 them to decay in Geant4 instead.
57 """
58 p8 = P8gen.getPythiaInstance()
59 n = 1
60 while n != 0:
61 n = p8.particleData.nextId(n)
62 p = p8.particleData.particleDataEntryPtr(n)
63 if p.tau0() > above_lifetime:
64 command = f"{n}:mayDecay = false"
65 p8.readString(command)
66 print(f"Pythia8 configuration: Made {p.name()} stable for Pythia, should decay in Geant4")
67
68

◆ parse_histograms()

pythia8_conf_utils.parse_histograms ( filepath)
This function parses a file containing histograms of branching ratios.

It places them in a dictionary indexed by the decay string (e.g. 'd_K0_e'),
as a pair ([masses...], [branching ratios...]), where the mass is expressed
in GeV.

Definition at line 69 of file pythia8_conf_utils.py.

69def parse_histograms(filepath):
70 """
71 This function parses a file containing histograms of branching ratios.
72
73 It places them in a dictionary indexed by the decay string (e.g. 'd_K0_e'),
74 as a pair ([masses...], [branching ratios...]), where the mass is expressed
75 in GeV.
76 """
77 with open(filepath) as f:
78 lines = f.readlines()
79 # Define regular expressions matching (sub-)headers and data lines
80 th1f_exp = re.compile(r"^TH1F\|.+")
81 header_exp = re.compile(r"^TH1F\|(.+?)\|B(?:R|F)/U2(.+?)\|.+? mass \‍(GeV\‍)\|?")
82 subheader_exp = re.compile(r"^\s*?(\d+?),\s*(\d+?\.\d+?),\s*(\d+\.\d+)\s*$")
83 data_exp = re.compile(r"^\s*(\d+?)\s*,\s*(-?\d+\.\d+)\s*$")
84 # Locate beginning of each histogram
85 header_line_idx = [i for i in range(len(lines)) if th1f_exp.match(lines[i]) is not None]
86 # Iterate over histograms
87 histograms = {}
88 for offset in header_line_idx:
89 # Parse header
90 mh = header_exp.match(lines[offset])
91 if mh is None or len(mh.groups()) != 2:
92 raise ValueError(f"Malformed header encountered: {lines[offset]}")
93 decay_code = mh.group(1)
94 # Parse sub-header (min/max mass and number of points)
95 ms = subheader_exp.match(lines[offset + 1])
96 if ms is None or len(ms.groups()) != 3:
97 raise ValueError(f"Malformed sub-header encountered: {lines[offset + 1]}")
98 npoints = int(ms.group(1))
99 min_mass = float(ms.group(2))
100 max_mass = float(ms.group(3))
101 masses = np.linspace(min_mass, max_mass, npoints, endpoint=False)
102 branching_ratios = np.zeros(npoints)
103 # Now read the data lines (skipping the two header lines)
104 for line in lines[offset + 2 : offset + npoints + 2]:
105 md = data_exp.match(line)
106 if md is None or len(md.groups()) != 2:
107 raise ValueError(f"Malformed data row encountered: {line}")
108 idx = int(md.group(1))
109 br = float(md.group(2))
110 branching_ratios[idx] = br
111 histograms[decay_code] = (masses, branching_ratios)
112 return histograms
113
114

◆ print_scale_factor()

None pythia8_conf_utils.print_scale_factor ( scaling_factor)

Definition at line 294 of file pythia8_conf_utils.py.

294def print_scale_factor(scaling_factor) -> None:
295 "Prints the scale factor used to make event generation more efficient."
296 print(f"One simulated event per {scaling_factor:.4g} meson decays")