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