CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_6_1_2_SLHC2_patch1/src/CalibMuon/DTCalibration/python/PlottingTools/plotResidualsPerLayer.py

Go to the documentation of this file.
00001 import ROOT
00002 from fitResidual import fitResidual
00003 from drawHistoAllChambers import drawHisto
00004 
00005 layerCorrectionFactors = {'SL1':(1.17,1.16,1.15,1.14),
00006                           'SL2':(1.83,1.20,1.20,1.83),
00007                           'SL3':(1.14,1.15,1.16,1.17)}
00008 
00009 def plotResLayer(fileName,sl,layer,
00010                           dir='DQMData/Run 1/DT/Run summary/DTCalibValidation',
00011                           option="HISTOPE1",draw=True):
00012 
00013     mean_ymin = -0.02
00014     mean_ymax =  0.02
00015     sig_ymin = 0.
00016     sig_ymax = 0.1
00017 
00018     slType = sl
00019     slStr = "SL%d" % slType
00020     layerType = layer
00021     layerStr = "Layer%d" % layerType
00022     verbose = False
00023     nSigmas = 2
00024 
00025     ROOT.TH1.AddDirectory(False)
00026 
00027     file = ROOT.TFile(fileName,'read')
00028 
00029     wheels = (-2,-1,0,1,2)
00030     stations = (1,2,3,4)
00031 
00032     # (Wh-2 MB1 Sec1 ... Wh-2 MB1 Sec12 ... Wh-1 MB1 Sec1 ... Wh-1 MB1 Sec12 ...)
00033     # (Wh-2 MB2 Sec1 ... Wh-2 MB2 Sec12 ... Wh-1 MB2 Sec1 ... Wh-1 MB1 Sec12 ...) ...  
00034     nBins = 250
00035     if slType == 2: nBins = 180
00036     histoMean = ROOT.TH1F("h_ResMeanAll_%s_%s" % (slStr,layerStr),"Mean of residuals",nBins,0,nBins)
00037     histoSigma = ROOT.TH1F("h_ResSigmaAll_%s_%s" % (slStr,layerStr),"Sigma of residuals",nBins,0,nBins)
00038     for st in stations:
00039         nSectors = 12
00040         if st == 4: nSectors = 14
00041         if st == 4 and slType == 2: continue 
00042         if verbose: print "Station",st
00043         for wh in wheels:
00044             if verbose: print "Wheel",wh 
00045             for sec in range(1,nSectors+1):
00046                 if verbose: print "Sector",sec
00047                 # Get histogram
00048                 histoName = "%s/Wheel%d/Station%d/Sector%d/%s/hResDist_STEP3_W%d_St%d_Sec%d_%s_%s" % (dir,wh,st,sec,slStr,wh,st,sec,slStr,layerStr) 
00049                 print "Accessing",histoName
00050                 histo = file.Get(histoName)
00051                 (histo,fitFunc) = fitResidual(histo,nSigmas,verbose)
00052                 fitMean = fitFunc.GetParameter(1)
00053                 fitMeanErr = fitFunc.GetParError(1)
00054                 fitSigma = fitFunc.GetParameter(2)
00055                 fitSigmaErr = fitFunc.GetParError(2)
00056 
00057                 layerIdx = (layer - 1)
00058                 corrFactor = layerCorrectionFactors[slStr][layerIdx]
00059 
00060                 binHistoNew = (st - 1)*60 + (wh + 2)*nSectors + sec
00061                 if verbose: print "Bin in summary histo",binHistoNew
00062                 histoMean.SetBinContent(binHistoNew,fitMean)
00063                 histoMean.SetBinError(binHistoNew,fitMeanErr)
00064                 histoSigma.SetBinContent(binHistoNew,fitSigma*corrFactor)
00065                 histoSigma.SetBinError(binHistoNew,fitSigmaErr*corrFactor)
00066   
00067                 if sec == 1:
00068                     label = "Wheel %d" % wh
00069                     if wh == -2: label += " MB%d" % st  
00070                     histoMean.GetXaxis().SetBinLabel(binHistoNew,label) 
00071                     histoSigma.GetXaxis().SetBinLabel(binHistoNew,label)
00072 
00073     objectsMean = drawHisto(histoMean,title="Mean of residuals (cm)",
00074                                       ymin=mean_ymin,ymax=mean_ymax,option=option,draw=draw)
00075     objectsSigma = drawHisto(histoSigma,title="Resolution (cm)",
00076                                         ymin=sig_ymin,ymax=sig_ymax,option=option,draw=draw)
00077 
00078     return (objectsMean,objectsSigma)
00079 
00080 def plot(fileName,sl,
00081                   dir='DQMData/Run 1/DT/Run summary/DTCalibValidation',type='mean',option='HISTOPE1'):
00082     colors = (2,4,12,44,55,38,27,46)
00083     markers = (24,25,26,27,28,30,32,5)
00084     labels=['Layer 1','Layer 2','Layer 3','Layer 4']
00085     idx_type = None
00086     if type == 'mean': idx_type = 0
00087     elif type == 'sigma': idx_type = 1
00088     else: raise RuntimeError, "Wrong option: %s" % type
00089 
00090     idx = 0
00091     canvas = None
00092     objects = None
00093     histos = []
00094     for layer in range(1,5):
00095         draw = False
00096         if not idx: draw = True
00097 
00098         objs = plotResLayer(fileName,sl,layer,dir,option,draw)
00099         histos.append(objs[idx_type][1])
00100         histos[-1].SetName( "%s_%d" % (histos[-1].GetName(),idx) )
00101         if not idx:
00102             canvas = objs[idx_type][0]
00103             objects = objs[idx_type][2]
00104 
00105         canvas.cd()
00106         if idx:
00107             histos[-1].SetLineColor(colors[ (idx - 1) % len(colors) ])
00108             histos[-1].SetMarkerColor(colors[ (idx - 1) % len(colors) ])
00109             histos[-1].SetMarkerStyle(markers[ (idx - 1) % len(markers) ])
00110 
00111             histos[-1].Draw(option + "SAME")
00112 
00113         idx += 1
00114 
00115     legend = ROOT.TLegend(0.4,0.7,0.95,0.8)
00116     for idx in range( len(histos) ):
00117         histo = histos[idx]
00118         label = histo.GetName()
00119         if len(labels): label = labels[idx]
00120         legend.AddEntry(histo,label,"LP")
00121 
00122         idx += 1
00123 
00124     canvas.cd()
00125     legend.SetFillColor( canvas.GetFillColor() )
00126     legend.Draw("SAME")
00127     objects.append(legend)
00128 
00129     # Compute averages
00130     # (Wh-2 MB1 Sec1 ... Wh-2 MB1 Sec12 ... Wh-1 MB1 Sec1 ... Wh-1 MB1 Sec12 ...)
00131     # (Wh-2 MB2 Sec1 ... Wh-2 MB2 Sec12 ... Wh-1 MB2 Sec1 ... Wh-1 MB1 Sec12 ...) ...  
00132     import math
00133     wheels = (-2,-1,0,1,2)
00134     stations = (1,2,3,4)
00135     slType = sl
00136     slStr = "SL%d" % slType
00137 
00138     nBinsAve = len(stations)*len(wheels)
00139     histoAverage = ROOT.TH1F("h_AverageAll_" + slStr,"",nBinsAve,0,nBinsAve)
00140     averages = {}
00141     averagesErr = {}
00142     averagesSumw = {}
00143     print "Averages:"
00144     for st in stations:
00145         nSectors = 12
00146         if st == 4: nSectors = 14
00147         if st == 4 and slType == 2: continue 
00148         for wh in wheels:
00149             binHistoAve = (st - 1)*5 + (wh + 2) + 1
00150             label = "Wheel %d" % wh
00151             if wh == -2: label += " MB%d" % st  
00152             histoAverage.GetXaxis().SetBinLabel(binHistoAve,label) 
00153 
00154             averages[(st,wh)] = 0.
00155             averagesSumw[(st,wh)] = 0.
00156             for sec in range(1,nSectors+1):
00157                 binHisto = (st - 1)*60 + (wh + 2)*nSectors + sec
00158                 for idx in range( len(histos) ):
00159                     histo = histos[idx]
00160                     value = histo.GetBinContent( binHisto ) 
00161                     error = histo.GetBinError( binHisto ) 
00162                     averages[(st,wh)]     += value/( error*error ) 
00163                     averagesSumw[(st,wh)] += 1./( error*error )
00164             # Average per (st,wh)
00165             averages[(st,wh)] = averages[(st,wh)]/averagesSumw[(st,wh)]
00166             averagesErr[(st,wh)] = math.sqrt( 1./averagesSumw[(st,wh)] )
00167             histoAverage.SetBinContent(binHistoAve,averages[(st,wh)])
00168             histoAverage.SetBinError(binHistoAve,averagesErr[(st,wh)])
00169             print "Station %d, Wheel %d: %.4f +/- %.6f" % (st,wh,averages[(st,wh)],averagesErr[(st,wh)])
00170      
00171     canvasAverage = ROOT.TCanvas("c_" + histoAverage.GetName())
00172     canvasAverage.SetGridx()
00173     canvasAverage.SetGridy()
00174     canvasAverage.SetFillColor( 0 )
00175     canvasAverage.cd()
00176     mean_ymin = -0.02
00177     mean_ymax =  0.02
00178     sig_ymin = 0.
00179     sig_ymax = 0.1
00180     if type == 'mean':
00181         histoAverage.GetYaxis().SetTitle("Mean of residuals (cm)")
00182         histoAverage.GetYaxis().SetRangeUser(mean_ymin,mean_ymax)
00183     elif type == 'sigma':
00184         histoAverage.GetYaxis().SetTitle("Resolution (cm)")
00185         histoAverage.GetYaxis().SetRangeUser(sig_ymin,sig_ymax)
00186 
00187     histoAverage.SetStats(0)
00188     histoAverage.SetLineWidth(2)
00189     histoAverage.SetMarkerStyle( 27 )
00190     histoAverage.SetMarkerSize( 1.5 )
00191     histoAverage.LabelsOption("d","X")
00192     histoAverage.Draw("E2")           
00193 
00194     return ( (canvas,canvasAverage),(histos,histoAverage),objects )
00195 
00196 def plotMean(fileName,sl,dir='DQMData/Run 1/DT/Run summary/DTCalibValidation',option='HISTOPE1'):
00197     type = 'mean'
00198     objs = plot(fileName,sl,dir,type,option)
00199     return objs
00200 
00201 def plotSigma(fileName,sl,dir='DQMData/Run 1/DT/Run summary/DTCalibValidation',option='HISTOPE1'):
00202     type = 'sigma'
00203     objs = plot(fileName,sl,dir,type,option)
00204     return objs
00205 
00206 def plotSigmaAll(fileName,dir='DQMData/Run 1/DT/Run summary/DTCalibValidation',option='HISTOPE1',outputFileName=''):
00207     colors = (2,4,12,44,55,38,27,46)
00208     markers = (24,25,26,27,28,30,32,5)
00209 
00210     slList = (1,2,3)
00211     labels = ('R-#phi SL1','R-z SL2','R-#phi SL3') 
00212     canvas = None
00213     objects = None
00214     histos = []
00215     idx = 0
00216     for sl in slList:
00217         draw = False
00218         if not idx: draw = True
00219 
00220         objs = plotSigma(fileName,sl,dir,option)
00221         histos.append(objs[1][1])
00222         histos[-1].SetName( "%s_%d" % (histos[-1].GetName(),idx) )
00223         if not idx:
00224             canvas = objs[0][1]
00225             #objects = objs[2][1]
00226 
00227         canvas.cd()
00228         if idx:
00229             histos[-1].SetLineColor(colors[ (idx - 1) % len(colors) ])
00230             histos[-1].SetMarkerColor(colors[ (idx - 1) % len(colors) ])
00231             histos[-1].SetMarkerStyle(markers[ (idx - 1) % len(markers) ])
00232 
00233             histos[-1].Draw(option + "SAME")
00234 
00235         idx += 1
00236         
00237     legend = ROOT.TLegend(0.4,0.7,0.95,0.8)
00238     for idx in range( len(histos) ):
00239         histo = histos[idx]
00240         label = histo.GetName()
00241         if len(labels): label = labels[idx]
00242         legend.AddEntry(histo,label,"LP")
00243 
00244         idx += 1
00245 
00246     canvas.cd()
00247     legend.SetFillColor( canvas.GetFillColor() )
00248     legend.Draw("SAME")
00249     if not objects: objects = [legend]
00250     else:           objects.append(legend)
00251 
00252     if outputFileName:
00253         outputFile = ROOT.TFile(outputFileName,'recreate')
00254         outputFile.cd()
00255         for histo in histos: histo.Write()
00256         outputFile.Close()
00257         return 0
00258     else:       
00259         return (canvas,histos,objects)
00260 
00261 #def plotDataVsMCFromFile(fileNameData,fileNameMC,labels=[]):
00262 def plotFromFile(fileNames,labels=[]):
00263 
00264     AddDirectoryStatus_ = ROOT.TH1.AddDirectoryStatus()
00265     ROOT.TH1.AddDirectory(False)
00266 
00267     #fileData = ROOT.TFile(fileNameData,'read')
00268     #fileMC = ROOT.TFile(fileNameMC,'read')
00269     rootFiles = []
00270     for file in fileNames: rootFiles.append( ROOT.TFile(file,'read') ) 
00271 
00272     variables = ['h_AverageAll_SL1_0',
00273                  'h_AverageAll_SL2_1',
00274                  'h_AverageAll_SL3_2']
00275 
00276     colors = (1,2,4,12,44,55,38,27,46)
00277     markers = (20,24,25,26,27,28,30,32,5)
00278     objects = None
00279     canvases = []
00280     legends = []
00281     histos = []
00282     idx_var = 0
00283     for var in variables:
00284         print "Accessing",var 
00285         #histoData = fileData.Get(var)
00286         #histoData.SetName(histoData.GetName() + "_data")
00287         #histoMC = fileMC.Get(var)
00288         #histoMC.SetName(histoMC.GetName() + "_mc")
00289         #histoData.SetLineColor(1)
00290         #histoData.SetMarkerStyle(20)
00291         #histoData.SetMarkerSize(1.4)
00292         #histoData.SetMarkerColor(1)
00293 
00294         #histoMC.SetLineColor(2)
00295         #histoMC.SetMarkerStyle(24)
00296         #histoMC.SetMarkerSize(1.4)
00297         #histoMC.SetMarkerColor(2)
00298 
00299         histos_tmp = []
00300         idx = 0
00301         for file in rootFiles:
00302             histos_tmp.append( file.Get(var) )
00303             histos_tmp[-1].SetName( "%s_%d" % (histos_tmp[-1].GetName(),idx) )
00304             print "Created",histos_tmp[-1].GetName()
00305             histos_tmp[-1].SetLineColor(colors[ idx % len(colors) ]) 
00306             histos_tmp[-1].SetMarkerColor(colors[ idx % len(colors) ]) 
00307             histos_tmp[-1].SetMarkerStyle(markers[ idx % len(markers) ]) 
00308             histos_tmp[-1].SetMarkerSize(1.4)
00309             idx += 1
00310         histos.append( histos_tmp )
00311 
00312         canvases.append( ROOT.TCanvas("c_" + var,var) ) 
00313         canvases[-1].SetGridx()
00314         canvases[-1].SetGridy()
00315         canvases[-1].SetFillColor(0) 
00316         canvases[-1].cd()
00317         #histoData.Draw()
00318         #histoMC.Draw("SAME")
00319         #histos.append( (histoData,histoMC) )
00320         histos[-1][0].Draw()
00321         for histo in histos[-1][1:]: histo.Draw("SAME")
00322             
00323         if len(labels):
00324             #labelData = labels[0]
00325             #labelMC = labels[1]
00326             legends.append( ROOT.TLegend(0.4,0.7,0.95,0.8) )
00327             idx = 0
00328             for histo in histos[-1]:
00329                 legends[-1].AddEntry(histo,labels[idx],"LP")
00330                 idx += 1
00331 
00332             legends[-1].SetFillColor( canvases[-1].GetFillColor() )
00333             legends[-1].Draw("SAME")
00334  
00335         idx_var += 1
00336 
00337     if not objects: objects = [legends]
00338     else:           objects.append(legends)
00339 
00340     ROOT.TH1.AddDirectory(AddDirectoryStatus_)
00341 
00342     return (canvases,histos,objects)