SND@LHC Software
Loading...
Searching...
No Matches
run_reco.py
Go to the documentation of this file.
1from __future__ import print_function
2import os, subprocess,ROOT,time,getpass,multiprocessing
3import rootUtils as ut
4ncores = min(multiprocessing.cpu_count(),4)
5user = getpass.getuser()
6# support for eos, assume: eosmount $HOME/eos
7
8h = {}
9
10def fitSingleGauss(x,ba=None,be=None):
11 name = 'myGauss_'+x
12 myGauss = h[x].GetListOfFunctions().FindObject(name)
13 if not myGauss:
14 if not ba : ba = h[x].GetBinCenter(1)
15 if not be : be = h[x].GetBinCenter(h[x].GetNbinsX())
16 bw = h[x].GetBinWidth(1)
17 mean = h[x].GetMean()
18 sigma = h[x].GetRMS()
19 norm = h[x].GetEntries()*0.3
20 myGauss = ROOT.TF1(name,'[0]*'+str(bw)+'/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]',4)
21 myGauss.SetParameter(0,norm)
22 myGauss.SetParameter(1,mean)
23 myGauss.SetParameter(2,sigma)
24 myGauss.SetParameter(3,1.)
25 myGauss.SetParName(0,'Signal')
26 myGauss.SetParName(1,'Mean')
27 myGauss.SetParName(2,'Sigma')
28 myGauss.SetParName(3,'bckgr')
29 h[x].Fit(myGauss,'','',ba,be)
30
31cmd = os.environ["FAIRSHIP"]+"/macro/ShipReco.py"
32cmdAna = os.environ["FAIRSHIP"]+"/macro/ShipAna.py"
33def execute( ncpu = 4 ):
34 cpus = {}
35 log = {}
36 for i in range(ncpu): cpus[i]={}
37 jobs = []
38 for x in os.listdir('.'):
39 if not x.find(prefix)<0:
40 if os.path.isdir(x) :
41 jobs.append(x)
42 k = 0
43 print(jobs)
44 for x in jobs:
45 if k==ncpu: k = 0
46 if 'child' in cpus[k]:
47 rc = child.communicate()[0]
48 log[k]['log'].close()
49 print("change to directory ",k,x)
50 os.chdir('./'+x)
51 for f in os.listdir('.'):
52 if not f.find("geofile_full")<0:
53 inputfile = f.replace("geofile_full","ship")
54 log[k] = open("logRec",'w')
55 cpus[k] = subprocess.Popen(["python",cmd,"-n 9999999 -f "+inputfile], stdout=log[k],)
56 k+=1
57 os.chdir('../')
58 break
59 return cpus,log
60
61def getJobs(prefix):
62 jobs = []
63 for x in os.listdir('.'):
64 if not x.find(prefix)<0:
65 if os.path.isdir(x) :
66 jobs.append(x)
67 return jobs
69 processoutput = os.popen("ps -u "+user).read()
70 nproc = 0
71 for x in processoutput.split('\n'):
72 if not x.find('python')<0 and x.find('defunct')<0 :
73 nproc+=1
74 return nproc
75def killAll():
76 processoutput = os.popen("ps -u "+user).read()
77 for x in processoutput.split('\n'):
78 if not x.find('python')<0:
79 pid = int(x[:5])
80 print('kill '+str(pid))
81 os.system('kill '+str(pid))
82def executeSimple(prefixes,reset=False):
83 proc = {}
84 for prefix in prefixes:
85 jobs = getJobs(prefix)
86 for x in jobs:
87 print("change to directory ",x)
88 os.chdir('./'+x)
89 geofile = None
90 for f in os.listdir('.'):
91 if not f.find("geofile_full")<0:
92 geofile = f
93 break
94 if not geofile:
95 print("ERROR: no geofile found",x)
96 os.chdir('../')
97 continue
98 else:
99 inputfile = geofile.replace("geofile_full","ship")
100 nproc = 100
101 while nproc > ncores :
102 nproc = checkRunningProcesses()
103 if nproc > ncores:
104 print('wait a minute')
105 time.sleep(100)
106 print('launch reco',x)
107 proc[x] = 1
108 try: os.system("rm logRec")
109 except: pass
110 if reset: os.system("python "+cmd+" -n 9999999 -f "+inputfile + " --saveDisk >> logRec &")
111 else: os.system("python "+cmd+" -n 9999999 -f "+inputfile + " >> logRec &")
112 os.chdir('../')
113 time.sleep(10)
114 nJobs = len(proc)
115 while nJobs > 0:
116 nJobs = len(proc)
117 print('debug ',nJobs)
118 for p in sorted(proc.keys()):
119 os.chdir('./'+p)
120 nproc = 100
121 while nproc > ncores :
122 nproc = checkRunningProcesses()
123 if nproc > ncores:
124 print('wait a minute')
125 time.sleep(100)
126 log = open('logRec')
127 completed = False
128 rl = log.readlines()
129 log.close()
130 if "finishing" in rl[len(rl)-1] : completed = True
131 if completed:
132 print('analyze ',p,nproc)
133 try: os.system("rm logAna")
134 except: pass
135 os.system("python "+cmdAna+" -n 9999999 -f "+inputfile.replace('.root','_rec.root')+ " >> logAna &")
136 rc = proc.pop(p)
137 time.sleep(10)
138 else:
139 print('Rec job not finished yet',p)
140 nproc = checkRunningProcesses()
141 if nproc == 1 : print("rec job probably failed, only when python process running")
142 time.sleep(100)
143 os.chdir('../')
144
145def executeAna(prefixes):
146 cpus = {}
147 log = {}
148 for prefix in prefixes:
149 jobs = getJobs(prefix)
150 for x in jobs:
151 print("change to directory ",x)
152 os.chdir('./'+x)
153 for f in os.listdir('.'):
154 if not f.find("geofile_full")<0:
155 inputfile = f.replace("geofile_full","ship")
156 log[x] = open("logAna",'w')
157 process = subprocess.Popen(["python",cmdAna,"-n 9999999", "-f "+inputfile.replace('.root','_rec.root')], stdout=log[x])
158 process.wait()
159 print('finished ',process.returncode)
160 log[x].close()
161 os.chdir('../')
162 break
163
164h={}
166 if not type(p)==type([]): pl=[p]
167 else: pl = p
168 hlist = ''
169 for p in pl:
170 prefix = str(p)
171 for x in os.listdir('.'):
172 if not x.find(prefix)<0:
173 if os.path.isdir(x) :
174 hlist += x+'/ShipAna.root '
175 print("-->",hlist)
176 os.system('hadd -f ShipAna.root '+hlist)
177 ut.readHists(h,"ShipAna.root")
178 print(h['meanhits'].GetEntries())
179 if 1>0:
180 ut.bookCanvas(h,key='strawanalysis',title='Distance to wire and mean nr of hits',nx=1200,ny=600,cx=2,cy=1)
181#
182 cv = h['strawanalysis'].cd(1)
183 h['disty'].DrawCopy()
184 h['distu'].DrawCopy('same')
185 h['distv'].DrawCopy('same')
186 cv = h['strawanalysis'].cd(2)
187 h['meanhits'].DrawCopy()
188 print(h['meanhits'].GetEntries())
189
190 ut.bookCanvas(h,key='fitresults',title='Fit Results',nx=1600,ny=1200,cx=2,cy=2)
191 cv = h['fitresults'].cd(1)
192 h['delPOverP'].Draw('box')
193 cv = h['fitresults'].cd(2)
194 cv.SetLogy(1)
195 h['chi2'].Draw()
196 cv = h['fitresults'].cd(3)
197 h['delPOverP_proj'] = h['delPOverP'].ProjectionY()
198 ROOT.gStyle.SetOptFit(11111)
199 h['delPOverP_proj'].Draw()
200 h['delPOverP_proj'].Fit('gaus')
201 cv = h['fitresults'].cd(4)
202 h['delPOverP2_proj'] = h['delPOverP2'].ProjectionY()
203 h['delPOverP2_proj'].Draw()
204 fitSingleGauss('delPOverP2_proj')
205 h['fitresults'].Print('fitresults.gif')
206 ut.bookCanvas(h,key='fitresults2',title='Fit Results',nx=1600,ny=1200,cx=2,cy=2)
207 print('finished with first canvas')
208 cv = h['fitresults2'].cd(1)
209 h['Doca'].Draw()
210 cv = h['fitresults2'].cd(2)
211 h['IP0'].Draw()
212 cv = h['fitresults2'].cd(3)
213 h['HNL'].Draw()
214 fitSingleGauss('HNL',0.,2.)
215 cv = h['fitresults2'].cd(4)
216 h['IP0/mass'].Draw('box')
217 h['fitresults2'].Print('fitresults2.gif')
218 h['strawanalysis'].Print('strawanalysis.gif')
219 print('finished making plots')
220
221def mergeNtuples(prefixes):
222 for prefix in prefixes:
223 jobs = getJobs(prefix)
224 haddCommand = ''
225 for x in jobs:
226 for f in os.listdir(x):
227 if not f.find("geofile_full")<0:
228 inputfile = (f.replace("geofile_full","ship")).replace('.root','_rec.root')
229 haddCommand+= ' '+ x + '/' + inputfile
230 break
231 cmd = 'hadd -f '+inputfile.replace('.root','_'+prefix+'.root') + haddCommand
232 os.system(cmd)
233def checkProd(prefixes,quiet=False):
234 summary = {'Sim':{},'Rec':{},'Ana':{}}
235 for prefix in prefixes:
236 jobs = getJobs(prefix)
237 for x in jobs:
238 try: log = open( x+'/log')
239 except:
240 if not quiet: print('no log file for ',x)
241 summary['Sim'][x] = -1
242 continue
243 rl = log.readlines()
244 log.close()
245 if len(rl)<1 :
246 if not quiet: print("simulation failed log file 0",x)
247 summary['Sim'][x] = 0
248 continue
249 elif "Real time" in rl[len(rl)-1] :
250 if not quiet: print('simulation step OK ',x)
251 summary['Sim'][x] = 1
252 else:
253 if not quiet: print("simulation failed ",x)
254 summary['Sim'][x] = 0
255 continue
256 try: log = open( x+'/logRec')
257 except:
258 if not quiet: print('no logRec file for ',x)
259 summary['Rec'][x] = -1
260 continue
261 rl = log.readlines()
262 log.close()
263 if "finishing" in rl[len(rl)-1] :
264 if not quiet: print('reconstruction step OK ',x)
265 summary['Rec'][x] = 1
266 else:
267 if not quiet: print("reconstruction failed ",x)
268 summary['Rec'][x] = 0
269 continue
270 try: log = open( x+'/logAna')
271 except:
272 if not quiet: print('no logAna file for ',x)
273 summary['Ana'][x] = -1
274 continue
275 rl = log.readlines()
276 log.close()
277 if "finished" in rl[len(rl)-1] :
278 if not quiet: print('analysis step OK ',x)
279 summary['Ana'][x] = 1
280 else:
281 if not quiet: print("analysis failed ",x)
282 summary['Ana'][x] = 0
283 continue
284 return summary
286 result = checkProd(pl,quiet=True)
287 for p in result:
288 for x in result[p]:
289 if result[p][x]<1 : print(p,x,result[p][x])
290
291
293 executeSimple(pl,reset=True)
295 mergeNtuples(pl)
297 for prefix in prefixes:
298 jobs = getJobs(prefix)
299 for x in jobs:
300 for f in os.listdir(x):
301 if not f.find("geofile_full")<0:
302 inputfile = (f.replace("geofile_full","ship")).replace('.root','_rec.root')
303 os.system('rm '+x+'/' + inputfile )
304
306 result = checkProd(pl,quiet=True)
307 eos = "/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select"
308 for x in result['Rec']:
309 if result['Rec'][x]<1 : print('Reco failed !',x,result['Rec'][x])
310 else:
311 cmd = eos+' cp -r '+os.path.abspath('.')+'/'+x+'/ /eos/experiment/ship/data/DAFreco/muonBackground/'+x+'/'
312 os.system(cmd)
313 print('copied to eos',x)
314
315pl=[]
316for p in os.sys.argv[1].split(','):
317 pref = 'muon'
318 xx = os.path.abspath('.').lower()
319 if not xx.find('neutrino')<0: pref='neutrino'
320 if not xx.find('vdis')<0 or not xx.find('vetodis')<0: pref='disV'
321 elif not xx.find('clby')<0: pref='disCLBY'
322 elif not xx.find('dis')<0: pref='dis'
323 pl.append(pref+p)
324print(" execute() input comma separated production nr, performs Simple/mergeHistos/mergeNtuples ")
325print(" executeSimple(pl,reset=True) ")
326print(" checkProd(pl)")
327print(" executeAna(pl) ")
328print(" mergeNtuples(pl) ")
329print(" removeIntermediateFiles(pl) only _rec ")
330print(" checkRunningProcesses() ")
331#61,611,612,613,614,615,616,62,621,622,623,624,625,626
removeIntermediateFiles(prefixes)
Definition run_reco.py:296
fitSingleGauss(x, ba=None, be=None)
Definition run_reco.py:10
copyRecoToEos(pl)
Definition run_reco.py:305
executeSimple(prefixes, reset=False)
Definition run_reco.py:82
mergeHistosMakePlots(p)
Definition run_reco.py:165
checkRunningProcesses()
Definition run_reco.py:68
printFailedJobs(pl)
Definition run_reco.py:285
checkProd(prefixes, quiet=False)
Definition run_reco.py:233
executeAna(prefixes)
Definition run_reco.py:145
mergeNtuples(prefixes)
Definition run_reco.py:221
getJobs(prefix)
Definition run_reco.py:61
killAll()
Definition run_reco.py:75