SND@LHC Software
Loading...
Searching...
No Matches
Calibration-TDC.py
Go to the documentation of this file.
1"""
2Utitlity for TDC calibration
3 --- step 1: produce plots from MuFilterEff root file: makeCalibrationHistos(r,readHists=True,t0_channel=4)
4 histograms are in /eos/experiment/sndlhc/calibration/commissioning/MuFilterEff_runXXX.root
5 --- step 2: fill dictionary with calibration parameters per run: getCalibrationParameters(runList=options.runNumbers)
6 location of TDC plots/TCanvas /eos/experiment/sndlhc/calibration/commissioning/TDC
7 --- getRunStatistics(r): returns number of fitted tracks for run r, useful to check if enough statistics
8"""
9
10import ROOT,os
11import rootUtils as ut
12import shipunit as u
13
14h={}
15
16eosroot = os.environ['EOSSHIP']
17systemAndChannels = {1:[8,0],2:[6,2],3:[1,0]}
18systemAndPlanes = {1:2,2:5,3:7}
19systemAndBars = {1:7,2:10,3:60}
20sdict = {1:'Veto',2:'US',3:'DS'}
21barColor = [ROOT.kRed,ROOT.kRed-7,ROOT.kMagenta,ROOT.kMagenta-6,ROOT.kBlue,ROOT.kBlue-9,
22 ROOT.kCyan,ROOT.kAzure-4,ROOT.kGreen,ROOT.kGreen+3]
24 if i==2 or i==5 or i==10 or i==13: return True
25 else: return False
26
27def myPrint(tc,name,withRootFile=True):
28 tc.Update()
29 tc.Print(name+'-run'+str(options.runNumber)+'.png')
30 tc.Print(name+'-run'+str(options.runNumber)+'.pdf')
31 if withRootFile: tc.Print(name+'-run'+str(options.runNumber)+'.root')
32
33from argparse import ArgumentParser
34parser = ArgumentParser()
35parser.add_argument("-p", "--Path", dest="path", help="path to histograms",default="/eos/experiment/sndlhc/calibration/commissioning/")
36parser.add_argument("-r", "--runNumbers", dest="runNumbers", help="list of run numbers, comma separated",default=None,required=True)
37parser.add_argument("-c", "--command", dest="command", help="command", default="")
38
39h = {}
40gain={'H8':{}}
41gain['H8'][3.65] = [49,50,51,52,53,58,59,71,74,80,86,89]
42gain['H8'][2.5] =[46,47,54,55,56,60,72,81,87,90]
43gain['H8'][1.0] =[73,82,88,91]
44gain={'H6':{}}
45gain['H6'][3.65] =[247,248,249,250,251,252,253,254,255,284,290]
46gain['H6'][2.5] =[286,292,298,301]
47gain['H6'][1.0] =[288,300,302]
48
49options = parser.parse_args()
50if options.path.find("/eos")==0: options.path= eosroot+options.path
51
53 F = ROOT.TFile.Open(options.path+"MuFilterEff_run"+str(r)+".root")
54 X = F.GetKey('trackslxy').ReadObj()
55 ntracks = X.GetEntries()
56 F.Close()
57 return ntracks
58
59def extractMeanAndSigma(tdcCanvas,s):
60 C = {}
61 f = ROOT.TFile.Open(tdcCanvas)
62 tTDCcalib = f.Get('tTDCcalib_'+sdict[s]).Clone()
63 for pad in tTDCcalib.GetListOfPrimitives():
64 for z in pad.GetListOfPrimitives():
65 if z.Class_Name() == 'TH1D': tag = z.GetName()
66 if z.Class_Name() == 'TGraphErrors': graph = z
67 station = tag.split('_')[1]
68 if not station in C: C[station]={}
69 case = 'sigma'
70 if tag.find('Mean')>0: case='mean'
71 if not case in C[station]: C[station][case]={}
72 for n in range(graph.GetN()):
73 C[station][case][ int(z.GetPointX(n)) ]=[ z.GetPointY(n),z.GetErrorY(n)]
74 return C
75
76def overlayMean(tdcCanvas,s):
77 f = ROOT.TFile.Open(tdcCanvas)
78 tTDCcalib = f.Get('tTDCcalib_'+sdict[s]).Clone()
79 names = []
80 for pad in tTDCcalib.GetListOfPrimitives():
81 for z in pad.GetListOfPrimitives():
82 if z.Class_Name().find('TH1')==0: tag = z.GetName()
83 if tag.find('Mean')<0: continue
84 for z in pad.GetListOfPrimitives():
85 if z.Class_Name().find('TH1')==0:
86 h[tag] = z.Clone('h'+tag)
87 h[tag].SetDirectory(ROOT.gROOT)
88 Ltag = tag
89 if z.Class_Name() == 'TGraphErrors':
90 h['g'+tag] = z.Clone()
91 names.append('g'+tag)
92 # split in left and right TGraphs
93 for g in names:
94 h['L'+g] = ROOT.TGraphErrors()
95 h['R'+g] = ROOT.TGraphErrors()
96 for x in ['L','R']:
97 h[x+g].SetLineColor(h[g].GetLineColor())
98 h[x+g].SetMarkerStyle(h[g].GetMarkerStyle())
99 for n in range(h[g].GetN()):
100 if h[g].GetPointX(n)<80:
101 nl = h['L'+g].GetN()
102 h['L'+g].SetPoint(nl,h[g].GetPointX(n),h[g].GetPointY(n))
103 h['L'+g].SetPointError(nl,h[g].GetErrorX(n),h[g].GetErrorY(n))
104 else:
105 nr = h['R'+g].GetN()
106 h['R'+g].SetPoint(nr,h[g].GetPointX(n)-80,h[g].GetPointY(n))
107 h['R'+g].SetPointError(nr,h[g].GetErrorX(n)-80,h[g].GetErrorY(n))
108 ROOT.gROOT.cd()
109 h[Ltag].SetStats(0)
110 h['T'] = ROOT.TCanvas('T',sdict[s],1,1,1200,900)
111 h['T'].cd()
112 h[Ltag].GetXaxis().SetRange(1,81)
113 h[Ltag].Draw()
114 for g in names:
115 h['L'+g].Draw('same')
116 h['R'+g].Draw('same')
117 return
118
119def getTDCdelays(path="TDCdelays.txt"):
120 f = open(path)
121 L = f.readlines()
122 delays = {}
123 lstart = 0
124 if len(L)>20: lstart = 21
125 for l in range(lstart,len(L)):
126 tmp = L[l].split(',')
127 for z in tmp:
128 x = z.split('=')
129 if len(x)<2: continue
130 value = float(x[1])
131 name = int(x[0].split('_')[1])
132 delays[name]=value
133 h['D'] = ROOT.TGraph()
134 h['D'].SetLineWidth(2)
135 n = 0
136 for bar_number in range(systemAndBars[2]):
137 for channel in range(8):
138 h['D'].SetPoint(n,n,delays[10*bar_number+channel]/1000.)
139 n+=1
140
141
142def getCalibrationParameters(runList=options.runNumbers):
143 C = {}
144 for r in runList.split(','):
145 C[int(r)]={1:{},2:{}}
146 for s in [1,2]:
147 if int(r)<100 and s==1: continue # no veto in H8
148 tdcCanvas = options.path+"TDC/TDCcalibration_"+sdict[s]+"-run"+r+'.root'
149 C[int(r)][s] = extractMeanAndSigma(tdcCanvas,s)
150 return C
151
152def runStability(C=None):
153 if not C: C = getCalibrationParameters(options.runNumbers)
154 runEvol = {1:{},2:{}}
155 badChannels = {1:{},2:{}}
156 for r in C:
157 for s in C[r]:
158 for l in C[r][s]:
159 for i in C[r][s][l]['mean']:
160 value = C[r][s][l]['mean'][i]
161 key = l+'_'+str(i)
162 rError = value[1] / value[0]
163 if rError > 0.05: continue # remove distributions with low statistics
164 if not key in runEvol[s]: runEvol[s][key] = ROOT.TGraph()
165 n = runEvol[s][key].GetN()
166 runEvol[s][key].SetPoint(n,value[0],1.)
167 ut.bookHist(h,'rms'+sdict[s],'rms',1000,-1.,1.)
168 ut.bookCanvas(h,sdict[s],'',900,600,1,1)
169 h[sdict[s]].cd()
170 for key in runEvol[s]:
171 x = runEvol[s][key].GetRMS()/runEvol[s][key].GetMean()
172 rc = h['rms'+sdict[s]].Fill(x)
173 if abs(x)>0.2: badChannels[key]=x
174 print("%s : %5.2F %5.2F %5.2F"%(key,x,runEvol[s][key].GetRMS(),runEvol[s][key].GetMean()))
175 h['rms'+sdict[s]+'100']=h['rms'+sdict[s]].Rebin(10,'rms'+sdict[s]+'100')
176 h['rms'+sdict[s]+'100'].Draw()
177 return runEvol,badChannels
178
179def makeCalibrationHistos(X=options.runNumbers,readHists=True,t0_channel=4):
180 for r in X.split(','):
181 if readHists:
182 F = ROOT.TFile.Open(options.path+"MuFilterEff_run"+str(r)+".root")
183 options.runNumber = r
184 for s in [1,2]:
185 if s==1 and int(r)<100: continue # no Veto in H8
186 h['tdcCalib'+sdict[s]] = {}
187 for l in range(systemAndPlanes[s]):
188 for bar in range(systemAndBars[s]):
189 for side in ['L','R']:
190 key = sdict[s]+str(s*10+l)+'_'+str(bar)
191 for i in range(systemAndChannels[s][1]+systemAndChannels[s][0]):
192 if i==t0_channel: continue
193 j = side+'_'+key+'-c'+str(i)
194 x = 'TDCcalib'+j
195 # get TDC calibration constants:
196 h['tdcCalib'+sdict[s]][j] =[0,0,0,0]
197 h[x] = F.GetKey(x).ReadObj()
198 if h[x].GetEntries()>10:
199 rc = h[x].Fit('gaus','SNQ')
200 rc = h[x].Fit('gaus','SNQ')
201 if rc:
202 res = rc.Get()
203 h['tdcCalib'+sdict[s]][j] =[res.Parameter(1),res.ParError(1),res.Parameter(2),res.ParError(2)]
204#
205 for l in range(systemAndPlanes[s]):
206 tag = sdict[s]+str(l)
207 ut.bookCanvas(h,'sigmaTDC_'+tag,'TDC RMS '+tag,2000,600,systemAndBars[s],2)
208 ut.bookCanvas(h, 'TDCcalib_'+tag,'TDC TDCi-T0 '+tag,2000,600,systemAndBars[s],2)
209 k=1
210 for bar in range(systemAndBars[s]):
211 for side in ['L','R']:
212 key = sdict[s]+str(10*s+l)+'_'+str(bar)
213 for i in range(systemAndChannels[s][1]+systemAndChannels[s][0]):
214 j = side+'_'+key+'-c'+str(i)
215 for x in ['sigmaTDC_'+tag,'TDCcalib_'+tag]:
216 if x.find('calib')>0 and (i==t0_channel): continue
217 tc=h[x].cd(k)
218 opt='same'
219 if i==0 and x.find('calib')<0: opt=""
220 if i==1 and x.find('calib')>0: opt=""
221 aHist = x.split('_')[0]+j
222 h[aHist] = F.GetKey(aHist).ReadObj()
223 h[aHist].SetLineColor(barColor[i])
224 h[aHist].GetXaxis().SetRangeUser(-5,5)
225 h[aHist].Draw(opt)
226 h[aHist].Draw(opt+'HIST')
227 k+=1
228 myPrint(h['sigmaTDC_'+tag],'TDC/TDCrms_'+tag)
229 myPrint(h['TDCcalib_'+tag],'TDC/TDCcalib_'+tag)
230#
231 ut.bookHist(h,'TDCcalibMean_'+tag,';SiPM channel ; [ns]',160,0.,160.)
232 ut.bookHist(h,'TDCcalibSigma_'+tag,';SiPM channel ; [ns]',160,0.,160.)
233 h['gTDCcalibMean_'+tag]=ROOT.TGraphErrors()
234 h['gTDCcalibSigma_'+tag]=ROOT.TGraphErrors()
235#
236 for x in h['tdcCalib'+sdict[s]]:
237 tmp = h['tdcCalib'+sdict[s]][x]
238 side = 0
239 z = x.split('_')
240 if z[0]=='R': side = 1
241 l = z[1][len(z[1])-1]
242 bar = z[2][0]
243 c = z[2].split('c')[1]
244 xbin = int(bar)*16+side*8+int(c)
245 tag = sdict[s]+str(l)
246 rc = h['TDCcalibMean_'+tag].SetBinContent(xbin+1,tmp[0])
247 rc = h['TDCcalibMean_'+tag].SetBinError(xbin+1,tmp[1])
248 rc = h['TDCcalibSigma_'+tag].SetBinContent(xbin+1,tmp[2])
249 rc = h['TDCcalibSigma_'+tag].SetBinError(xbin+1,tmp[3])
250 #print("%s %5.2F+/-%5.2F %5.2F+/-%5.2F"%(x,tmp[0],tmp[1],tmp[2],tmp[3]))
251 ut.bookCanvas(h,'tTDCcalib_'+sdict[s],'TDC calib '+sdict[s],2400,1800,2,systemAndPlanes[s])
252 for l in range(systemAndPlanes[s]):
253 tag = sdict[s]+str(l)
254 aHistS = h['TDCcalibSigma_'+tag]
255 aHistM = h['TDCcalibMean_'+tag]
256 k=0
257 for i in range(1,aHistS.GetNbinsX()):
258 if aHistS.GetBinContent(i)>0:
259 h['gTDCcalibSigma_'+tag].SetPoint(k,i-1,aHistS.GetBinContent(i))
260 h['gTDCcalibSigma_'+tag].SetPointError(k,0.5,aHistS.GetBinError(i))
261 h['gTDCcalibMean_'+tag].SetPoint(k,i-1,aHistM.GetBinContent(i))
262 h['gTDCcalibMean_'+tag].SetPointError(k,0.5,aHistM.GetBinError(i))
263 k+=1
264#
265 planeColor = {0:ROOT.kBlue,1:ROOT.kRed,2:ROOT.kGreen,3:ROOT.kCyan,4:ROOT.kMagenta}
266 for l in range(systemAndPlanes[s]):
267 tag = sdict[s]+str(l)
268 tc = h['tTDCcalib_'+sdict[s]].cd(2*l+1)
269 aHistS = h['TDCcalibSigma_'+tag]
270 aHistS.Reset()
271 aHistS.SetMaximum(2.0)
272 aHistS.Draw()
273 h['gTDCcalibSigma_'+tag].SetLineColor(planeColor[l])
274 h['gTDCcalibSigma_'+tag].Draw('same')
275#
276 for l in range(systemAndPlanes[s]):
277 tag = sdict[s]+str(l)
278 tc = h['tTDCcalib_'+sdict[s]].cd(2*l+2)
279 aHistM = h['TDCcalibMean_'+tag]
280 aHistM.Reset()
281 aHistM.SetMaximum(2.0)
282 aHistM.SetMinimum(-2.0)
283 aHistM.Draw()
284 h['gTDCcalibMean_'+tag].SetLineColor(planeColor[l])
285 h['gTDCcalibMean_'+tag].Draw('same')
286 myPrint(h['tTDCcalib_'+sdict[s]],'TDC/TDCcalibration_'+sdict[s])
287
288
290 for r in C:
291 for system in C[r]:
292 for plane in C[r][sytem]:
293 for channel in C[r][sytem]['mean']:
294 continue
295
296if options.command:
297 tmp = options.command.split(';')
298
299 if tmp[0].find('.C')>0: # execute a C macro
300 ROOT.gROOT.LoadMacro(tmp[0])
301 ROOT.Execute()
302 exit()
303 command = tmp[0]+"("
304 for i in range(1,len(tmp)):
305 command+=tmp[i]
306 if i<len(tmp)-1: command+=","
307 command+=")"
308 print('executing ' + command + "for run ",options.runNumbers)
309 eval(command)
310 print('finished ' + command + "for run ",options.runNumbers)
311
extractMeanAndSigma(tdcCanvas, s)
getCalibrationParameters(runList=options.runNumbers)
overlayMean(tdcCanvas, s)
myPrint(tc, name, withRootFile=True)
makeCalibrationHistos(X=options.runNumbers, readHists=True, t0_channel=4)
getTDCdelays(path="TDCdelays.txt")