FairShip
Loading...
Searching...
No Matches
extractMuonsAndUpdateWeight.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 os
5
6import ROOT
7
8path = "/eos/experiment/ship/data/Mbias/background-prod-2018/"
9
10# functions, should extract events with muons, update weight based on process/decay and PoT
11
12muSources = {"eta": 221, "omega": 223, "phi": 333, "rho0": 113, "eta_prime": 331}
13charmExtern = [4332, 4232, 4132, 4232, 4122, 431, 411, 421]
14
15# for 10GeV Yandex Production 65.041 Billion PoT, weight = 768.75 for 5E13 pot
16weightMbias = 768.75
17
18# for 10GeV charm Production 102.2 Billion PoT equivalent, weight = 489.24
19# added another cycle
20weightCharm = 489.24 * 2.0 / 3.0
21
22# for 10GeV charm Production 5336 Billion PoT equivalent, weight = 9.37
23weightBeauty = 9.37
24
25# Active weight, set by the per-source entry points (Mbias/Charm/Beauty)
26# before they call muonUpdateWeight.
27weight: float = weightMbias
28
29
30def muonUpdateWeight(sTree, diMuboost: float, xSecboost: float, noCharm=True) -> int:
31 nMu = 0
32 for v in sTree.vetoPoint:
33 mu = v.GetTrackID()
34 t = sTree.MCTrack[mu]
35 if abs(t.GetPdgCode()) != 13:
36 continue
37 moID = abs(sTree.MCTrack[t.GetMotherId()].GetPdgCode())
38 if moID in charmExtern and noCharm:
39 continue # take heavy flavours from separate production
40 nMu += 1
41 pName = t.GetProcName().Data()
42 t.SetWeight(weight)
43 if not pName.find("Hadronic inelastic") < 0:
44 t.MultiplyWeight(1.0 / diMuboost)
45 elif not pName.find("Lepton pair") < 0 or not pName.find("Positron annihilation") < 0:
46 t.MultiplyWeight(1.0 / xSecboost)
47 elif not pName.find("Primary particle") < 0 or not pName.find("Decay") < 0:
48 if moID in muSources.values():
49 t.MultiplyWeight(1.0 / diMuboost)
50 return nMu
51
52
53def PoT(f) -> tuple[float | int, float, float]:
54 nTot = 0
55 # POT = 1000000000 with ecut=10.0 diMu100.0 X100.0
56 diMuboost = 0.0
57 xSecboost = 0.0
58 ncycles = 0
59 for k in f.GetListOfKeys():
60 if k.GetName() == "FileHeader":
61 txt = k.GetTitle()
62 tmp = txt.split("=")[1]
63 tmp2 = tmp.split("with")[0]
64 if tmp2.find("E") < 0:
65 nTot += int(tmp2)
66 else:
67 nTot += float(tmp2)
68 ncycles += 1
69 i = txt.find("diMu")
70 if i < 0:
71 diMuboost += 1.0
72 else:
73 diMuboost += float(txt[i + 4 :].split(" ")[0])
74 i = txt.find("X")
75 if i < 0:
76 xSecboost += 1.0
77 else:
78 xSecboost += float(txt[i + 1 :].split(" ")[0])
79 diMuboost = diMuboost / float(ncycles)
80 xSecboost = xSecboost / float(ncycles)
81 print(
82 "POT = ",
83 nTot,
84 " number of events:",
85 f.Get("cbmsim").GetEntries(),
86 " diMuboost=",
87 diMuboost,
88 " XsecBoost=",
89 xSecboost,
90 )
91 return nTot, diMuboost, xSecboost
92
93
94def TotStat() -> None:
95 lfiles = os.listdir(path)
96 ntot = 0
97 for fn in lfiles:
98 f = ROOT.TFile(path + fn)
99 nPot, _diMuboost, _xSecboost = PoT(f)
100 ntot += nPot
101 print("Total statistics so far", ntot / 1.0e9, " billion")
102
103
104def processFile(fin: str, noCharm: bool = True, process_muons_only: bool = False) -> int:
105 f = ROOT.TFile.Open(os.environ["EOSSHIP"] + path + fin)
106 nPot, diMuboost, xSecboost = PoT(f)
107 sTree = f.Get("cbmsim")
108 outFile = fin.replace(".root", "_mu.root")
109 fmu = ROOT.TFile(outFile, "recreate")
110 newTree = sTree.CloneTree(0)
111 for n in range(sTree.GetEntries()):
112 sTree.GetEntry(n)
113 nMu = muonUpdateWeight(sTree, diMuboost, xSecboost, noCharm)
114 if nMu > 0 or not process_muons_only:
115 newTree.Fill()
116 ff = f.FileHeader.Clone("Extracted Muon Background File")
117 txt = ff.GetTitle()
118 tmp = txt.split("=")[1]
119 newTxt = txt.replace(tmp.split("with")[0].replace(" ", ""), str(nPot))
120 ff.SetTitle(newTxt)
121 fmu.cd()
122 ff.Write("FileHeader", ROOT.TObject.kSingleKey)
123 newTree.AutoSave()
124 fmu.Close()
125 return 0
126
127
128def run() -> None:
129 tmp = "pythia8_Geant4_10.0_cXX.root"
130 global weight
131 weight = weightMbias
132 for run in range(0, 67000, 1000):
133 rc = processFile(tmp.replace("XX", str(run)))
134 if rc == 0:
135 fmu = tmp.replace("XX", str(run) + "_mu")
136 rc = os.system("xrdcp " + fmu + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + fmu)
137 if rc != 0:
138 print("copy to EOS failed, stop", fmu)
139 else:
140 rc = os.system("rm " + fmu)
141
142
143def run4Charm() -> None:
144 tmp = "pythia8_Geant4_charm_XX-YY_10.0.root"
145 global weight
146 weight = weightCharm
147 for cycle in [0, 1, 2]:
148 for run in range(0, 100, 20):
149 crun = run + cycle * 1000
150 fname = tmp.replace("XX", str(crun)).replace("YY", str(crun + 19))
151 rc = processFile(fname, False)
152 if rc == 0:
153 fmu = fname.replace(".root", "_mu.root")
154 rc = os.system("xrdcp " + fmu + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + fmu)
155 if rc != 0:
156 print("copy to EOS failed, stop", fmu)
157 else:
158 rc = os.system("rm " + fmu)
159
160
161def run4beauty() -> None:
162 global weight
163 weight = weightBeauty
164 fname = "pythia8_Geant4_beauty_5336B_10.0.root"
165 rc = processFile(fname, False)
166 if rc == 0:
167 fmu = fname.replace(".root", "_mu.root")
168 rc = os.system("xrdcp " + fmu + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + fmu)
169 if rc != 0:
170 print("copy to EOS failed, stop", fmu)
171 else:
172 rc = os.system("rm " + fmu)
173
174
175# merge with beauty in a second step
176
177
178# finished one file pythia8_Geant4_10.0_withCharm44000_mu.root 2712798 1113638
179
180
181def mergeCharm() -> None:
182 tmp = "pythia8_Geant4_charm_XX-YY_10.0.root"
183 mergedFile = "pythia8_Geant4_charm_102.2B_10.0_mu.root"
184 cmd = "hadd " + mergedFile
185 for cycle in [0, 1]:
186 for run in range(0, 100, 20):
187 crun = run + cycle * 1000
188 fname = tmp.replace("XX", str(crun)).replace("YY", str(crun + 19))
189 fmu = " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + fname.replace(".root", "_mu.root")
190 cmd += fmu
191 os.system(cmd)
192 os.system("xrdcp " + mergedFile + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + mergedFile)
193
194
195def mergeMbiasAndCharm(flavour: str = "charm") -> None:
196 done = []
197 timer = ROOT.TStopwatch()
198 timer.Start()
199 pp = os.environ["EOSSHIP"] + path
200 Rndm = ROOT.TRandom3()
201 Rndm.SetSeed(0)
202 if flavour == "charm":
203 allFiles = {"charm": "pythia8_Geant4_charm_102.2B_10.0_mu.root"}
204 tmp = "pythia8_Geant4_10.0_cXX_mu.root"
205 else:
206 allFiles = {"beauty": "pythia8_Geant4_beauty_5336B_10.0_mu.root"}
207 tmp = "pythia8_Geant4_10.0_withCharmXX_mu.root"
208 for run in range(0, 67000, 1000):
209 allFiles[str(run)] = tmp.replace("XX", str(run))
210 nEntries = {}
211 Nall = 0
212 for x in allFiles:
213 f = ROOT.TFile.Open(pp + allFiles[x])
214 nEntries[x] = f.Get("cbmsim").GetEntries()
215 Nall += nEntries[x]
216 nCharm = 0
217 frac = nEntries[flavour] / float(Nall)
218 print("debug", frac)
219 os.system("xrdcp " + pp + allFiles[flavour] + " " + allFiles[flavour])
220 for k in allFiles:
221 if k == flavour:
222 continue
223 if k in done:
224 continue
225 os.system("xrdcp " + pp + allFiles[k] + " " + allFiles[k])
226 os.system("hadd -f tmp.root " + allFiles[flavour] + " " + allFiles[k])
227 os.system("rm " + allFiles[k])
228 f = ROOT.TFile("tmp.root")
229 sTree = f.Get("cbmsim")
230 sTree.LoadBaskets(30000000000)
231 if flavour == "charm":
232 outFile = tmp.replace("cXX", "withCharm" + k)
233 else:
234 outFile = tmp.replace("XX", "andBeauty" + k)
235 fmu = ROOT.TFile(outFile, "recreate")
236 newTree = sTree.CloneTree(0)
237 nMbias = 0
238 # 0 - nEntries['charm']-1 , nEntries['charm'] - nEntries[0]-1, nEntries[0] - nEntries[1000]-1
239 # randomList = ROOT.TEntryList(chain)
240 myList = []
241 while nMbias < nEntries[k]:
242 if Rndm.Rndm() > frac:
243 # rc = randomList.Enter(nMbias+nEntries['charm'])
244 myList.append(nMbias + nEntries[flavour])
245 nMbias += 1
246 else:
247 if nEntries[flavour] > nCharm:
248 # rc = randomList.Enter(nCharm)
249 myList.append(nCharm)
250 nCharm += 1
251 else:
252 pass
253 # chain.SetEntryList(randomList)
254 # nev = randomList.GetN()
255 nev = len(myList)
256 print("start:", outFile, nev)
257 for iev in range(nev):
258 rc = sTree.GetEntry(myList[iev])
259 rc = newTree.Fill()
260 if (iev) % 100000 == 0:
261 timer.Stop()
262 print("status:", timer.RealTime(), k, iev)
263 timer.Start()
264 newTree.AutoSave()
265 print("finished one file", outFile, nMbias, nCharm)
266 if flavour == "charm":
267 ff = f.FileHeader.Clone("With Charm Merged Muon Background File")
268 else:
269 ff = f.FileHeader.Clone("With Charm and Beauty Merged Muon Background File")
270 ff.GetTitle()
271 fmu.cd()
272 ff.Write("FileHeader", ROOT.TObject.kSingleKey)
273 fmu.Close()
274 f.Close()
275 rc = os.system("xrdcp " + outFile + " $EOSSHIP/eos/experiment/ship/data/Mbias/background-prod-2018/" + outFile)
276 if rc != 0:
277 print("copy to EOS failed", outFile)
278 else:
279 rc = os.system("rm " + outFile)
280
281
282def testRatio(fname) -> None:
283 f = ROOT.TFile.Open(os.environ["EOSSHIP"] + path + fname)
284 sTree = f.Get("cbmsim")
285 Nall = sTree.GetEntries()
286 charm = 0
287 for n in range(Nall):
288 sTree.GetEvent(n)
289 for m in sTree.MCTrack:
290 pdgID = abs(m.GetPdgCode())
291 if pdgID in charmExtern:
292 charm += 1
293 break
294 print("charm found", charm, " ratio ", charm / float(Nall))
int muonUpdateWeight(sTree, float diMuboost, float xSecboost, noCharm=True)
tuple[float|int, float, float] PoT(f)
None mergeMbiasAndCharm(str flavour="charm")
int processFile(str fin, bool noCharm=True, bool process_muons_only=False)