FairShip
Loading...
Searching...
No Matches
makeCascade.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4import argparse
5import copy
6import os
7import random
8import sys
9import time
10from array import array
11from typing import Any
12
13import ROOT
14import rootUtils as ut
15
16ROOT.gROOT.LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C")
17ROOT.basiclibs()
18timer = ROOT.TStopwatch()
19timer.Start()
20
21ap = argparse.ArgumentParser(description="Run SHiP makeCascade: generate ccbar or bbar")
22ap.add_argument(
23 "-s",
24 "--seed",
25 type=int,
26 default=int(time.time() * 100000000 % 900000000),
27 help="Random number seed, integer. If not given, current time will be used",
28)
29ap.add_argument(
30 "-t",
31 "--Fntuple",
32 default="",
33 help="Name of ntuple output file, default: Cascade{nevgen/1000}k-parp16-MSTP82-1-MSEL{mselcb}-ntuple.root",
34)
35ap.add_argument("-n", "--nevgen", type=int, default=100000, help="Number of events to produce, default 100000")
36ap.add_argument("-E", "--pbeamh", type=float, default=400.0, help="Energy of beam in GeV, default 400 GeV")
37ap.add_argument(
38 "-m", "--mselcb", type=int, default=4, help="4 (5): charm (beauty) production, default charm", choices=[4, 5]
39)
40ap.add_argument(
41 "-P",
42 "--storePrimaries",
43 action=argparse.BooleanOptionalAction,
44 default=False,
45 help="If this argument is used, store all particles produced together with charm.",
46)
47ap.add_argument(
48 "--target-composition",
49 default="W",
50 help="Target composition (to determine the ratio of protons in the material). Default is Tungsten (W). Only other choice is Molybdenum (Mo)",
51 choices=["W", "Mo"],
52)
53ap.add_argument(
54 "--pythia_tune",
55 default="PoorE791",
56 help="Choices of Pythia tune are PoorE791 (default, settings with default Pythia6 pdf, based on getting <pt> at 500 GeV pi-) or LHCb (settings by LHCb for Pythia 6.427)",
57 choices=["PoorE791", "LHCb"],
58)
59# some parameters for generating the chi (sigma(signal)/sigma(total) as a function of momentum
60ap.add_argument("--nev", type=int, default=5000, help="Events / momentum")
61ap.add_argument("--nrpoints", type=int, default=20, help="Number of momentum points taken to calculate sig/sigtot")
62
63args = ap.parse_args()
64if args.Fntuple == "":
65 args.Fntuple = f"Cascade{int(args.nevgen / 1000)}k-parp16-MSTP82-1-MSEL{args.mselcb}-ntuple.root"
66
67print(f"Generate {args.nevgen} p.o.t. with msel = {args.mselcb} proton beam {args.pbeamh}GeV")
68print(f"Output ntuples written to: {args.Fntuple}")
69
70# cascade beam particles, anti-particles are generated automatically if they exist.
71idbeam = [2212, 211, 2112, 321, 130, 310]
72target = ["p+", "n0"]
73print(f"Chi generation with {args.nev} events/point, nr points={args.nrpoints}")
74print(f"Cascade beam particle: {idbeam}")
75
76# fracp is the fraction of protons in nucleus, used to average chi on p and n target in Pythia.
77if args.target_composition == "W": # target is Tungsten, fracp is 74/(184)
78 fracp = 0.40
79else: # target would then be Molybdenum, fracp is 42/98
80 fracp = 0.43
81
82print(f"Target particles: {target}, fraction of protons in {args.target_composition}={fracp}")
83
84# lower/upper momentum limit for beam, depends on msel..
85# signal particles wanted (and their antis), which could decay semi-leptonically.
86if args.mselcb == 4:
87 pbeaml = 34.0
88 idsig = [411, 421, 431, 4122, 4132, 4232, 4332, 4412, 4414, 4422, 4424, 4432, 4434, 4444]
89elif args.mselcb == 5:
90 pbeaml = 130.0
91 idsig = [
92 511,
93 521,
94 531,
95 541,
96 5122,
97 5132,
98 5142,
99 5232,
100 5242,
101 5332,
102 5342,
103 5412,
104 5414,
105 5422,
106 5424,
107 5432,
108 5434,
109 5442,
110 5444,
111 5512,
112 5514,
113 5522,
114 5524,
115 5532,
116 5534,
117 5542,
118 5544,
119 5554,
120 ]
121else:
122 print(f"Error: msel is unknown: {args.mselcb}, STOP program")
123 sys.exit("ERROR on input, exit")
124
125PDG = ROOT.TDatabasePDG.Instance()
126myPythia = ROOT.TPythia6()
127tp = ROOT.tPythia6Generator()
128
129# Pythia6 can only accept names below in pyinit, hence reset PDG table:
130for _pdg_code, _name in [(2212, "p+"), (-2212, "pbar-"), (2112, "n0"), (-2112, "nbar0"), (130, "KL0"), (310, "KS0")]:
131 _p = ut.get_particle(_pdg_code)
132 _p.SetName(_name)
133# lower lowest sqrt(s) allowed for generating events
134myPythia.SetPARP(2, 2.0)
135
136
137def PoorE791_tune(P6) -> None:
138 # settings with default Pythia6 pdf, based on getting <pt> at 500 GeV pi-
139 # same as that of E791: http://arxiv.org/pdf/hep-ex/9906034.pdf
140 print(" ")
141 print("********** PoorE791_tune **********")
142 # change pt of D's to mimic E791 data.
143 P6.SetPARP(91, 1.6)
144 print(f"PARP(91)={P6.GetPARP(91)}")
145 # what PDFs etc.. are being used:
146 print("MSTP PDF info, i.e. (51) and (52)=", P6.GetMSTP(51), P6.GetMSTP(52))
147 # set multiple interactions equal to Fortran version, i.e.=1, default=4, and adapt parp(89) accordingly
148 P6.SetMSTP(82, 1)
149 P6.SetPARP(89, 1000.0)
150 print(
151 "And corresponding multiple parton stuff, i.e. MSTP(82),PARP(81,89,90)=",
152 P6.GetMSTP(82),
153 P6.GetPARP(81),
154 P6.GetPARP(89),
155 P6.GetPARP(90),
156 )
157 print("********** PoorE791_tune **********")
158 print(" ")
159
160
161def LHCb_tune(P6) -> None:
162 # settings by LHCb for Pythia 6.427
163 # https://twiki.cern.ch/twiki/bin/view/LHCb/SettingsSim08
164 print(" ")
165 print("********** LHCb_tune **********")
166 # P6.SetCKIN(41,3.0)
167 P6.SetMSTP(2, 2)
168 P6.SetMSTP(33, 3)
169 # P6.SetMSTP(128, 2) # store or not store
170 P6.SetMSTP(81, 21)
171 P6.SetMSTP(82, 3)
172 P6.SetMSTP(52, 2)
173 P6.SetMSTP(51, 10042) # (ie CTEQ6 LO fit, with LOrder alpha_S PDF from LHAPDF)
174 P6.SetMSTP(142, 0) # do not weigh events
175 P6.SetPARP(67, 1.0)
176 P6.SetPARP(82, 4.28)
177 P6.SetPARP(89, 14000)
178 P6.SetPARP(90, 0.238)
179 P6.SetPARP(85, 0.33)
180 P6.SetPARP(86, 0.66)
181 P6.SetPARP(91, 1.0)
182 P6.SetPARP(149, 0.02)
183 P6.SetPARP(150, 0.085)
184 P6.SetPARJ(11, 0.4)
185 P6.SetPARJ(12, 0.4)
186 P6.SetPARJ(13, 0.769)
187 P6.SetPARJ(14, 0.09)
188 P6.SetPARJ(15, 0.018)
189 P6.SetPARJ(16, 0.0815)
190 P6.SetPARJ(17, 0.0815)
191 P6.SetMSTJ(26, 0)
192 P6.SetPARJ(33, 0.4)
193 print("********** LHCb_tune **********")
194 print(" ")
195
196
197def fillp1(hist) -> None:
198 # scan filled bins in hist, and fill intermediate bins with linear interpolation
199 nb = hist.GetNbinsX()
200 i1 = hist.FindBin(pbeaml, 0.0, 0.0)
201 y1 = hist.GetBinContent(i1)
202 p1 = hist.GetBinCenter(i1)
203 for i in range(i1 + 1, nb + 1):
204 if hist.GetBinContent(i) > 0.0:
205 y2 = hist.GetBinContent(i)
206 p2 = hist.GetBinCenter(i)
207 tg = (y2 - y1) / (p2 - p1)
208 for ib in range(i1 + 1, i):
209 px = hist.GetBinCenter(ib)
210 yx = (px - p1) * tg + y1
211 hist.Fill(px, yx)
212 i1 = i
213 y1 = y2
214 p1 = p2
215
216
217if args.pythia_tune == "PoorE791":
218 PoorE791_tune(myPythia)
219 myPythia.OpenFortranFile(11, os.devnull) # Pythia output to dummy (11) file (to screen use 6)
220 myPythia.SetMSTU(11, 11)
221else:
222 LHCb_tune(myPythia)
223 myPythia.OpenFortranFile(6, os.devnull) # avoid any printing to the screen, only when LHAPDF is used, in LHCb tune
224
225# start with different random number for each run...
226print(f"Setting random number seed = {args.seed}")
227myPythia.SetMRPY(1, args.seed)
228
229# histogram helper
230h = {}
231
232# initialise phase, determine chi=sigma(signal)/sigma(total) for many beam momenta.
233# loop over beam particles
234id = 0
235nb = 400
236t0 = time.time()
237idhist = len(idbeam) * 4 * [0]
238print("Get chi vs momentum for all beam+target particles")
239for idp in range(0, len(idbeam)):
240 for idpm in [-1, 1]: # particle or anti-particle
241 idw = idbeam[idp] * idpm
242 _p = PDG.GetParticle(idw)
243 if _p: # if particle exists, book hists etc.
244 name = _p.GetName()
245 id = id + 1
246 for idnp in range(2):
247 idb = id * 10 + idnp * 4
248 ut.bookHist(h, str(idb + 1), f"sigma vs p, {name} -> {target[idnp]}", nb, 0.5, args.pbeamh + 0.5)
249 ut.bookHist(h, str(idb + 2), f"sigma-tot vs p, {name} -> {target[idnp]}", nb, 0.5, args.pbeamh + 0.5)
250 ut.bookHist(h, str(idb + 3), f"chi vs p, {name}-> {target[idnp]}", nb, 0.5, args.pbeamh + 0.5)
251 ut.bookHist(h, str(idb + 4), f"Prob(normalised), {name} -> {target[idnp]}", nb, 0.5, args.pbeamh + 0.5)
252 # keep track of histogram<->Particle id relation.
253 idhist[id] = idw
254 for idpn in range(2): # target is proton or neutron
255 idadd = idpn * 4
256 print(f"{name}, {target[idpn]}, for chi, seconds: {time.time() - t0}")
257 for ipbeam in range(args.nrpoints): # loop over beam momentum
258 pbw = ipbeam * (args.pbeamh - pbeaml) / (args.nrpoints - 1) + pbeaml
259 # convert to center of a bin
260 ibin = h[str(id * 10 + 1 + idadd)].FindBin(pbw, 0.0, 0.0)
261 pbw = h[str(id * 10 + 1 + idadd)].GetBinCenter(ibin)
262 # new particle/momentum, init again, first signal run.
263 myPythia.SetMSEL(args.mselcb) # set forced ccbar or bbbar generation
264 myPythia.Initialize("FIXT", name, target[idpn], pbw)
265 for iev in range(args.nev):
266 myPythia.GenerateEvent()
267 # signal run finished, get cross-section
268 h[str(id * 10 + 1 + idadd)].Fill(pbw, tp.getPyint5_XSEC(2, 0))
269 myPythia.SetMSEL(2) # now total cross-section, i.e. msel=2
270 myPythia.Initialize("FIXT", name, target[idpn], pbw)
271 for iev in range(args.nev // 10):
272 # if iev%100==0: print 'generated mbias events',iev,' seconds:',time.time()-t0
273 myPythia.GenerateEvent()
274 # get cross-section
275 h[str(id * 10 + 2 + idadd)].Fill(pbw, tp.getPyint5_XSEC(2, 0))
276 # for this beam particle, do arithmetic to get chi.
277 h[str(id * 10 + 3 + idadd)].Divide(h[str(id * 10 + 1 + idadd)], h[str(id * 10 + 2 + idadd)], 1.0, 1.0)
278 # fill with linear function between evaluated momentum points.
279 fillp1(h[str(id * 10 + 3 + idadd)])
280
281# collected all, now re-scale to make max chi at 400 Gev==1.
282chimx = 0.0
283for i in range(1, id + 1):
284 for idpn in range(2):
285 idw = i * 10 + idpn * 4 + 3
286 ibh = h[str(idw)].FindBin(args.pbeamh)
287 print(
288 f"beam id: {i}, {idw}, {idhist[i]}, momentum: {args.pbeamh},chi: {h[str(idw)].GetBinContent(ibh)}, chimx: {chimx}"
289 )
290 if h[str(idw)].GetBinContent(ibh) > chimx:
291 chimx = h[str(idw)].GetBinContent(ibh)
292chimx = 1.0 / chimx
293for i in range(1, id + 1):
294 for idpn in range(2):
295 idw = i * 10 + idpn * 4 + 3
296 h[str(idw + 1)].Add(h[str(idw)], h[str(idw)], chimx, 0.0)
297
298# switch output printing OFF for generation phase.
299# Generate ccbar (or bbbar) pairs according to probability in hists i*10+8.
300# some check histos
301ut.bookHist(h, str(1), "E of signals", 100, 0.0, 400.0)
302ut.bookHist(h, str(2), "nr signal per cascade depth", 50, 0.5, 50.5)
303ut.bookHist(h, str(3), "D0 pt**2", 40, 0.0, 4.0)
304ut.bookHist(h, str(4), "D0 pt**2", 100, 0.0, 18.0)
305ut.bookHist(h, str(5), "D0 pt", 100, 0.0, 10.0)
306ut.bookHist(h, str(6), "D0 XF", 100, -1.0, 1.0)
307
308ftup = ROOT.TFile.Open(args.Fntuple, "RECREATE")
309Ntup = ROOT.TNtuple(
310 "pythia6",
311 "pythia6 heavy flavour",
312 "id:px:py:pz:E:M:mid:mpx:mpy:mpz:mE:mM:k:a0:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:a15:\
313s0:s1:s2:s3:s4:s5:s6:s7:s8:s9:s10:s11:s12:s13:s14:s15",
314)
315
316# make sure all particles for cascade production are stable
317for kf in idbeam:
318 kc = myPythia.Pycomp(kf)
319 myPythia.SetMDCY(kc, 1, 0)
320# make charm or beauty signal hadrons stable
321for kf in idsig:
322 kc = myPythia.Pycomp(kf)
323 myPythia.SetMDCY(kc, 1, 0)
324
325# Heterogeneous cascade-particle stack: each slot is replaced with a list
326# `[pid, px, py, pz, depth, history, ...]` once populated.
327stack: list[Any] = 1000 * [0]
328for iev in range(args.nevgen):
329 if iev % 1000 == 0:
330 print("Generate event ", iev)
331 nstack = 0
332 # put protons of energy pbeamh on the stack
333 # stack: PID, px, py, pz, cascade depth, nstack of mother
334 stack[nstack] = [2212, 0.0, 0.0, args.pbeamh, 1, 100 * [0], 100 * [0]]
335 stack[nstack][5][0] = 2212
336 while nstack >= 0:
337 # generate a signal based on probabilities in hists i*10+8?
338 ptot = ROOT.TMath.Sqrt(stack[nstack][1] ** 2 + stack[nstack][2] ** 2 + stack[nstack][3] ** 2)
339 prbsig = 0.0
340 idpn = 0
341 for i in range(1, id + 1):
342 if stack[nstack][0] == idhist[i]: # get hist id for this beam particle
343 idpn = 0
344 if random.random() > fracp: # decide on p or n target
345 idpn = 1
346 idw = i * 10 + idpn * 4 + 4
347 ib = h[str(idw)].FindBin(ptot, 0.0, 0.0)
348 prbsig = h[str(idw)].GetBinContent(ib)
349 if prbsig > random.random():
350 # last particle on the stack as beam particle
351 for k in range(1, 4):
352 myPythia.SetP(1, k, stack[nstack][k])
353 myPythia.SetP(2, k, 0.0)
354 # new particle/momentum, init again: signal run.
355 myPythia.SetMSEL(args.mselcb) # set forced ccbar or bbbar generation
356 _beam = ut.get_particle(stack[nstack][0])
357 myPythia.Initialize("3MOM", _beam.GetName(), target[idpn], 0.0)
358 myPythia.GenerateEvent()
359 # look for the signal particles
360 charmFound = []
361 for itrk in range(1, myPythia.GetN() + 1):
362 idabs = ROOT.TMath.Abs(myPythia.GetK(itrk, 2))
363 if idabs in idsig: # if signal is found, store in ntuple
364 vl = array("f")
365 vl.append(float(myPythia.GetK(itrk, 2)))
366 for i in range(1, 6):
367 vl.append(float(myPythia.GetP(itrk, i)))
368 vl.append(float(myPythia.GetK(1, 2)))
369 for i in range(1, 6):
370 vl.append(float(myPythia.GetP(1, i)))
371 vl.append(float(stack[nstack][4]))
372 for i in range(16):
373 vl.append(float(stack[nstack][5][i]))
374 nsub = stack[nstack][4] - 1
375 if nsub > 15:
376 nsub = 15
377 for i in range(nsub):
378 vl.append(float(stack[nstack][6][i]))
379 vl.append(float(myPythia.GetMSTI(1)))
380 for i in range(nsub + 1, 16):
381 vl.append(float(0))
382 Ntup.Fill(vl)
383 charmFound.append(itrk)
384 h["1"].Fill(myPythia.GetP(itrk, 4))
385 h["2"].Fill(stack[nstack][4])
386 if idabs == 421 and stack[nstack][4] == 1:
387 # some checking hist to monitor pt**2, XF of prompt D^0
388 pt2 = myPythia.GetP(itrk, 1) ** 2 + myPythia.GetP(itrk, 2) ** 2
389 h["3"].Fill(pt2)
390 h["4"].Fill(pt2)
391 h["5"].Fill(ROOT.TMath.Sqrt(pt2))
392 # boost to Cm frame for XF ccalculation of D^0
393 beta = args.pbeamh / (myPythia.GetP(1, 4) + myPythia.GetP(2, 5))
394 gamma = (1 - beta**2) ** (-0.5)
395 pbcm = -gamma * beta * myPythia.GetP(1, 4) + gamma * myPythia.GetP(1, 3)
396 pDcm = -gamma * beta * myPythia.GetP(itrk, 4) + gamma * myPythia.GetP(itrk, 3)
397 xf = pDcm / pbcm
398 h["6"].Fill(xf)
399 if len(charmFound) > 0 and args.storePrimaries:
400 for itP in range(1, myPythia.GetN() + 1):
401 if itP in charmFound:
402 continue
403 if myPythia.GetK(itP, 1) == 1:
404 # store only undecayed particle and no charm found
405 # ***WARNING****: with new with new ancestor and process info (a0-15, s0-15) add to ntuple, might not work???
406 Ntup.Fill(
407 float(myPythia.GetK(itP, 2)),
408 float(myPythia.GetP(itP, 1)),
409 float(myPythia.GetP(itP, 2)),
410 float(myPythia.GetP(itP, 3)),
411 float(myPythia.GetP(itP, 4)),
412 float(myPythia.GetP(itP, 5)),
413 -1,
414 float(myPythia.GetV(itP, 1) - myPythia.GetV(charmFound[0], 1)),
415 float(myPythia.GetV(itP, 2) - myPythia.GetV(charmFound[0], 2)),
416 float(myPythia.GetV(itP, 3) - myPythia.GetV(charmFound[0], 3)),
417 0,
418 0,
419 stack[nstack][4],
420 )
421
422 # now generate msel=2 to add new cascade particles to the stack
423 for k in range(1, 4):
424 myPythia.SetP(1, k, stack[nstack][k])
425 myPythia.SetP(2, k, 0.0)
426 # new particle/momentum, init again, generate total cross-section event
427 myPythia.SetMSEL(2) # mbias event
428 idpn = 0
429 if random.random() > fracp:
430 idpn = 1
431 _beam = ut.get_particle(stack[nstack][0])
432 myPythia.Initialize("3MOM", _beam.GetName(), target[idpn], 0.0)
433 myPythia.GenerateEvent()
434 # remove used particle from the stack, before adding new
435 # first store its history: cascade depth and ancestors-list
436 icas = stack[nstack][4] + 1
437 if icas > 98:
438 icas = 98
439 anclist = copy.copy(stack[nstack][5])
440 sublist = copy.copy(stack[nstack][6])
441 # fill in interaction process of first proton
442 if nstack == 0:
443 sublist[0] = myPythia.GetMSTI(1)
444 nstack = nstack - 1
445 for itrk in range(1, myPythia.GetN() + 1):
446 if myPythia.GetK(itrk, 1) == 1:
447 ptot = ROOT.TMath.Sqrt(
448 myPythia.GetP(itrk, 1) ** 2 + myPythia.GetP(itrk, 2) ** 2 + myPythia.GetP(itrk, 3) ** 2
449 )
450 if ptot > pbeaml:
451 # produced particle is stable and has enough momentum, is it in the wanted list?
452 for isig in range(len(idbeam)):
453 if ROOT.TMath.Abs(myPythia.GetK(itrk, 2)) == idbeam[isig] and nstack < 999:
454 if nstack < 999:
455 nstack += 1
456 # update ancestor list
457 tmp = copy.copy(anclist)
458 tmp[icas - 1] = myPythia.GetK(itrk, 2)
459 stmp = copy.copy(sublist)
460 # Pythia interaction process identifier
461 stmp[icas - 1] = myPythia.GetMSTI(1)
462 stack[nstack] = [
463 myPythia.GetK(itrk, 2),
464 myPythia.GetP(itrk, 1),
465 myPythia.GetP(itrk, 2),
466 myPythia.GetP(itrk, 3),
467 icas,
468 tmp,
469 stmp,
470 ]
471
472print("Now at Ntup.Write()")
473Ntup.Write()
474for akey in h:
475 h[akey].Write()
476ftup.Close()
477
478timer.Stop()
479rtime = timer.RealTime()
480ctime = timer.CpuTime()
481print(" ")
482print("Macro finished successfully.")
483print(f"Output file is {ftup.GetName()}")
484print(f"Real time {rtime} s, CPU time {ctime} s")
None fillp1(hist)
None PoorE791_tune(P6)
None LHCb_tune(P6)