FairShip
Loading...
Searching...
No Matches
ana_ShipMuon.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
4# analyze muon background /media/Data/HNL/PythiaGeant4Production/pythia8_Geant4_total.root
5import multiprocessing as mp
6import os
7from io import TextIOWrapper
8
9import ROOT
10from ShipGeoConfig import load_from_root_file
11
12ROOT.gInterpreter.ProcessLine("typedef double Double32_t")
13local = False
14if not os.uname()[1].lower().find("ubuntu") < 0:
15 local = True
16
17parallel = True
18if parallel:
19 # Define an output queue
20 output = mp.Queue()
21# Process objects when parallel, plain filenames otherwise
22processes: list[mp.Process | str] = []
23
24
25# 11-19 with QGSP_BERT_EMV instead of QGSP_BERT_HP_PEN
26# 51-59 passive shielding
27# 41-49 fixed field horizontal
28# 61-69 chamber with vacuum
29# 71-79 without field in the wings
30# 81-89 add shielding
31# 91-99 switch off muBrems, muPair
32# 101-109 vacuum tube as cone, Al->Steel
33
34# prefix = 'muon4' # default
35# prefix = 'muon6' # Al -> vacuum
36# prefix = 'muon7' # no field in wings
37# prefix = 'muon8' # entry window + additional shielding
38# prefix = 'muon9' # switch off muBrems, muPair
39# prefix = 'muon10' # vacuum tube as cone, Al->Steel
40# prefix = 'muon14' # vacuum tube as cone, Al->Steel, slightly smaller lead shield
41# prefix = 'muon12' # switch off muIoni
42# prefix = 'muon13' # switch off muBrems, muPair AND muIoni
43# prefix = 'muon15' # vacuum tube as cone, Al->Steel, cave with air
44# prefix = 'muon 161-169 new geometry
45# prefix = 'muon 251-259 passive shielding with concrete walls
46# prefix = 'muon 171-179 new increased Bdl, 2.5m clearance from start, 9m space for tau
47# 181-189 narrow tunnel around first magnet, add 2m hadron absorber, fixed problem with B-field -> G4
48# 191-199 narrow tunnel bug fix, also bug fix for top/bottom, now with tungsten core in add absorber
49# 201-209 test with reduced field, 1.5T
50# 211-219 many bug fixes, overlaps, added Goliath magnet
51# 221-229 bug fix for Goliath
52# 231-239 reduce field to 1T
53# 311-314 change numbering of veto volumes
54# 321-324 1 Teslas
55# 331-339 added TauSensitive, fixed C1, using muons from Yandex
56# 341-349 should be the same as 331-339
57# 361-364 4m high magnets!
58# 371-374 new strawpoints
59# 381-389 yandex file, overwrite with magC1 fixed
60# 391-399 change to dY = 2m
61# 401-409 change to dY = 2m Yandex
62# 411-419 back to dY = 4m, add sensitive plance downstream det2
63# 421-429 reduce size of vacuum tank before veto station, add pdgcode for muonPoint, move det2 closer
64# 431-439 reduce size of vacuum tank before veto station, add pdgcode for muonPoint, move det2 closer Yandex
65# 441-449 try with increased tau mu detector, and reduced height of active muon shield, dy=1m
66# 451-459 try with increased tau mu detector, and reduced height of active muon shield, dy=1m Yandex
67# 461-469 dy=4m and then 1m, RPC fixed, display on
68# 471-479 dy=4m and then 1m, RPC fixed, Yandex
69# 481-489 dy=4m and then 1m, RPC fixed, display OFF
70# 491-499 back to dy=1m display on
71# 551-554 ultimate slim design
72# 561-564 fixing overlaps hcal and almost overlaps in magnets
73# 571-574 more undetected overlaps fixed
74# 581-584 test with replacing tungsten core with iron, 10m height
75# 591-599 test with replacing tungsten core with iron, 6m height, display
76# 601-609 replacing tungsten core with iron, 6m height, Yandex data, display
77# 610-619 replacing tungsten core with iron, 10m height, display
78# 620-629 replacing tungsten core with iron, 10m height, Yandex data, display
79# 630-639 10m height, change RPC width 4.5->3.6m
80# 640-649 10m height, change RPC width 4.5->3.6m Yandex
81# 650-669 6m height, change RPC width 4.5->3.6m
82# 660-669 6m height, change RPC width 4.5->3.6m Yandex
83# makeProd("muon700",10,False,False) # switch off field of active shielding # prefix,DY,y=False,phiRandom=False,X=None
84# makeProd("muon710",10,False,False) # start production with beam smeared on r=3cm disk
85# makeProd("muon720",10,True,False)
86# makeProd("muon711",10,False,True) # start production with beam smeared on r=3cm disk
87# makeProd("muon721",10,True,True)
88# makeProd("muon712",10,False,True) # start production with beam smeared on r=3cm disk
89# makeProd("muon722",10,True,True)
90# makeProd("muon713",10,False,True) # start production with beam smeared on r=3cm disk
91# makeProd("muon723",10,True,True)
92# makeProd("muon714",10,False,True) # start production with beam smeared on r=3cm disk
93# makeProd("muon724",10,True,True)
94# makeProd("muon715",10,False,True) # start production with beam smeared on r=3cm disk
95# makeProd("muon725",10,True,True)
96# makeProd("muon716",10,False,True) # start production with beam smeared on r=3cm disk
97# makeProd("muon726",10,True,True)
98# makeProd("muon717",10,False,True) # start production with beam smeared on r=3cm disk
99# makeProd("muon777",10,False,True) # in case the other one does not work 717
100# makeProd("muon727",10,True,True) # ?
101# makeProd("muon718",10,False,True) # start production with beam smeared on r=3cm disk
102# makeProd("muon728",10,True,True)
103# makeProd("muon719",10,False,True) # start production with beam smeared on r=3cm disk
104# makeProd("muon729",10,True,True)
105# makeProd("muon730",10,'Jpsi',False)
106# makeProd("muon731",10,'Jpsi',True)
107# makeProd("muon732",10,'Jpsi',True)
108# makeProd("muon733",10,'Jpsi',True) # back to pencil beam
109# makeProd("muon630",10,False,True) # test with new muonShield code, 3cm smearing
110# makeProd("muon631",10,False,True) # run with concrete wall enabled as sensitive
111# makeProd("muon632",10,False,True) # run with concrete wall enabled as sensitive, active shielding polarity fixed
112# but wrong geometry
113# makeProd("muon810",10,False,False) # start production with latest geometry
114# makeProd("muon820",10,True,False)
115# makeProd("muon811",10,False,True) #
116# makeProd("muon821",10,True,True)
117
124
125# makeProd("muon814",10,False,True) #
126# makeProd("muon824",10,True,True)
127# makeProd("muon815",10,False,True)
128# makeProd("muon825",10,True,True)
129# makeProd("muon816",10,False,True)
130# makeProd("muon826",10,True,True)
131# makeProd("muon817",10,False,True)
132# makeProd("muon827",10,True,True)
133# makeProd("muon818",10,False,True)
134# makeProd("muon828",10,True,True)
135# makeProd("muon819",10,False,True)
136# makeProd("muon829",10,True,True)
137# makeProd("muon910",10,False,True)
138# makeProd("muon920",10,True,True)
139# makeProd("muon911",10,False,True)
140# makeProd("muon921",10,True,True)
141
142# makeProd("muon912",10,False,True)
143# makeProd("muon922",10,True,True)
144
145# makeProd("muon913",10,False,True)
146# makeProd("muon923",10,True,True)
147# makeProd("muon914",10,False,True)
148# makeProd("muon924",10,True,True)
149# makeProd("muon915",10,False,True)
150# makeProd("muon925",10,True,True)
151# makeProd("muon916",10,False,True)
152# makeProd("muon926",10,True,True)
153# makeProd("muon917",10,False,True)
154# makeProd("muon927",10,True,True)
155# makeProd("muon927",10,True,True,8)
156# makeProd("muon918",10,False,True)
157# makeProd("muon928",10,True,True)
158# makeProd("muon919",10,False,True)
159# makeProd("muon929",10,True,True)
160# makeProd("muon1019",10,False,True)
161# makeProd("muon1029",10,True,True)
162# makeProd("muon1018",10,False,True)
163# makeProd("muon1028",10,True,True)
164# makeProd("muon1017",10,False,True)
165# makeProd("muon1027",10,True,True)
166# makeProd("muon1016",10,False,True)
167# makeProd("muon1026",10,True,True)
168# makeProd("muon1015",10,False,True)
169# makeProd("muon1025",10,True,True)
170# makeProd("muon1014",10,False,True)
171# makeProd("muon1024",10,True,True)
172# makeProd("muon1013",10,False,True)
173# makeProd("muon1023",10,True,True)
174# makeProd("muon1012",10,False,True)
175# makeProd("muon1022",10,True,True)
176# makeProd("muon633",10,'concrete',False) # run with concrete wall enabled as sensitive
177# makeProd("muon1111",10,'False',False) # try iron for first shield
178# makeProd("muon1121",10,'True',False) # try iron for first shield
179# makeProd("muon1112",10,'False',True) # try iron for first shield
180# makeProd("muon1122",10,'True',True) # try iron for first shield
181# restart with also rockS sensitive and &&->||
182# makeProd("muon634",10,'concrete',False) # run with concrete wall enabled as sensitive, and active shield too
183# makeProd("muon635",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
184# makeProd("muon636",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
185# makeProd("muon637",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
186# makeProd("muon638",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
187# makeProd("muon639",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
188# makeProd("muon640",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
189# makeProd("muon641",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
190# makeProd("muon642",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
191# makeProd("muon643",10,'concrete',True) # run with concrete wall enabled as sensitive, and active shield too
192# makeProd("muon650",10,'concrete',False) # run with concrete wall enabled as sensitive, first tunnel 10m wide
193# makeProd("muon651",10,'concrete',False) # run with concrete wall enabled as sensitive, first tunnel 10m wide
194# makeProd("muon652",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide
195# makeProd("muon653",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide
196# makeProd("muon654",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide
197# makeProd("muon655",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide
198# makeProd("muon656",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide
199# makeProd("muon657",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide
200# makeProd("muon658",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide
201# makeProd("muon659",10,'concrete',True) # run with concrete wall enabled as sensitive, first tunnel 10m wide
202# makeProd("muon660",10,'concrete',False) # liter magnet
203# makeProd("muon661",10,'concrete',True) # liter magnet
204# makeProd("muon662",10,'concrete',True) # liter magnet
205# makeProd("muon663",10,'concrete',True) # liter magnet
206# makeProd("muon664",10,'concrete',True) # liter magnet
207# makeProd("muon665",10,'concrete',True) # liter magnet
208# makeProd("muon666",10,'concrete',True) # liter magnet
209# makeProd("muon667",10,'concrete',True) # liter magnet
210# makeProd("muon668",10,'concrete',True) # liter magnet
211# makeProd("muon669",10,'concrete',True) # liter magnet
212# makeProd("muon670",10,'concrete',False) # even liter magnet
213# makeProd("muon671",10,'concrete',True) # even liter magnet
214# makeProd("muon672",10,'concrete',True) # even liter magnet
215# makeProd("muon673",10,'concrete',True) # even liter magnet
216# makeProd("muon674",10,'concrete',True) # even liter magnet
217# makeProd("muon675",10,'concrete',True) # even liter magnet
218# makeProd("muon676",10,'concrete',True) # even liter magnet
219# makeProd("muon677",10,'concrete',True) # even liter magnet
220# makeProd("muon678",10,'concrete',True) # even liter magnet
221# makeProd("muon679",10,'concrete',True) # even liter magnet
222# new attempt, previous did not worked out
223# makeProd("muon680",10,'concrete',False) # even liter magnet
224# makeProd("muon681",10,'concrete',True) # even liter magnet
225# makeProd("muon682",10,'concrete',True) # even liter magnet
226# makeProd("muon683",10,'concrete',True) # even liter magnet
227# makeProd("muon684",10,'concrete',True) # even liter magnet
228# makeProd("muon685",10,'concrete',True) # even liter magnet
229# makeProd("muon686",10,'concrete',True) # even liter magnet
230# makeProd("muon687",10,'concrete',True) # even liter magnet
231# makeProd("muon688",10,'concrete',True) # even liter magnet
232# makeProd("muon689",10,'concrete',True) # even liter magnet
233# new attempt, increase height of first magnet, previous did not worked out either
234# makeProd("muon690",10,'concrete',False) # even liter magnet
235# makeProd("muon691",10,'concrete',True) # even liter magnet
236# makeProd("muon692",10,'concrete',True) # even liter magnet
237# makeProd("muon693",10,'concrete',True) # even liter magnet
238# makeProd("muon694",10,'concrete',True) # even liter magnet
239# makeProd("muon695",10,'concrete',True) # even liter magnet
240# makeProd("muon696",10,'concrete',True) # even liter magnet
241# makeProd("muon697",10,'concrete',True) # even liter magnet
242# makeProd("muon698",10,'concrete',True) # even liter magnet
243# makeProd("muon699",10,'concrete',True) # even liter magnet
244# testing height 4m->2m
245# makeProd("muon700",10,'concrete',False) # even liter magnet
246# makeProd("muon701",10,'concrete',True) # even liter magnet
247# makeProd("muon702",10,'concrete',True) # even liter magnet
248# makeProd("muon703",10,'concrete',True) # even liter magnet
249# makeProd("muon704",10,'concrete',True) # even liter magnet
250# makeProd("muon705",10,'concrete',True) # even liter magnet
251# makeProd("muon706",10,'concrete',True) # even liter magnet
252# makeProd("muon707",10,'concrete',True) # even liter magnet
253# makeProd("muon708",10,'concrete',True) # even liter magnet
254# makeProd("muon709",10,'concrete',True) # even liter magnet
255# testing height 4m->2m + new magnets
256# makeProd("muon800",10,'concrete',False) # even liter magnet
257# makeProd("muon801",10,'concrete',True) # even liter magnet
258# makeProd("muon802",10,'concrete',True) # even liter magnet
259# makeProd("muon803",10,'concrete',True) # even liter magnet
260# makeProd("muon804",10,'concrete',True) # even liter magnet
261# makeProd("muon805",10,'concrete',True) # even liter magnet
262# makeProd("muon806",10,'concrete',True) # even liter magnet
263# makeProd("muon807",10,'concrete',True) # even liter magnet
264# makeProd("muon808",10,'concrete',True) # even liter magnet
265# makeProd("muon809",10,'concrete',True) # even liter magnet
266# new iteration, and ship_geo.Yheight*1./10.
267# makeProd("muon710",10,'concrete',False) # even liter magnet
268# makeProd("muon711",10,'concrete',True) # even liter magnet
269# makeProd("muon712",10,'concrete',True) # even liter magnet
270# makeProd("muon713",10,'concrete',True) # even liter magnet
271# makeProd("muon714",10,'concrete',True) # even liter magnet
272# makeProd("muon715",10,'concrete',True) # even liter magnet
273# makeProd("muon716",10,'concrete',True) # even liter magnet
274# makeProd("muon717",10,'concrete',True) # even liter magnet
275# makeProd("muon718",10,'concrete',True) # even liter magnet
276# makeProd("muon719",10,'concrete',True) # even liter magnet
277# new iteration, and back to ship_geo.Yheight*2./10.
278# makeProd("muon720",10,'concrete',False) # even liter magnet
279# makeProd("muon721",10,'concrete',True) # even liter magnet
280# makeProd("muon722",10,'concrete',True) # even liter magnet
281# makeProd("muon723",10,'concrete',True) # even liter magnet
282# makeProd("muon724",10,'concrete',True) # even liter magnet
283# makeProd("muon725",10,'concrete',True) # even liter magnet
284# makeProd("muon726",10,'concrete',True) # even liter magnet
285# makeProd("muon727",10,'concrete',True) # even liter magnet
286# makeProd("muon728",10,'concrete',True) # even liter magnet
287# makeProd("muon729",10,'concrete',True) # even liter magnet
288# new iteration, and back to ship_geo.Yheight*2./10. but with more info in vetoPoint
289# makeProd("muon730",10,'concrete',False) # even liter magnet
290# makeProd("muon740",10,'concrete',False) # even liter magnet
291# new iteration, ship_geo.Yheight*1./10.
292# makeProd("muon750",10,'concrete',False) #
293# new iteration, ship_geo.Yheight*1.5/10.
294# makeProd("muon760",10,'concrete',False) #
295# makeProd("muon761",10,'concrete',True) #
296# as before but now with full simulation
297# makeProd("muon1710",10,False,False)
298# makeProd("muon1720",10,True,False)
299# makeProd("muon1711",10,False,True)
300# makeProd("muon1721",10,True,True)
301# makeProd("muon1712",10,False,True)
302# makeProd("muon1722",10,True,True)
303# makeProd("muon1713",10,False,True)
304# makeProd("muon1723",10,True,True)
305# makeProd("muon1714",10,False,True)
306# makeProd("muon1724",10,True,True)
307# makeProd("muon1715",10,False,True)
308# makeProd("muon1725",10,True,True)
309# makeProd("muon1716",10,False,True)
310# makeProd("muon1726",10,True,True)
311# another one, hopefully better
312# makeProd("muon1717",10,'concrete',False) #
313# another one, increasing height to 3m
314# makeProd("muon1718",10,'concrete',False) #
315
316prefixes = []
317withChain = 0
318pref = "muon"
319xx = os.path.abspath(".").lower()
320if not xx.find("neutrino") < 0:
321 pref = "neutrino"
322if not xx.find("vdis") < 0:
323 pref = "disV"
324elif not xx.find("clby") < 0:
325 pref = "disCLBY"
326elif not xx.find("dis") < 0:
327 pref = "dis"
328
329if len(os.sys.argv) > 1:
330 for i in range(1, len(os.sys.argv)):
331 for prefix in os.sys.argv[i].split(","):
332 if prefix.find(pref) < 0:
333 prefix = pref + prefix
334 prefixes.append(prefix)
335 withChain += 1
336else:
337 prefixes = [""]
338
339testdir = "."
340path = ""
341# if local: path = "/media/Data/HNL/muonBackground/"
342if prefixes[0] != "":
343 testdir = path + prefixes[0] + "1"
344# figure out which setup
345fgeo = None
346sGeo = None
347inputFile = None
348for f in os.listdir(testdir):
349 if not f.find("geofile_full") < 0:
350 fgeo = ROOT.TFile(testdir + "/" + f)
351 sGeo = fgeo.Get("FAIRGeom")
352 inputFile = f.replace("geofile_full", "ship")
353 break
354if fgeo is None or not sGeo or inputFile is None:
355 raise RuntimeError("No geofile_full found in " + testdir)
356# try to extract from input file name
357tmp = inputFile.split(".")
358try:
359 dy = float(tmp[1] + "." + tmp[2])
360except Exception:
361 dy = 10.0
362
363if not inputFile.find("_D.") < 0:
364 inputFile1 = inputFile.replace("_D.", ".")
365 inputFile2 = inputFile
366else:
367 inputFile1 = inputFile
368 inputFile2 = inputFile.replace(".root", "_D.root")
369
370import rootUtils as ut
371import shipunit as u
372
373PDG = ROOT.TDatabasePDG.Instance()
374import geometry_config
375
376# init geometry and mag. field
377if not fgeo.FindKey("ShipGeo"):
378 # old geofile, missing Shipgeo dictionary
379 # re-create geometry and mag. field
380 ShipGeo = geometry_config.create_config(Yheight=dy)
381else:
382 # new geofile, load Shipgeo dictionary written by run_simScript.py
383 ShipGeo = load_from_root_file(fgeo, "ShipGeo")
384
385# -----Create geometry----------------------------------------------
386import shipDet_conf
387
388run = ROOT.FairRunSim()
389modules = shipDet_conf.configure(run, ShipGeo)
390
391
392def origin(sTree, it):
393 """Return (r, z) of the ancestor track produced by the primary muon.
394
395 Returns the sentinel (-1.0, 0.0) if the mother chain does not end at the
396 primary muon (track 0).
397 """
398 at = sTree.MCTrack[it]
399 im = at.GetMotherId()
400 if im > 0:
401 return origin(sTree, im)
402 if im == 0:
403 return ROOT.TMath.Sqrt(at.GetStartX() ** 2 + at.GetStartY() ** 2), at.GetStartZ()
404 # does not come from muon
405 return -1.0, 0.0
406
407
408otherPhysList = False
409noField = False
410passive = False
411#
412top = sGeo.GetTopVolume()
413muon = top.GetNode("MuonDetector_1")
414mvol = muon.GetVolume()
415zmuon = muon.GetMatrix().GetTranslation()[2]
416totl = (zmuon + mvol.GetShape().GetDZ()) / u.m
417ztarget = -100.0
418
419fchain = []
420fchainRec = []
421# first time trying to read a chain of Fairship files, doesn't seem to work out of the box, try some tricks.
422testdir = "."
423if path != "":
424 testdir = path
425if withChain > 0:
426 for prefix in prefixes:
427 for i in range(1, 10):
428 if prefix + str(i) not in os.listdir(testdir):
429 continue
430 q1 = inputFile1 in os.listdir(path + prefix + str(i))
431 q2 = inputFile2 in os.listdir(path + prefix + str(i))
432 recFile1 = inputFile1.replace(".root", "_rec.root")
433 recFile2 = inputFile2.replace(".root", "_rec.root")
434 r1 = recFile1 in os.listdir(path + prefix + str(i))
435 r2 = recFile2 in os.listdir(path + prefix + str(i))
436 if q1 or r1:
437 inputFile = inputFile1
438 elif q2 or r2:
439 inputFile = inputFile2
440 else:
441 continue
442 fname = path + prefix + str(i) + "/" + inputFile
443 recFile = inputFile.replace(".root", "_rec.root")
444 if recFile not in os.listdir(path + prefix + str(i)):
445 fchain.append(fname)
446 continue
447 fname = path + prefix + str(i) + "/" + recFile
448 fchainRec.append(fname)
449 fchain.append(fname) # take rec file if exist
450else:
451 fchain.append(inputFile)
452 prefix = ""
453
454
455def makeProd() -> None:
456 ntot = 736406
457 ncpu = 4
458 n3 = int(ntot / ncpu)
459 cmd = "python $FAIRSHIP/macro/run_simScript.py --MuonBack -f $SHIPSOFT/data/pythia8_Geant4_onlyMuons.root " # --display"
460 ns = 0
461 prefix = "muon18"
462 for i in range(1, ncpu + 1):
463 d = prefix + str(i)
464 if d not in os.listdir("."):
465 os.system("mkdir " + d)
466 os.chdir("./" + prefix + "1")
467 for i in range(1, ncpu + 1):
468 if i == ncpu:
469 n3 = ntot - i * n3
470 os.system("cp $FAIRSHIP/macro/run_simScript.py .")
471 os.system(cmd + " -n " + str(n3) + " -i " + str(ns) + " > log &")
472 # print " -n "+str(n3)+" -i "+str(ns)
473 ns += n3
474 if i == ncpu:
475 break
476 os.chdir("../" + prefix + str(i + 1))
477
478
479def detMap():
480 sGeo = ROOT.gGeoManager
481 detList = {}
482 for v in sGeo.GetListOfVolumes():
483 nm = v.GetName()
484 i = sGeo.FindVolumeFast(nm).GetNumber()
485 detList[i] = nm
486 return detList
487
488
489def fitSingleGauss(x, ba=None, be=None) -> None:
490 name = "myGauss_" + x
491 myGauss = h[x].GetListOfFunctions().FindObject(name)
492 if not myGauss:
493 if not ba:
494 ba = h[x].GetBinCenter(1)
495 if not be:
496 be = h[x].GetBinCenter(h[x].GetNbinsX())
497 bw = h[x].GetBinWidth(1)
498 mean = h[x].GetMean()
499 sigma = h[x].GetRMS()
500 norm = h[x].GetEntries() * 0.3
501 myGauss = ROOT.TF1(name, "[0]*" + str(bw) + "/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]", 4)
502 myGauss.SetParameter(0, norm)
503 myGauss.SetParameter(1, mean)
504 myGauss.SetParameter(2, sigma)
505 myGauss.SetParameter(3, 1.0)
506 myGauss.SetParName(0, "Signal")
507 myGauss.SetParName(1, "Mean")
508 myGauss.SetParName(2, "Sigma")
509 h[x].Fit(myGauss, "", "", ba, be)
510
511
512h = {}
513histlist = {}
514txt = {}
515labels = {}
516logVols = detMap()
517
518
519def bookHist(detName) -> None:
520 for mu in ["", "_mu", "_muV0"]:
521 tag = detName + mu
522 if detName.find("LS") < 0:
523 ut.bookHist(h, tag, "x/y " + detName, 100, -3.0, 3.0, 100, -6.0, 6.0)
524 else:
525 ut.bookHist(h, tag, "z phi " + detName, 100, -50.0, 50.0, 100, -1.0, 1.0)
526 ut.bookHist(h, tag + "_E", "deposited energy MeV " + detName, 100, 0.0, 2.0)
527 ut.bookHist(h, tag + "_P", "particle mom GeV " + detName, 500, 0.0, 50.0)
528 ut.bookHist(h, tag + "_LP", "particle mom GeV " + detName, 100, 0.0, 1.0)
529 ut.bookHist(h, tag + "_OP", "original particle mom GeV " + detName, 400, 0.0, 400.0)
530 ut.bookHist(h, tag + "_id", "particle id " + detName, 5001, -2499.5, 2499.5)
531 ut.bookHist(h, tag + "_mul", "multiplicity of hits/tracks " + detName, 100, -0.5, 99.5)
532 ut.bookHist(h, tag + "_evmul", "multiplicity of hits/event " + detName, 100, -0.5, 9999.5)
533 ut.bookHist(h, tag + "_origin", "r vs z", 100, ztarget, totl, 100, 0.0, 12.0)
534 ut.bookHist(h, tag + "_originmu", "r vs z", 100, ztarget, totl, 100, 0.0, 12.0)
535
536
537ut.bookHist(h, "origin", "r vs z", 100, ztarget, totl, 100, 0.0, 15.0)
538ut.bookHist(h, "borigin", "r vs z", 100, ztarget, totl, 500, 0.0, 30.0)
539ut.bookHist(h, "porigin", "r vs z secondary", 100, ztarget, totl, 500, 0.0, 30.0)
540ut.bookHist(h, "mu-inter", "r vs z", 100, ztarget, totl, 50, 0.0, 3.0)
541ut.bookHist(h, "muonP", "muon momentum", 100, 0.0, 400.0)
542ut.bookHist(h, "weight", "muon weight", 1000, 1.0e3, 1.0e6)
543ut.bookHist(h, "delx13", "x diff first and last point, mu-", 100, -10.0, 10.0)
544ut.bookHist(h, "delx-13", "x diff first and last point, mu+", 100, -10.0, 10.0)
545ut.bookHist(h, "deltaElec", "energy of delta electrons", 100, 0.0, 10.0)
546ut.bookHist(h, "secondaries", "energy of delta electrons", 100, 0.0, 10.0)
547ut.bookHist(h, "prop_deltaElec", "energy of delta elec / muon energy", 100, 0.0, 1.0)
548ut.bookHist(h, "dummy", "", 10, 0.0, 1.0)
549ut.bookHist(h, "dE", "", 100, 0.0, 10.0, 100, 0.0, 10.0)
550h["dummy"].SetMaximum(10.0)
551
552histlistAll = {
553 1: "strawstation_5",
554 2: "strawstation_1",
555 3: "strawstation_4",
556 4: "Ecal",
557 5: "muondet",
558 6: "VetoTimeDet",
559 7: "T1LiSc",
560 8: "T2LiSc",
561 9: "T3LiSc",
562 10: "T5LiSc",
563 11: "ShipRpc",
564 12: "volHPT",
565 13: "Target",
566 14: "TimeDet",
567 15: "Det2",
568}
569hLiSc = {1: {}}
570for i in range(1, 7):
571 hLiSc[1][i] = "T1LiSc_" + str(i)
572hLiSc[2] = {}
573for i in range(1, 48):
574 hLiSc[2][i] = "T2LiSc_" + str(i)
575hLiSc[3] = {}
576for i in range(1, 3):
577 hLiSc[3][i] = "T3LiSc_" + str(i)
578hLiSc[5] = {}
579for i in range(1, 3):
580 hLiSc[5][i] = "T5LiSc_" + str(i)
581hMuon = {}
582for i in range(0, 4):
583 hMuon[i] = "muondet" + str(i)
584
585
586# start event loop
587mom = ROOT.TVector3()
588pos = ROOT.TVector3()
589
590
591def BigEventLoop() -> None:
592 pid = 1
593 for fn in fchain:
594 if os.path.islink(fn):
595 rfn = os.path.realpath(fn).split("eos")[1]
596 fn = ROOT.gSystem.Getenv("EOSSHIP") + "/eos/" + rfn
597 elif not os.path.isfile(fn):
598 raise RuntimeError("Don't know what to do with " + fn)
599 if parallel:
600 # process files parallel instead of sequential
601 processes.append(mp.Process(target=executeOneFile, args=(fn, output, pid)))
602 pid += 1
603 else:
604 processes.append(fn)
605 # Run processes
606 n = 0
607 for p in processes:
608 if isinstance(p, mp.Process):
609 p.start()
610 n += 1
611 else:
613 if parallel:
614 # Exit the completed processes
615 for p in processes:
616 if isinstance(p, mp.Process):
617 p.join()
618 # clean histos before reading in the new ones
619 for x in h:
620 h[x].Reset()
621 print("now, collect the output")
622 pid = 1
623 for p in processes:
624 ut.readHists(h, "tmpHists_" + str(pid) + ".root")
625 pid += 1
626 # compactify liquid scintillator
627 for mu in ["", "_mu", "_muV0"]:
628 for x in ["", "_E", "_P", "_LP", "_OP", "_id", "_mul", "_evmul", "_origin", "_originmu"]:
629 for k in [1, 2, 3, 5]:
630 first = True
631 for j in hLiSc[k]:
632 detName = hLiSc[k][j]
633 tag = detName + mu + x
634 newh = detName[0:2] + "LiSc" + mu + x
635 if tag not in h:
636 continue
637 if first:
638 h[newh] = h[tag].Clone(newh)
639 h[newh].SetTitle(h[tag].GetTitle().split("_")[0])
640 first = False
641 else:
642 h[newh].Add(h[tag])
643 # compactify muon stations
644 for mu in ["", "_mu", "_muV0"]:
645 for x in ["", "_E", "_P", "_LP", "_OP", "_id", "_mul", "_evmul", "_origin", "_originmu"]:
646 first = True
647 for j in hMuon:
648 detName = hMuon[j]
649 tag = detName + mu + x
650 newh = "muondet" + mu + x
651 if first:
652 h[newh] = h[tag].Clone(newh)
653 h[newh].SetTitle(h[tag].GetTitle().split(" ")[0] + " " + newh)
654 first = False
655 else:
656 h[newh].Add(h[tag])
657
658 # make list of hists with entries
659 k = 1
660 for x in histlistAll:
661 if histlistAll[x] in h:
662 histlist[k] = histlistAll[x]
663 # make cumulative histograms
664 for c in ["", "_E", "_P", "_LP", "_OP", "_id", "_mul", "_evmul", "_origin", "_originmu"]:
665 h[histlist[k] + "_mu" + c].Add(h[histlist[k] + "_muV0" + c])
666 h[histlist[k] + c].Add(h[histlist[k] + "_mu" + c])
667 h[histlist[k] + c].SetMinimum(0.0)
668 h[histlist[k] + "_mu" + c].SetMinimum(0.0)
669 h[histlist[k] + "_muV0" + c].SetMinimum(0.0)
670 k += 1
671 nstations = len(histlist)
672 makePlots(nstations)
673
674
675def executeOneFile(fn, output=None, pid=None) -> None:
676 f = ROOT.TFile.Open(fn)
677 sTree = f.Get("cbmsim")
678 nEvents = sTree.GetEntries()
679 if sTree.GetBranch("GeoTracks"):
680 sTree.SetBranchStatus("GeoTracks", 0)
681 sTree.GetEntry(0)
682 hitContainers = [
683 sTree.vetoPoint,
684 sTree.muonPoint,
685 sTree.EcalPointLite,
686 sTree.strawtubesPoint,
687 sTree.ShipRpcPoint,
688 sTree.TargetPoint,
689 ]
690 ntot = 0
691 for n in range(nEvents):
692 sTree.GetEntry(n)
693 theMuon = sTree.MCTrack[0]
694 if len(sTree.MCTrack) > 1:
695 w = sTree.MCTrack[1].GetWeight() # also works for neutrinos
696 else:
697 print("should not happen with new files", n, fn)
698 w = sTree.MCTrack[0].GetWeight() # also works for neutrinos
699 if w == 0:
700 w = 1.0
701 h["weight"].Fill(w)
702 h["muonP"].Fill(theMuon.GetP() / u.GeV, w)
703 ntot += 1
704 if ntot % 10000 == 0:
705 print("read event", f.GetName(), n)
706 hitmult = {}
707 esum = 0
708 for mcp in sTree.MCTrack:
709 if mcp.GetMotherId() == 0: # mother is original muon
710 E = mcp.GetEnergy()
711 if mcp.GetPdgCode() == 11:
712 h["deltaElec"].Fill(E, w)
713 esum += E
714 h["secondaries"].Fill(E, w)
715 h["prop_deltaElec"].Fill(
716 esum / sTree.MCTrack[0].GetP(), w
717 ) # until energy is really made persistent GetEnergy()
718 for c in hitContainers:
719 for ahit in c:
720 if not ahit.GetEnergyLoss() > 0:
721 continue
722 detID = ahit.GetDetectorID()
723 if ahit.GetName() == "strawtubesPoint":
724 detName = "strawstation_" + str(ahit.GetStationNumber())
725 x = ahit.GetX()
726 y = ahit.GetY()
727 E = ahit.GetEnergyLoss()
728 else:
729 if detID not in logVols:
730 detName = c.GetName().replace("Points", "")
731 if detName not in histlistAll.values():
732 print(detID, detName, c.GetName())
733 else:
734 detName = logVols[detID]
735 x = ahit.GetX()
736 y = ahit.GetY()
737 ahit.GetZ()
738 E = ahit.GetEnergyLoss()
739 if detName not in h:
740 bookHist(detName)
741 mu = ""
742 pdgID = -2
743 if "PdgCode" in dir(ahit):
744 pdgID = ahit.PdgCode()
745 trackID = ahit.GetTrackID()
746 phit = -100.0
747 mom = ROOT.TVector3()
748 aTrack = None
749 if not trackID < 0:
750 aTrack = sTree.MCTrack[trackID]
751 pdgID = aTrack.GetPdgCode()
752 aTrack.GetMomentum(mom) # ! this is not momentum of particle at Calorimeter place
753 phit = mom.Mag() / u.GeV
754 if abs(pdgID) == 13:
755 mu = "_mu"
756 if phit > 3 and abs(pdgID) == 13:
757 mu = "_muV0"
758 detName = detName + mu
759 if detName.find("LS") < 0:
760 h[detName].Fill(x / u.m, y / u.m, w)
761 else:
762 h[detName].Fill(ahit.GetZ() / u.m, ROOT.TMath.ATan2(y, x) / ROOT.TMath.Pi(), w)
763 h[detName + "_E"].Fill(E / u.MeV, w)
764 if detName not in hitmult:
765 hitmult[detName] = {-1: 0}
766 if trackID not in hitmult[detName]:
767 hitmult[detName][trackID] = 0
768 hitmult[detName][trackID] += 1
769 hitmult[detName][-1] += 1
770 h[detName + "_id"].Fill(pdgID, w)
771 h[detName + "_P"].Fill(phit, w)
772 h[detName + "_LP"].Fill(phit, w)
773 if aTrack is not None:
774 r = ROOT.TMath.Sqrt(aTrack.GetStartX() ** 2 + aTrack.GetStartY() ** 2) / u.m
775 h["origin"].Fill(aTrack.GetStartZ() / u.m, r, w)
776 h[detName + "_origin"].Fill(aTrack.GetStartZ() / u.m, r, w)
777 if abs(pdgID) == 13:
778 h[detName + "_originmu"].Fill(aTrack.GetStartZ() / u.m, r, w)
779 h["borigin"].Fill(aTrack.GetStartZ() / u.m, r, w)
780 aTrack.GetMomentum(mom)
781 h[detName + "_OP"].Fill(mom.Mag() / u.GeV, w)
782 rz_inter = -1.0, 0.0
783 if trackID > 0:
784 rz_inter = origin(sTree, trackID)
785 h["porigin"].Fill(
786 aTrack.GetStartZ() / u.m,
787 ROOT.TMath.Sqrt(aTrack.GetStartX() ** 2 + aTrack.GetStartY() ** 2) / u.m,
788 w,
789 )
790 h["mu-inter"].Fill(rz_inter[1] / u.m, rz_inter[0] / u.m, w)
791 for detName in hitmult:
792 h[detName + "_evmul"].Fill(hitmult[detName][-1], w)
793 for tr in hitmult[detName]:
794 h[detName + "_mul"].Fill(hitmult[detName][tr], w)
795 if output:
796 ut.writeHists(h, "tmpHists_" + str(pid) + ".root")
797 output.put("ok")
798 f.Close()
799
800
801#
802def makePlots(nstations: int) -> None:
803 cxcy = {
804 1: [2, 1],
805 2: [3, 1],
806 3: [2, 2],
807 4: [3, 2],
808 5: [3, 2],
809 6: [3, 2],
810 7: [3, 3],
811 8: [3, 3],
812 9: [3, 3],
813 10: [4, 3],
814 11: [4, 3],
815 12: [4, 3],
816 13: [5, 3],
817 14: [5, 3],
818 15: [5, 3],
819 }
820 ut.bookCanvas(
821 h,
822 key="ResultsI",
823 title="hit occupancies",
824 nx=1100,
825 ny=600 * cxcy[nstations][1],
826 cx=cxcy[nstations][0],
827 cy=cxcy[nstations][1],
828 )
829 ut.bookCanvas(
830 h,
831 key="ResultsImu",
832 title="hit occupancies",
833 nx=1100,
834 ny=600 * cxcy[nstations][1],
835 cx=cxcy[nstations][0],
836 cy=cxcy[nstations][1],
837 )
838 ut.bookCanvas(
839 h,
840 key="ResultsImuV0",
841 title="hit occupancies",
842 nx=1100,
843 ny=600 * cxcy[nstations][1],
844 cx=cxcy[nstations][0],
845 cy=cxcy[nstations][1],
846 )
847 ut.bookCanvas(
848 h,
849 key="ResultsII",
850 title="deposited energies",
851 nx=1100,
852 ny=600 * cxcy[nstations][1],
853 cx=cxcy[nstations][0],
854 cy=cxcy[nstations][1],
855 )
856 ut.bookCanvas(
857 h,
858 key="ResultsIII",
859 title="track info",
860 nx=1100,
861 ny=600 * cxcy[nstations][1],
862 cx=cxcy[nstations][0],
863 cy=cxcy[nstations][1],
864 )
865 ut.bookCanvas(
866 h,
867 key="ResultsIV",
868 title="track info",
869 nx=1100,
870 ny=600 * cxcy[nstations][1],
871 cx=cxcy[nstations][0],
872 cy=cxcy[nstations][1],
873 )
874 ut.bookCanvas(h, key="ResultsV", title="origin info", nx=600, ny=400, cx=1, cy=1)
875 txt[0] = "occupancy 1sec 5E13pot "
876 h["dummy"].Fill(-1)
877 nSpills = len(prefixes)
878 for i in histlist:
879 tc = h["ResultsI"].cd(i)
880 hn = histlist[i]
881 if hn not in h:
882 continue
883 h[hn].SetStats(0)
884 h[hn].Draw("colz")
885 txt[i] = "%5.2G" % (h[hn].GetSumOfWeights() / nSpills)
886 labels[i] = ROOT.TLatex().DrawLatexNDC(0.15, 0.85, txt[i])
887 #
888 hn = histlist[i] + "_mu"
889 tc = h["ResultsImu"].cd(i)
890 h[hn].SetStats(0)
891 h[hn].Draw("colz")
892 txt[i + 100] = "%5.2G" % (h[hn].GetSumOfWeights() / nSpills)
893 labels[i + 100] = ROOT.TLatex().DrawLatexNDC(0.15, 0.85, txt[i + 100])
894 #
895 hn = histlist[i] + "_muV0"
896 tc = h["ResultsImuV0"].cd(i)
897 h[hn].SetStats(0)
898 h[hn].Draw("colz")
899 txt[i + 200] = "%5.2G" % (h[hn].GetSumOfWeights() / nSpills)
900 labels[i + 200] = ROOT.TLatex().DrawLatexNDC(0.15, 0.85, txt[i + 200])
901 #
902 for i in histlist:
903 tc = h["ResultsII"].cd(i)
904 h[histlist[i] + "_E"].Draw("colz")
905 #
906 for i in histlist:
907 tc = h["ResultsIII"].cd(i)
908 tc.SetLogy(1)
909 hn = histlist[i]
910 drawBoth("_P", hn)
911 hid = h[hn + "_id"]
912 print("particle statistics for " + histlist[i])
913 for k in range(hid.GetNbinsX()):
914 ncont = hid.GetBinContent(k + 1)
915 pid = hid.GetBinCenter(k + 1)
916 if ncont > 0:
917 temp = int(abs(pid) + 0.5) * int(pid / abs(pid))
918 _p = ut.get_particle(temp)
919 nm = _p.GetName()
920 print(f"{nm} :{ncont:5.2g}")
921 hid = h[histlist[i] + "_mu_id"]
922 for k in range(hid.GetNbinsX()):
923 ncont = hid.GetBinContent(k + 1)
924 pid = hid.GetBinCenter(k + 1)
925 if ncont > 0:
926 temp = int(abs(pid) + 0.5) * int(pid / abs(pid))
927 _p = ut.get_particle(temp)
928 nm = _p.GetName()
929 print(f"{nm} :{ncont:5.2g}")
930 #
931 tc = h["ResultsV"].cd(1)
932 h["origin"].SetStats(0)
933 h["origin"].Draw("colz")
934 #
935 for i in histlist:
936 tc = h["ResultsIV"].cd(i)
937 tc.SetLogy(1)
938 hn = histlist[i]
939 drawBoth("_OP", hn)
941
942
943#
944def AnaEventLoop() -> None:
945 fout = open("rareEvents.txt", "w") # noqa: SIM115
946 for fn in fchainRec:
947 f = ROOT.TFile(fn)
948 if not f.FindObjectAny("cbmsim"):
949 print("skip file ", f.GetName())
950 continue
951 sTree = f.Get("cbmsim")
952 sTree.GetEvent(0)
953 if sTree.GetBranch("GeoTracks"):
954 sTree.SetBranchStatus("GeoTracks", 0)
955 nEvents = sTree.GetEntries()
956 for n in range(nEvents):
957 sTree.GetEntry(n)
958 if n == 0:
959 print("now at event ", n, f.GetName())
960 if len(sTree.MCTrack) > 1:
961 wg = sTree.MCTrack[1].GetWeight() # also works for neutrinos
962 else:
963 wg = sTree.MCTrack[0].GetWeight() # also works for neutrinos
964 i = -1
965 for atrack in sTree.FitTracks:
966 i += 1
967 fitStatus = atrack.getFitStatus()
968 if not fitStatus.isFitConverged():
969 continue
970 nmeas = atrack.getNumPoints()
971 chi2 = fitStatus.getChi2() / nmeas
972 fittedState = atrack.getFittedState()
973 P = fittedState.getMomMag()
974 fout.write("rare event with track %i, %s, %8.2F \n" % (n, f.GetName(), wg))
975 originOfMuon(fout, n, f.GetName(), nEvents)
976 fout.write("reco %i,%5.3F,%8.2F \n" % (nmeas, chi2, P))
977 mcPartKey = sTree.fitTrack2MC[i]
978 mcPart = sTree.MCTrack[mcPartKey]
979 for ahit in sTree.strawtubesPoint:
980 if ahit.GetTrackID() == mcPartKey:
981 fout.write(
982 "P when making hit %i, %8.2F \n"
983 % (
984 ahit.PdgCode(),
985 ROOT.TMath.Sqrt(ahit.GetPx() ** 2 + ahit.GetPy() ** 2 + ahit.GetPz() ** 2) / u.GeV,
986 )
987 )
988 break
989 if not mcPart:
990 continue
991 Ptruth = mcPart.GetP()
992 fout.write("Ptruth %i %8.2F \n" % (mcPart.GetPdgCode(), Ptruth / u.GeV))
993
994
995#
996def muDISntuple(fn) -> None:
997 # take as input the rare events
998 fout = ROOT.TFile("muDISVetoCounter.root", "recreate")
999 h["ntuple"] = ROOT.TNtuple("muons", "muon flux VetoCounter", "id:px:py:pz:x:y:z:w")
1000 f = ROOT.TFile(fn)
1001 sTree = f.Get("cbmsim")
1002 nEvents = sTree.GetEntries()
1003 for n in range(nEvents):
1004 sTree.GetEntry(n)
1005 if len(sTree.MCTrack) > 1:
1006 wg = sTree.MCTrack[1].GetWeight()
1007 else:
1008 wg = sTree.MCTrack[0].GetWeight()
1009 for ahit in sTree.vetoPoint:
1010 detID = ahit.GetDetectorID()
1011 if logVols[detID] != "VetoTimeDet":
1012 continue
1013 pid = ahit.PdgCode()
1014 if abs(pid) != 13:
1015 continue
1016 P = ROOT.TMath.Sqrt(ahit.GetPx() ** 2 + ahit.GetPy() ** 2 + ahit.GetPz() ** 2)
1017 if 3 / u.GeV < P:
1018 h["ntuple"].Fill(
1019 float(pid),
1020 float(ahit.GetPx() / u.GeV),
1021 float(ahit.GetPy() / u.GeV),
1022 float(ahit.GetPz() / u.GeV),
1023 float(ahit.GetX() / u.m),
1024 float(ahit.GetY() / u.m),
1025 float(ahit.GetZ() / u.m),
1026 float(wg),
1027 )
1028 fout.cd()
1029 h["ntuple"].Write()
1030
1031
1032def analyzeConcrete() -> None:
1033 h["fout"] = ROOT.TFile("muConcrete.root", "recreate")
1034 h["ntuple"] = ROOT.TNtuple("muons", "muon flux concrete", "id:px:py:pz:x:y:z:w")
1035 for m in ["", "mu", "V0"]:
1036 ut.bookHist(h, "conc_hitz" + m, "concrete hit z " + m, 100, -100.0, 100.0)
1037 ut.bookHist(h, "conc_hitzP" + m, "concrete hit z vs P" + m, 100, -100.0, 100.0, 100, 0.0, 25.0)
1038 ut.bookHist(h, "conc_hity" + m, "concrete hit y " + m, 100, -15.0, 15.0)
1039 ut.bookHist(h, "conc_p" + m, "concrete hit p " + m, 1000, 0.0, 400.0)
1040 ut.bookHist(h, "conc_pt" + m, "concrete hit pt " + m, 100, 0.0, 20.0)
1041 ut.bookHist(h, "conc_hitzy" + m, "concrete hit zy " + m, 100, -100.0, 100.0, 100, -15.0, 15.0)
1042 top = sGeo.GetTopVolume()
1043 magn = top.GetNode("magyoke_1")
1044 z0 = magn.GetMatrix().GetTranslation()[2] / u.m
1045 for fn in fchain:
1046 f = ROOT.TFile(fn)
1047 if not f.FindObjectAny("cbmsim"):
1048 print("skip file ", f.GetName())
1049 continue
1050 sTree = f.Get("cbmsim")
1051 nEvents = sTree.GetEntries()
1052 ROOT.gROOT.cd()
1053 for n in range(nEvents):
1054 sTree.GetEntry(n)
1055 if len(sTree.MCTrack) > 1:
1056 wg = sTree.MCTrack[1].GetWeight()
1057 else:
1058 wg = sTree.MCTrack[0].GetWeight()
1059 for ahit in sTree.vetoPoint:
1060 detID = ahit.GetDetectorID()
1061 if logVols[detID] != "rockD":
1062 continue
1063 m = ""
1064 pid = ahit.PdgCode()
1065 if abs(pid) == 13:
1066 m = "mu"
1067 P = ROOT.TMath.Sqrt(ahit.GetPx() ** 2 + ahit.GetPy() ** 2 + ahit.GetPz() ** 2)
1068 if abs(pid) == 13 and 3 / u.GeV < P:
1069 m = "V0"
1070 h["ntuple"].Fill(
1071 float(pid),
1072 float(ahit.GetPx() / u.GeV),
1073 float(ahit.GetPy() / u.GeV),
1074 float(ahit.GetPz() / u.GeV),
1075 float(ahit.GetX() / u.m),
1076 float(ahit.GetY() / u.m),
1077 float(ahit.GetZ() / u.m),
1078 float(wg),
1079 )
1080 h["conc_hitz" + m].Fill(ahit.GetZ() / u.m - z0, wg)
1081 h["conc_hity" + m].Fill(ahit.GetY() / u.m, wg)
1082 h["conc_p" + m].Fill(P / u.GeV, wg)
1083 h["conc_hitzP" + m].Fill(ahit.GetZ() / u.m, P / u.GeV, wg)
1084 Pt = ROOT.TMath.Sqrt(ahit.GetPx() ** 2 + ahit.GetPy() ** 2)
1085 h["conc_pt" + m].Fill(Pt / u.GeV, wg)
1086 h["conc_hitzy" + m].Fill(ahit.GetZ() / u.m - z0, ahit.GetY() / u.m, wg)
1087 #
1088 # start = [ahit.GetX()/u.m,ahit.GetY()/u.m,ahit.GetZ()/u.m]
1089 # direc = [-ahit.GetPx()/P,-ahit.GetPy()/P,-ahit.GetPz()/P]
1090 # t = - start[0]/direc[0]
1091
1092 ut.bookCanvas(h, key="ResultsV0", title="muons hitting concrete, p>3GeV", nx=1000, ny=600, cx=2, cy=2)
1093 ut.bookCanvas(h, key="Resultsmu", title="muons hitting concrete", nx=1000, ny=600, cx=2, cy=2)
1094 ut.bookCanvas(h, key="Results", title="hitting concrete", nx=1000, ny=600, cx=2, cy=2)
1095 for m in ["", "mu", "V0"]:
1096 tc = h["Results" + m].cd(1)
1097 h["conc_hity" + m].Draw()
1098 tc = h["Results" + m].cd(2)
1099 h["conc_hitz" + m].Draw()
1100 tc = h["Results" + m].cd(3)
1101 tc.SetLogy(1)
1102 h["conc_pt" + m].Draw()
1103 tc = h["Results" + m].cd(4)
1104 tc.SetLogy(1)
1105 h["conc_p" + m].Draw()
1106 h["fout"].cd()
1107 h["ntuple"].Write()
1108
1109
1110def rareEventEmulsion(fname: str = "rareEmulsion.txt") -> None:
1111 fout = open(fname, "w") # noqa: SIM115
1112 for fn in fchainRec:
1113 f = ROOT.TFile(fn)
1114 if not f.FindObjectAny("cbmsim"):
1115 print("skip file ", f.GetName())
1116 continue
1117 sTree = f.Get("cbmsim")
1118 sTree.GetEvent(0)
1119 if sTree.GetBranch("GeoTracks"):
1120 sTree.SetBranchStatus("GeoTracks", 0)
1121 nEvents = sTree.GetEntries()
1122 for n in range(nEvents):
1123 sTree.GetEntry(n)
1124 if n == 0:
1125 print("now at event ", n, f.GetName())
1126 for ahit in sTree.vetoPoint:
1127 detID = ahit.GetDetectorID()
1128 if logVols[detID] != "Emulsion":
1129 continue
1130 ahit.GetX()
1131 ahit.GetY()
1132 ahit.GetZ()
1133 if len(sTree.MCTrack) > 1:
1134 wg = sTree.MCTrack[1].GetWeight() # also works for neutrinos
1135 else:
1136 wg = sTree.MCTrack[0].GetWeight() # also works for neutrinos
1137 fout.write("rare emulsion hit %i, %s, %8.3F, %i \n" % (n, f.GetName(), wg, ahit.PdgCode()))
1138 if ahit.GetPz() / u.GeV > 1.0:
1139 fout.write(
1140 "V,P when making hit %8.3F,%8.3F,%8.3F %8.3F,%8.3F,%8.3F (GeV) \n"
1141 % (
1142 ahit.GetX() / u.m,
1143 ahit.GetY() / u.m,
1144 ahit.GetZ() / u.m,
1145 ahit.GetPx() / u.GeV,
1146 ahit.GetPy() / u.GeV,
1147 ahit.GetPz() / u.GeV,
1148 )
1149 )
1150 else:
1151 fout.write(
1152 "V,P when making hit %8.3F,%8.3F,%8.3F %8.3F,%8.3F,%8.3F (MeV)\n"
1153 % (
1154 ahit.GetX() / u.m,
1155 ahit.GetY() / u.m,
1156 ahit.GetZ() / u.m,
1157 ahit.GetPx() / u.MeV,
1158 ahit.GetPy() / u.MeV,
1159 ahit.GetPz() / u.MeV,
1160 )
1161 )
1162 originOfMuon(fout, n, f.GetName(), nEvents)
1163
1164
1165#
1166def extractRareEvents(single=None) -> None:
1167 for fn in fchainRec:
1168 if single:
1169 if fn.find(str(single)) < 0:
1170 continue
1171 f = ROOT.TFile(fn)
1172 if not f.FindObjectAny("cbmsim"):
1173 print("skip file ", f.GetName())
1174 continue
1175 sTree = f.Get("cbmsim")
1176 nEvents = sTree.GetEntries()
1177 raref = ROOT.TFile(fn.replace(".root", "_rare.root"), "recreate")
1178 newTree = sTree.CloneTree(0)
1179 for n in range(nEvents):
1180 sTree.GetEntry(n)
1181 if n == 0:
1182 print("now at event ", n, f.GetName())
1183 # count fitted tracks which have converged and nDF>20:
1184 n = 0
1185 for fT in sTree.FitTracks:
1186 fst = fT.getFitStatus()
1187 if not fst.isFitConverged():
1188 continue
1189 if fst.getNdf() < 20:
1190 continue
1191 n += 1
1192 if n > 0:
1193 rc = newTree.Fill()
1194 print("filled newTree", rc)
1195 sTree.Clear()
1196 newTree.AutoSave()
1197 print(" --> events saved:", newTree.GetEntries())
1198 f.Close()
1199 raref.Close()
1200
1201
1202#
1203def extractMuCloseByEvents(single=None) -> None:
1204 mom = ROOT.TVector3()
1205 pos = ROOT.TVector3()
1206 # Goliath magnet has been removed from geometry
1207 goliath_node = top.GetNode("volGoliath_1")
1208 if goliath_node:
1209 golmx = goliath_node.GetMatrix()
1210 zGol = golmx.GetTranslation()[2]
1211 else:
1212 zGol = -9999.0 # No Goliath, accept all z positions
1213 for fn in fchainRec:
1214 if single:
1215 if fn.find(str(single)) < 0:
1216 continue
1217 f = ROOT.TFile(fn)
1218 if not f.FindObjectAny("cbmsim"):
1219 print("skip file ", f.GetName())
1220 continue
1221 sTree = f.Get("cbmsim")
1222 nEvents = sTree.GetEntries()
1223 raref = ROOT.TFile(fn.replace(".root", "_clby.root"), "recreate")
1224 newTree = sTree.CloneTree(0)
1225 for n in range(nEvents):
1226 sTree.GetEntry(n)
1227 if n == 0:
1228 print("now at event ", n, f.GetName())
1229 # look for muons p>3 hitting something
1230 n = 0
1231 for c in [sTree.vetoPoint, sTree.strawtubesPoint, sTree.ShipRpcPoint]:
1232 for ahit in c:
1233 if abs(ahit.PdgCode()) != 13:
1234 continue
1235 ahit.Momentum(mom)
1236 if mom.Mag() < 3.0:
1237 continue
1238 ahit.Position(pos)
1239 if pos.z() < zGol:
1240 continue
1241 n += 1
1242 if n > 0:
1243 newTree.Fill()
1244 # print 'filled newTree',rc
1245 sTree.Clear()
1246 newTree.AutoSave()
1247 print(" --> events saved:", newTree.GetEntries())
1248 f.Close()
1249 raref.Close()
1250
1251
1252#
1253def MergeRareEvents(runs: list[str] | None = None) -> None:
1254 if runs is None:
1255 runs = ["61", "62"]
1256 for prefix in runs:
1257 cmd = "$ROOTSYS/bin/hadd rareEvents_" + prefix + ".root -f "
1258 for fn in fchainRec:
1259 if fn.find("muon" + prefix) < 0:
1260 continue
1261 fr = fn.replace(".root", "_rare.root")
1262 cmd = cmd + " " + fr
1263 os.system(cmd)
1264
1265
1266#
1267def persistency() -> None:
1268 printAndCopy(prefix)
1269 ut.writeHists(h, prefix + ".root", plusCanvas=True)
1270
1271
1272def reDraw(fn) -> None:
1273 if fn.find("root") < 0:
1274 fn = fn + ".root"
1275 if "tc" not in h:
1276 h["tc"] = ROOT.TFile(fn)
1277 for x in ["ResultsI", "ResultsII", "ResultsImu", "ResultsImuV0", "ResultsIII", "ResultsIV", "ResultsV"]:
1278 h[x] = h["tc"].FindObjectAny(x)
1279 h[x].Draw()
1280
1281
1282def printAndCopy(prefix: str | None = None) -> None:
1283 if not prefix:
1284 prefix = (h["tc"].GetName()).replace(".root", "")
1285 for x in ["ResultsI", "ResultsII", "ResultsImu", "ResultsImuV0", "ResultsIII", "ResultsIV", "ResultsV"]:
1286 h[x].Update()
1287 if prefix not in os.listdir("."):
1288 os.mkdir(prefix)
1289 os.chdir(prefix)
1290 h["ResultsI"].Print(prefix + "Back_occ.png")
1291 h["ResultsII"].Print(prefix + "Back_depE.png")
1292 h["ResultsImu"].Print(prefix + "muBack_occ.png")
1293 h["ResultsImuV0"].Print(prefix + "muV0Back_occ.png")
1294 h["ResultsIII"].Print(prefix + "Back_P.png")
1295 h["ResultsIV"].Print(prefix + "Back_OP.png")
1296 h["ResultsV"].Print(prefix + "origin.png")
1297 os.chdir("../")
1298
1299
1300def drawBoth(tag: str, hn) -> None:
1301 n1 = h[hn + "_mu" + tag].GetMaximum()
1302 n2 = h[hn + tag].GetMaximum()
1303 if n1 > n2:
1304 h[hn + tag].SetMaximum(n1)
1305 h[hn + "_mu" + tag].SetLineColor(4)
1306 h[hn + tag].SetLineColor(3)
1307 h[hn + "_mu" + tag].Draw()
1308 h[hn + tag].Draw("same")
1309
1310
1311def debugGeoTracks(sTree) -> None:
1312 for i in range(sTree.GetEntries()):
1313 sTree.GetEntry(i)
1314 n = 0
1315 for gt in sTree.GeoTracks:
1316 print(
1317 i, n, gt.GetFirstPoint()[2], gt.GetLastPoint()[2], gt.GetParticle().GetPdgCode(), gt.GetParticle().P()
1318 )
1319 n += 1
1320
1321
1323 f = ROOT.TFile.Open(fchain[i])
1324 sTree = f.Get("cbmsim")
1325 mom = ROOT.TVector3()
1326 for i in range(sTree.GetEntries()):
1327 sTree.GetEntry(i)
1328 nS = len(sTree.strawtubesPoint)
1329 if nS > 0:
1330 mu = sTree.MCTrack[0]
1331 mu.GetMomentum(mom)
1332 print(i, nS)
1333 mom.Print()
1334 sp = sTree.strawtubesPoint[(max(0, nS - 3))]
1335 sp.Momentum(mom)
1336 mom.Print()
1337 print("-----------------------")
1338 f.Close()
1339
1340
1342 f = ROOT.TFile.Open(fchain[i])
1343 sTree = f.Get("cbmsim")
1344 mom = ROOT.TVector3()
1345 for i in range(sTree.GetEntries()):
1346 sTree.GetEntry(i)
1347 np = 0
1348 for vp in sTree.vetoPoint:
1349 detName = logVols[vp.GetDetectorID()]
1350 if detName == "VetoTimeDet":
1351 np += 0 # ??
1352 vp.Momentum(mom)
1353 print(i, detName, vp.PdgCode())
1354 mom.Print()
1355 print("-----------------------")
1356 f.Close()
1357
1358
1359def depEnergy(sTree) -> None:
1360 for n in range(sTree.GetEntries()):
1361 sTree.GetEntry(n)
1362 for ahit in sTree.strawtubesPoint:
1363 dE = ahit.GetEnergyLoss() / u.keV
1364 ahit.Momentum(mom)
1365 pa = ut.get_particle(ahit.PdgCode())
1366 mpa = pa.Mass()
1367 E = ROOT.TMath.Sqrt(mom.Mag2() + mpa**2)
1368 ekin = E - mpa
1369 h["dE"].Fill(dE, ekin / u.MeV)
1370 h["dE"].SetXTitle("keV")
1371 h["dE"].SetYTitle("MeV")
1372
1373
1374def originOfMuon(fout: TextIOWrapper, n: int, fn, nEvents) -> None:
1375 # from fn extract Yandex or CERN/cracow
1376 ncpu = 9
1377 x = fn.find("/")
1378 ni = int(fn[x - 1 : x]) - 1
1379 if nEvents < 100000:
1380 fm = "$SHIPSOFT/data/pythia8_Geant4_onlyMuons.root"
1381 else:
1382 fm = "$SHIPSOFT/data/pythia8_Geant4_Yandex_onlyMuons.root"
1383 fmuon = ROOT.TFile(fm)
1384 ntupl = fmuon.Get("pythia8-Geant4")
1385 ntot = ntupl.GetEntries()
1386 n3 = int(ntot / ncpu)
1387 N = n3 * ni + n
1388 ntupl.GetEvent(N)
1389 P = ROOT.TMath.Sqrt(ntupl.pz * ntupl.pz + ntupl.py * ntupl.py + ntupl.px * ntupl.px)
1390 fout.write("original muon %i, %i, %8.2F \n" % (ntupl.parentid, ntupl.pythiaid, P))
1391 fmuon.Close()
1392
1393
1394#
1395# BigEventLoop()
1396# makePlots()
1397# AnaEventLoop()
1398
1399
1400# ShipAna
1401def pers() -> None:
1402 xdisk = "/media/Work/HNL/"
1403 for x in h:
1404 if isinstance(h[x], ROOT.TCanvas):
1405 h[x].Update()
1406 tn = h[x].GetName() + ".png"
1407 h[x].Print(tn)
1408 rpath = os.path.abspath(".").split("/HNL/")[1]
1409 lp = rpath.split("/")
1410 prefix = xdisk
1411 for i in range(len(lp)):
1412 if lp[i] not in os.listdir(prefix):
1413 os.system("mkdir " + prefix + "/" + lp[i])
1414 prefix = prefix + "/" + lp[i]
1415 os.system("cp " + tn + " " + xdisk + rpath)
1416
1417
1418from operator import itemgetter
1419
1420
1421def makeNicePrintout(x: list[str] | None = None):
1422 if x is None:
1423 x = ["rareEvents_61-62.txt", "rareEvents_71-72.txt"]
1424 result: list[dict[str, str | float]] = []
1425 cor = 1.0
1426 for fn in x:
1427 with open(fn) as f:
1428 recTrack: dict[str, str | float] | None = None
1429 if fn == "rareEvents_81-102.txt":
1430 cor = 30.0
1431 for lx in f.readlines():
1432 line = lx.replace("\n", "")
1433 if not line.find("rare event") < 0:
1434 if recTrack:
1435 result.append(recTrack)
1436 tmp = line.split(",")
1437 w = tmp[2].replace(" ", "")
1438 ff = tmp[1].split("/")[0].replace(" ", "")
1439 recTrack = {"w": w, "file": ff}
1440 elif recTrack is None:
1441 # skip anything before the first "rare event" marker
1442 continue
1443 elif not line.find("original") < 0:
1444 tmp = line.split(",")
1445 recTrack["origin"] = tmp[0].split(" ")[2]
1446 recTrack["pytiaid"] = tmp[1].replace(" ", "")
1447 recTrack["o-mom"] = tmp[2].replace(" ", "")
1448 elif not line.find("reco ") < 0:
1449 tmp = line.split(",")
1450 recTrack["nmeas"] = tmp[0].split(" ")[1]
1451 recTrack["chi2"] = tmp[1]
1452 recTrack["p_rec"] = tmp[2].replace(" ", "")
1453 elif not line.find("making") < 0:
1454 tmp = line.split(",")
1455 recTrack["p_hit"] = tmp[1].replace(" ", "")
1456 recTrack["fp_hit"] = float(tmp[1].replace(" ", ""))
1457 elif not line.find("Ptruth") < 0:
1458 tmp = line.split(" ")
1459 recTrack["id_hit"] = tmp[1].replace(" ", "")
1460 # flush the record still being assembled when the file ends
1461 if recTrack:
1462 result.append(recTrack)
1463 # print a table
1464 print(
1465 "%4s %8s %8s %4s %8s %8s %8s %8s %8s %8s "
1466 % ("nr", "origin", "pythiaID", "ID", "p_orig", "p_hit", "chi2", "weight", "file", "cor w")
1467 )
1468 # sort according to p_hit
1469 tmp = sorted(result, key=itemgetter("fp_hit"))
1470 muonrate1 = 0
1471 muonrate2 = 0
1472 muonrate3 = 0
1473 for i in range(len(tmp)):
1474 tr = tmp[i]
1475 corw = float(tr["w"]) / cor
1476 if float(tr["p_hit"]) > 1:
1477 muonrate1 += corw
1478 if float(tr["p_hit"]) > 2:
1479 muonrate2 += corw
1480 if float(tr["p_hit"]) > 3:
1481 muonrate3 += corw
1482 print(
1483 "%4i %8s %8s %4s %8s %8s %8s %8s %8s %8s "
1484 % (
1485 i,
1486 tr["origin"],
1487 tr["pytiaid"],
1488 tr["id_hit"],
1489 tr["o-mom"],
1490 tr["p_hit"],
1491 tr["chi2"],
1492 tr["w"],
1493 tr["file"],
1494 corw,
1495 )
1496 )
1497 print("guestimate for muonrate above 1GeV = ", muonrate1)
1498 print("guestimate for muonrate above 2GeV = ", muonrate2)
1499 print("guestimate for muonrate above 3GeV = ", muonrate3)
1500 # guestimate for muonrate above 1GeV = 56025.4793333
1501 # guestimate for muonrate above 2GeV = 25584.9546667
1502 # guestimate for muonrate above 3GeV = 14792.8113333
1503 return tmp
1504
1505
1506#
1507def readAndMergeHistos(prods) -> None:
1508 for p in prods:
1509 x = p
1510 if p.find(".root") < 0:
1511 x = p + ".root"
1512 ut.readHists(h, x)
1513 # make list of hists with entries
1514 k = 1
1515 for x in histlistAll:
1516 if histlistAll[x] in h:
1517 histlist[k] = histlistAll[x]
1518 k += 1
1519 nstations = len(histlist)
1520 print("make plots for ", nstations)
1521 makePlots(nstations)
1522 printAndCopy(prods[0].replace(".root", ""))
1523
1524
1525# python -i $HNL/ana_ShipMuon.py 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
1526# python -i $HNL/ana_ShipMuon.py 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
1527# python -i $HNL/ana_ShipMuon.py 1012 1013 1014 1015 1016 1017 1018 1019 1022 1023 1024 1025 1026 1027 1028 1029
1528# python -i $HNL/ana_ShipMuon.py 634 635 636 637 638 639 640 641 642 643
1529# combine all cern-cracow
1530# python -i $HNL/ana_ShipMuon.py 810 811 812 813 814 815 816 817 818 819 910 911 912 913 914 915 916 917 918 919 1012 1013 1014 1015 1016 1017 1018 1019
1531# python -i $HNL/ana_ShipMuon.py 820 821 822 823 824 825 826 827 828 829 920 921 922 923 924 925 926 927 928 929 1022 1023 1024 1025 1026 1027 1028 1029
1532# make muonDIS ntuple: muDISntuple("/media/Data/HNL/muonBackground/rareEvents_81-102.root") -> 'muDISVetoCounter.root'
1533# second step python $FAIRSHIP/muonDIS/makeMuonDIS.py -f muDISVetoCounter.root -n 10 -nDISPerMuon 10000
1534# third step run_simScript.py --MuDIS -n 10 -f muonDis.root
1535# for concrete
1536# analyzeConcrete() -> muConcrete.root
origin(sTree, it)
None eventsWithEntryPoints(i)
None rareEventEmulsion(str fname="rareEmulsion.txt")
None originOfMuon(TextIOWrapper fout, int n, fn, nEvents)
None MergeRareEvents(list[str]|None runs=None)
None makePlots(int nstations)
None fitSingleGauss(x, ba=None, be=None)
None bookHist(detName)
None debugGeoTracks(sTree)
None eventsWithStrawPoints(i)
None readAndMergeHistos(prods)
None AnaEventLoop()
None BigEventLoop()
None extractRareEvents(single=None)
None depEnergy(sTree)
None analyzeConcrete()
makeNicePrintout(list[str]|None x=None)
None executeOneFile(fn, output=None, pid=None)
None reDraw(fn)
None drawBoth(str tag, hn)
None printAndCopy(str|None prefix=None)
None muDISntuple(fn)
None extractMuCloseByEvents(single=None)
create_config(str DecayVolumeMedium="helium", float Yheight=6.0, int strawDesign=10, str shieldName="TRY_2026", int nuTargetPassive=1, bool SND=True, SND_design=None, TARGET_YAML=None)
configure(run, ship_geo, str|None geofile=None)