Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
import ROOT
ROOT.gROOT.SetBatch(True)
from setTDRStyle import setTDRStyle


from granularity import *


class ValidationPlotter:
    def __init__(self):
        setTDRStyle()
        self.inFiles = {}
        self.labels = {}
        self.colors = {}
        self.markers = {}
        self.outPath = None
        self.granularity = standardGranularity
        self.validationGranularity = validationGranularity

        self.order = []
        
    def addInputFile(self, label, inFile, color=None, marker=20):
        self.order.append(label)
        self.inFiles[label] = inFile
        self.labels[label] = label
        self.markers[label] = marker
        if color != None:
            self.colors[label] = color
        else:
            # choose first not occupied color (other than white)
            for autoColor in range(1,100):
                if autoColor not in self.colors.values() and not autoColor == 10:
                    self.colors[label] = autoColor
                    break
    
    def setGranularity(self, granularity):
        self.granularity = granularity
    
    def setOutputPath(self, outPath):
        self.outPath = outPath
        
    def convertName(self, name):
        out = name.replace("Bpix", "BPIX")
        out = out.replace("Fpix", "FPIX")
        out = out.replace("Plus", "+")
        out = out.replace("Minus", "-")
        out = out.replace("Fpix", "FPIX")
        out = out.replace("Tib", "TIB")
        out = out.replace("Tob", "TOB")
        out = out.replace("Tid", "TID")
        out = out.replace("Tec", "TEC")
        out = out.replace("Layer", " L")
        out = out.replace("Ring", " R")
        out = out.replace("Stereo", "S")
        out = out.replace("Rphi", "R") # different from Ring, this one does not add a space in front
        out = out.replace("In", "i")
        out = out.replace("Out", "o")
        return out
    
    def plotHist(self, folder, name, title, hists, twoDimensional=False):
        self.canvas = ROOT.TCanvas("canvas", "canvas", ROOT.gStyle.GetCanvasDefW(),ROOT.gStyle.GetCanvasDefH())
        ROOT.gPad.SetRightMargin(0.10)
        if twoDimensional:
            ROOT.gPad.SetRightMargin(0.2)
            
        
        legend = ROOT.TLegend(0.2,0.7,0.9,0.90)
        legend.SetFillColor(0)
        legend.SetFillStyle(0)
        legend.SetTextSize(0.03)
        legend.SetMargin(0.15)
        legend.SetNColumns(2)
        legend.SetBorderSize(0)
        
        normalize = False
        if len (hists) > 1:
            normalize = True
        

        firstHist = True
        scaleHist = None
        maximum = 0
        for hist, label in hists:
            
            n = int(hist.Integral())
            mu = hist.GetMean()
            sigma = hist.GetRMS()
            
            if normalize:
                hist.Scale(1./hist.Integral())
            
            if hist.GetMaximum() > maximum:
                maximum = hist.GetMaximum()
            
            if firstHist:
                scaleHist = hist
                addDraw = ""
                firstHist = False
            else:
                addDraw = "same"
            
            if not twoDimensional:
                if self.markers[label] != 0:
                    drawMode = "P0%s"%(addDraw)
                else:
                    drawMode = "hist%s"%(addDraw)
            else:
                drawMode = "COLZ"
                
            scaleHist.SetMaximum(maximum*1.5)
            scaleHist.SetMinimum(0)
            
            hist.Draw(drawMode)
            
            legText = "#splitline{{{label}}}{{N={n:.2E},#mu={mu:.2f},RMS={sigma:.2f}}}".format(label=label,n=n, mu=mu,sigma=sigma)
            
            if self.markers[label] != 0:
                legend.AddEntry(hist, legText, "p")
            else:
                legend.AddEntry(hist, legText, "l")
        
        if not twoDimensional:
            legend.Draw()
        
        cmsText = ROOT.TLatex(0.26,0.96,title)
        cmsText.SetTextFont(42)
        cmsText.SetNDC()
        cmsText.Draw("same")
        
        import os
        if not os.path.isdir(self.outPath):
            os.makedirs(self.outPath)
        if not os.path.isdir(self.outPath+"/"+folder):
            os.makedirs(self.outPath+"/"+folder)
        self.canvas.SaveAs("{}/{}/{}.pdf".format(self.outPath, folder, name))
        self.canvas = None
            
        
        
    def makeResidualPlot(self, sectorNumber, coordinate):
        # residual
        hists = []
        for label in self.order:
            fi = ROOT.TFile(self.inFiles[label], "READ")
            hist = fi.Get("ApeEstimator1/Sector_{sectorNumber}/Results/h_Res{coordinate}".format(sectorNumber=sectorNumber, coordinate=coordinate))
            hist.SetLineColor(self.colors[label])
            hist.SetMarkerColor(self.colors[label])
            hist.SetMarkerStyle(self.markers[label])
            hist.SetDirectory(0)
            if self.markers[label] == 0:
                hist.SetMarkerSize(0)
                hist.SetLineWidth(2)
                
            hists.append((hist, label))
            nameHist = fi.Get("ApeEstimator1/Sector_{sectorNumber}/z_name".format(sectorNumber=sectorNumber))
            nameHist.SetDirectory(0)
            title = self.convertName(nameHist.GetTitle())
            fi.Close()
            
        name = "Sector_{sectorNumber}_Res{coordinate}".format(sectorNumber=sectorNumber, coordinate=coordinate)
        
        self.plotHist("residuals", name, title, hists)
        
        
        # normalized residual
        hists = []
        for label in self.order:
            fi = ROOT.TFile(self.inFiles[label], "READ")
            hist = fi.Get("ApeEstimator1/Sector_{sectorNumber}/Results/h_NorRes{coordinate}".format(sectorNumber=sectorNumber, coordinate=coordinate))
            hist.SetLineColor(self.colors[label])
            hist.SetMarkerColor(self.colors[label])
            hist.SetMarkerStyle(self.markers[label])
            hist.SetDirectory(0)
            if self.markers[label] == 0:
                hist.SetMarkerSize(0)
                hist.SetLineWidth(2)
                
            hists.append((hist, label))
            nameHist = fi.Get("ApeEstimator1/Sector_{sectorNumber}/z_name".format(sectorNumber=sectorNumber))
            nameHist.SetDirectory(0)
            title = self.convertName(nameHist.GetTitle())
            fi.Close()
        name = "Sector_{sectorNumber}_NorRes{coordinate}".format(sectorNumber=sectorNumber, coordinate=coordinate)
        
        self.plotHist("residuals", name, title, hists)
        
    def makeTrackPlot(self,histName, twoDimensional=False):
        hists = []
        for label in self.order:
            fi = ROOT.TFile(self.inFiles[label], "READ")
            hist = fi.Get("ApeEstimator2/TrackVariables/{histName}".format(histName=histName))
            hist.SetLineColor(self.colors[label])
            hist.SetMarkerColor(self.colors[label])
            hist.SetMarkerStyle(self.markers[label])
            hist.SetDirectory(0)
            if self.markers[label] == 0:
                hist.SetMarkerSize(0)
                hist.SetLineWidth(2)
            fi.Close()
            if twoDimensional:
                self.plotHist("tracks", histName+"_"+label, label, [(hist, label),], twoDimensional=True)
            else:
                hists.append((hist, label))
        if len(hists) > 0:
            self.plotHist("tracks", histName, histName, hists, twoDimensional=twoDimensional)
            
    def makeHitsPlot(self, sectorNumber, histName, twoDimensional=False):
        hists = []
        for label in self.order:
            fi = ROOT.TFile(self.inFiles[label], "READ")
            sectorName = fi.Get("ApeEstimator2/Sector_{sector}/z_name".format(sector=sectorNumber)).GetTitle()
            hist = fi.Get("ApeEstimator2/Sector_{sector}/{histName}".format(sector=sectorNumber,histName=histName))
            hist.SetLineColor(self.colors[label])
            hist.SetMarkerColor(self.colors[label])
            hist.SetMarkerStyle(self.markers[label])
            hist.SetDirectory(0)
            fi.Close()
            if self.markers[label] == 0:
                hist.SetMarkerSize(0)
                hist.SetLineWidth(2)
            
            if twoDimensional:
                self.plotHist("hits"+"/{}".format(sectorName), histName+"_"+label, "{}: ".format(sectorName)+histName+" "+label, [(hist, label),], twoDimensional=True)
            else:
                hists.append((hist, label))
        if len(hists) > 0:
            self.plotHist("hits"+"/{}".format(sectorName), histName, "{}: ".format(sectorName)+histName, hists, twoDimensional=twoDimensional)
            
    
    
    def draw(self):
        for coordinate in self.granularity.sectors.keys():
            rangeList = self.granularity.sectors[coordinate]
            for first, last in rangeList:
                for i in range(first, last+1):
                    self.makeResidualPlot(i, coordinate)
                    
        self.makeTrackPlot("h_hitsSize")
        self.makeTrackPlot("h_hitsValid")
        self.makeTrackPlot("h_hitsInvalid")
        self.makeTrackPlot("h_hits2D")
        self.makeTrackPlot("h_layersMissed")
        self.makeTrackPlot("h_hitsPixel")
        self.makeTrackPlot("h_hitsStrip")
        self.makeTrackPlot("h_charge")
        self.makeTrackPlot("h_chi2")
        self.makeTrackPlot("h_ndof")
        self.makeTrackPlot("h_norChi2")
        self.makeTrackPlot("h_prob")
        self.makeTrackPlot("h_eta")
        self.makeTrackPlot("h_etaErr")
        self.makeTrackPlot("h_theta")
        self.makeTrackPlot("h_phi")
        self.makeTrackPlot("h_phiErr")
        self.makeTrackPlot("h_d0Beamspot")
        self.makeTrackPlot("h_d0BeamspotErr")
        self.makeTrackPlot("h_dz")
        self.makeTrackPlot("h_dzErr")
        self.makeTrackPlot("h_pt")
        self.makeTrackPlot("h_ptErr")
        self.makeTrackPlot("h_meanAngle")
        self.makeTrackPlot("h_hitsGood")
        # these don't have several histograms in one plot
        self.makeTrackPlot("h2_meanAngleVsHits", twoDimensional=True)
        self.makeTrackPlot("h2_hitsGoodVsHitsValid", twoDimensional=True)
        self.makeTrackPlot("h2_hitsPixelVsEta", twoDimensional=True)
        self.makeTrackPlot("h2_hitsPixelVsTheta", twoDimensional=True)
        self.makeTrackPlot("h2_hitsStripVsEta", twoDimensional=True)
        self.makeTrackPlot("h2_hitsStripVsTheta", twoDimensional=True)
        self.makeTrackPlot("h2_ptVsTheta", twoDimensional=True)
        
        rangeList = self.validationGranularity.sectors["X"]
        for first, last in rangeList:
            for i in range(first, last+1):
                # Get list of plots per sector, as pixel sectors have different plots
                # We get the list from one of the result files, the rest should have the same structure
                directoryFile = ROOT.TFile(self.inFiles[self.order[0]], "READ")
                directory = directoryFile.GetDirectory("ApeEstimator2/Sector_{}".format(i))
                
                for histObject in directory.GetListOfKeys():
                    histName = histObject.GetName()
                    if histName.startswith("h_"): # 1D hist
                        self.makeHitsPlot(i, histName)
                    elif histName.startswith("h2_"):
                        self.makeHitsPlot(i, histName, twoDimensional=True)

                directoryFile.Close()
                

def main():
    pass


if __name__ == "__main__":
    main()