Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-08-15 22:40:10

0001 import ROOT
0002 ROOT.gROOT.SetBatch(True)
0003 from setTDRStyle import setTDRStyle
0004 
0005 from systematicErrors import *
0006 from granularity import *
0007 
0008 
0009 class ResultPlotter:
0010     def __init__(self):
0011         setTDRStyle()
0012         self.inFiles = {}
0013         self.hitNumbers = {}
0014         self.labels = {}
0015         self.colors = {}
0016         self.markers = {}
0017         self.outPath = None
0018         self.hasSystematics = {}
0019         self.systematics = {}
0020         self.granularity = standardGranularity
0021         self.title = ""
0022         self.order = []
0023         
0024     def addInputFile(self, label, inFile, color=None, marker=20, hitNumbers=None):
0025         self.order.append(label)
0026         self.inFiles[label] = inFile
0027         self.labels[label] = label
0028         self.systematics[label] = []
0029         self.hasSystematics[label] = False
0030         self.markers[label] = marker
0031         self.hitNumbers[label] = hitNumbers
0032         if color != None:
0033             self.colors[label] = color
0034         else:
0035             # choose first not occupied color (other than white)
0036             for autoColor in range(1,100):
0037                 if autoColor not in self.colors.values() and not autoColor == 10:
0038                     self.colors[label] = autoColor
0039                     break
0040     
0041     def setGranularity(self, granularity):
0042         self.granularity = granularity
0043     
0044     def setOutputPath(self, outPath):
0045         self.outPath = outPath
0046     
0047     def setTitle(self, title):
0048         self.title = title
0049     
0050     def doSystematics(self, label):
0051         self.hasSystematics[label] = True
0052     
0053     def addSystematics(self, label, systematics, additive=True):
0054         self.hasSystematics[label] = True
0055         if not additive:
0056             self.systematics[label] = []
0057         self.systematics[label].append(systematics)
0058     
0059     def convertName(self, name):
0060         out = name.replace("Bpix", "BPIX")
0061         out = out.replace("Fpix", "FPIX")
0062         out = out.replace("Plus", "+")
0063         out = out.replace("Minus", "-")
0064         out = out.replace("Fpix", "FPIX")
0065         out = out.replace("Tib", "TIB")
0066         out = out.replace("Tob", "TOB")
0067         out = out.replace("Tid", "TID")
0068         out = out.replace("Tec", "TEC")
0069         out = out.replace("Layer", " L")
0070         out = out.replace("Ring", " R")
0071         out = out.replace("Stereo", "S")
0072         out = out.replace("Rphi", "R") # different from Ring, this one does not add a space in front
0073         out = out.replace("In", "i")
0074         out = out.replace("Out", "o")
0075         return out
0076     
0077     def makeHitNumbers(self, label, sectorRange, coordinate):
0078         self.numHitCounters += 1
0079         sectors = list(range(sectorRange[0],sectorRange[1]+1))
0080         numSectors = len(sectors)
0081         
0082         fi = ROOT.TFile(self.hitNumbers[label], "READ")
0083         align = 22
0084         size = 0.02
0085         font = 42
0086         labels = []
0087         for i,sector in enumerate(sectors):
0088             hitHist = fi.Get("ApeEstimator1/Sector_{}/Results/h_NorRes{}".format(sector, coordinate.upper()))
0089             num = hitHist.GetEntries()
0090             posX = (float(i)+0.5)/numSectors*(1-ROOT.gPad.GetLeftMargin()-ROOT.gPad.GetRightMargin())+ROOT.gPad.GetLeftMargin()
0091             posY = (1-ROOT.gPad.GetTopMargin()-size)-1.2*size*self.numHitCounters
0092             
0093             labelTex = ROOT.TLatex(posX, posY, "%.2E"%(num))
0094             labelTex.SetNDC(True)
0095             labelTex.SetTextColor(self.colors[label])
0096             labelTex.SetTextSize(size)
0097             labelTex.SetTextFont(font)
0098             labelTex.SetTextAngle(45)
0099             labelTex.SetTextAlign(align)
0100             labels.append(labelTex)
0101         return labels
0102             
0103     def makeHist(self, label, sectorRange, coordinate, number):
0104         sectors = list(range(sectorRange[0],sectorRange[1]+1))
0105         numSectors = len(sectors)
0106         
0107         hist = ROOT.TH1F("{}hist{}_{}".format(label, number, coordinate), "", numSectors, 0, numSectors)
0108         hist.SetTitle(";;#sigma_{align," + coordinate.lower() + "}  [#mum]")
0109         hist.SetAxisRange(0.,100.,"Y")
0110         
0111         syst = None
0112         if self.hasSystematics[label]:
0113             syst = ROOT.TGraphAsymmErrors()
0114         
0115         fi = ROOT.TFile(self.inFiles[label], "READ")
0116         nameTree = fi.Get("nameTree")
0117         apeTree = fi.Get("iterTree{}".format(coordinate.upper()))
0118         # Get last entries in branches (for apeTree) to retrieve result of this iteration
0119         # in iterTreeX/Y, the results of the previous iterations are also stored
0120         nameTree.GetEntry(0)
0121         apeTree.GetEntry(apeTree.GetEntries()-1)
0122         iBin = 1
0123         for sector in sectors:
0124             sectorApe  = 10000. * (float(getattr(apeTree,  "Ape_Sector_{}".format(sector))))**0.5
0125             sectorName = self.convertName(str(getattr(nameTree, "Ape_Sector_{}".format(sector))))
0126             binWidth = hist.GetXaxis().GetBinCenter(iBin) - hist.GetXaxis().GetBinLowEdge(iBin)
0127             hist.SetBinContent(iBin, sectorApe)
0128             hist.SetBinError(iBin, 0.0000001)
0129             hist.GetXaxis().SetBinLabel(iBin, sectorName)
0130             
0131             if self.hasSystematics[label]:
0132                 sysErrUp = 0
0133                 sysErrDn = 0
0134                 # add up errors quadratically
0135                 for partError in self.systematics[label]:
0136                     scaleFac = 1.0
0137                     if partError.isRelative[sector-1]:
0138                         scaleFac = sectorApe
0139         
0140                     if partError.direction[sector-1] == DIR_BOTH:
0141                         sysErrUp += (scaleFac*partError[coordinate][sector-1])**2
0142                         sysErrDn += (scaleFac*partError[coordinate][sector-1])**2
0143                     elif partError.direction[sector-1] == DIR_DOWN:
0144                         sysErrDn += (scaleFac*partError[coordinate][sector-1])**2
0145                     elif partError.direction[sector-1] == DIR_UP:
0146                         sysErrUp += (scaleFac*partError[coordinate][sector-1])**2
0147                 sysErrUp = sysErrUp**0.5
0148                 sysErrDn = sysErrDn**0.5
0149                 
0150                 syst.SetPoint(iBin, hist.GetXaxis().GetBinCenter(iBin), sectorApe)
0151                 syst.SetPointError(iBin, binWidth, binWidth, sysErrDn, sysErrUp)
0152             
0153             iBin += 1
0154         hist.SetDirectory(0)
0155         fi.Close()
0156         return hist, syst
0157         
0158     def draw(self):
0159         allLabels = []
0160         for coordinate in self.granularity.sectors.keys():
0161             plotNumber = 0
0162             rangeList = self.granularity.sectors[coordinate]
0163             for sectorRange in rangeList:
0164                 self.canvas = ROOT.TCanvas("canvas", "canvas", max(int(ROOT.gStyle.GetCanvasDefW()*len(list(range(sectorRange[0],sectorRange[1]+1)))/10.), int(ROOT.gStyle.GetCanvasDefW()/2)),ROOT.gStyle.GetCanvasDefH())
0165                 ROOT.gPad.SetRightMargin(0.10)
0166                 
0167                 legend = ROOT.TLegend(0.2,0.62,0.5,0.82)
0168                 legend.SetFillColor(0)
0169                 legend.SetFillStyle(0)
0170                 legend.SetTextSize(0.04)
0171                 legend.SetMargin(0.30)
0172                 legend.SetBorderSize(0)
0173                 
0174                 firstHist = True
0175                 histos = [] # need to save histos or they will be deleted right after variable is set to something else
0176                 systGraphs = [] # same for systematics errors
0177                 self.numHitCounters = 0
0178                 for name in self.order:
0179                     if firstHist:
0180                         addDraw = ""
0181                         firstHist = False
0182                     else:
0183                         addDraw = "same"
0184                     
0185                     if self.markers[name] != 0:
0186                         drawMode = "P0%s"%(addDraw)
0187                     else:
0188                         drawMode = "hist%s"%(addDraw)
0189                     
0190                     histo, syst = self.makeHist(name, sectorRange, coordinate, plotNumber) 
0191                     histo.SetMarkerColor(self.colors[name])
0192                     histo.SetMarkerStyle(self.markers[name])
0193                     if self.markers[name] == 0:
0194                         histo.SetMarkerSize(0)
0195                         histo.SetLineColor(self.colors[name])
0196                         histo.SetLineWidth(2)
0197                         
0198                     histo.Draw(drawMode)
0199                     histos.append(histo)
0200                     if self.markers[name] != 0:
0201                         legend.AddEntry(histo, self.labels[name], "p")
0202                     else:
0203                         legend.AddEntry(histo, self.labels[name], "l")
0204                         
0205                     if self.hasSystematics[name]:
0206                         syst.SetFillColor(self.colors[name])
0207                         syst.SetFillStyle(3354)
0208                         syst.Draw("02same")
0209                         systGraphs.append(syst)
0210                     
0211                     if self.hitNumbers[name] != None:
0212                         labels = self.makeHitNumbers(name, sectorRange, coordinate) 
0213                         allLabels.extend(labels)
0214                         for label in labels:
0215                             label.Draw("same")
0216                 legend.Draw()
0217                 self.canvas.Update()
0218                 
0219                 cmsText = ROOT.TLatex(0.16,0.96,self.title)
0220                 cmsText.SetTextFont(42)
0221                 cmsText.SetNDC()
0222                 cmsText.Draw("same")
0223                 
0224                 import os
0225                 if not os.path.isdir(self.outPath):
0226                     os.makedirs(self.outPath)
0227                 
0228                 self.canvas.SaveAs("{}/results_{}_{}.pdf".format(self.outPath, coordinate, self.granularity.names[coordinate][plotNumber]))
0229                 self.canvas = None
0230                 legend = None
0231                 histos = None
0232                 plotNumber += 1
0233 
0234 def main():
0235     pass
0236 
0237 
0238 if __name__ == "__main__":
0239     main()