示例#1
0
def makePlot(ratios, saveName, yTile):
    newCan = TCanvas('can', 'can', 500, 500)
    newCan.SetGrid()

    leg = prepareLegend('topRight')
    leg.SetHeader('Track p_{T} [GeV]')

    for i, plot in enumerate(ratios):
        plot.SetMinimum(0)
        plot.SetMaximum(1.5)
        if i == 0:
            plot.Draw('Phist')
        else:
            plot.Draw('Psame hist')

        plot.GetYaxis().SetTitleOffset(1.4)
        plot.GetYaxis().SetTitle('Ratio ' + yTile)
        plot.GetXaxis().SetRangeUser(0, 4)
        leg.AddEntry(plot, plot.GetName().split('_')[-1], 'lp')

    leg.Draw()
    newCan.SaveAs('ratios/' + saveName + '.pdf')
示例#2
0
def drawMultigraph(legendPosition, title, saveName, geometries, graphDict):

    newCan = TCanvas("newCan" + title + rand_uuid(), "", 500, 500)
    newCan.SetLeftMargin(0.15)

    smallestYvalue = 999.0
    largestYvalue = -11.0

    theGraph = TMultiGraph(rand_uuid(), rand_uuid())
    leg = prepareLegend(legendPosition)
    for geometry in geometries:
        # find min and max of the TGraphs ... kinda defeats the point of the multigraph ... but yeah ...
        minX = Double(0.)
        minY = Double(0.)
        maxY = Double(0.)
        dummy = graphDict[geometry].GetPoint(0, minX, minY)
        dummy = graphDict[geometry].GetPoint(graphDict[geometry].GetN() - 1,
                                             minX, maxY)
        if float(minY) < smallestYvalue:
            smallestYvalue = minY
        if float(maxY) > largestYvalue:
            largestYvalue = maxY

        theGraph.Add(graphDict[geometry], 'p')
        theGraph.SetTitle(title)
        leg.AddEntry(graphDict[geometry], '{0} mm'.format(geometry), 'lp')
    theGraph.Draw('a')
    theGraph.GetHistogram().GetYaxis().SetTitleOffset(1.75)
    leg.Draw()
    newCan.SaveAs(saveName)

    # Draw with log y
    theGraph.GetHistogram().SetMinimum(smallestYvalue / 5)
    theGraph.GetHistogram().SetMaximum(largestYvalue * 5)
    newCan.SetLogy(1)
    saveName = saveName.replace(".pdf", "_log.pdf")
    newCan.SaveAs(saveName)
def main(inputFile, outputDirBase):

    outputDirBase = appendSlash(outputDirBase)
    checkDir(outputDirBase)

    # open file
    iFile = TFile.Open(inputFile)

    ptRanges = [
        #[0,2],
        [2, 5],
        [6, 10],
        [11, 30],
        [31, 50]
    ]
    etaRanges = [[0, 0.2], [0.2, 0.4], [0.4, 0.8], [0.8, 1.0], [1.0, 1.2],
                 [1.2, 1.4], [1.4, 1.6], [1.6, 1.8], [1.8, 2.0]]

    parameters = {
        'ptRes': {
            'title': 'p_{T} resolution',
            'units': '',
            'label': '#deltap_{T}/p_{T}'
        },
        'z0Res': {
            'title': 'z0 resolution',
            'units': '[mm]',
            'label': '#deltaz_{0}'
        },
        'ptResRaw': {
            'title': 'p_{T} resolution',
            'units': '[GeV]',
            'label': '#deltap_{T}'
        },
        #'d0Res'   : {'title' : 'd0 resolution' , 'units' : '[mm]', 'label': '#deltad_{0}'},

        ##'phiRes'  : {'title' : '#phi resolution',        'units' : '[deg]',      'label' : '#delta#phi'},
        ##'CtgThetaRes': {'title' : 'cot(#theta) resolution', 'units' : '',      'label' : '#deltacot(#theta)'},
    }

    branchNames = [
        #"TruthTrack",
        "Track",
        #"PBMatchedTracks",
        "TracksFromHit30",
        "SmearedTracksFromHits",
        #"PBMatchedHitTracks",
    ]

    for branch in branchNames:
        outputDir = appendSlash(outputDirBase + branch)
        checkDir(outputDir)

        for par in parameters.keys():

            ##############################################
            # Make 1d resolution plot across all eta range
            ##############################################
            basicCan = TCanvas(branch + par + "basicCan", "", 500, 500)
            basicRes = iFile.Get(branch + '_' + par)
            basicRes.Fit(
                "gaus", "MQ"
            )  # M: "improve fit", Q: "quiet" (no printing), O: "Don't draw fit or histo
            theFit = basicRes.GetFunction("gaus")
            basicCan.SetLogy()
            basicRes.Draw()
            theFit.Draw('same')
            basicCan.SaveAs(outputDir + par + '_basic.pdf')

            ##########################################################
            # Make proper resolution plots in pT and eta slices from 3D plot
            ##########################################################
            plotName = branch + '_' + par + '_pt_eta'
            resPlot = iFile.Get(plotName)
            if not is_TH3(resPlot):
                print plotName
                print 'ERROR, {0} is not of type TH3, it is {1}'.format(
                    resPlot.GetName(), type(resPlot))
                sys.exit()

            # Create legend
            #leg = prepareLegend('bottomRight')
            leg = prepareLegend('topLeft')
            leg.SetHeader('Track p_{T} [GeV]')

            # Fit resolution, extract sigma
            graphs = []
            for n, ptRange in enumerate(ptRanges):
                graphs.append(TGraphErrors())
                for i, etaRange in enumerate(etaRanges):

                    xposition = (etaRange[0] + etaRange[1]) / 2.0
                    fitResults = extractResolution(resPlot, ptRange, etaRange,
                                                   par, outputDir)
                    yVal = fitResults['Sigma'][0]
                    yErr = fitResults['Sigma'][1]
                    if par == "phiRes":  # want phi resolution to be in degrees (to compare with tkLayout)
                        yVal *= 180.0 / PI
                        yErr *= 180.0 / PI
                    graphs[n].SetPoint(i, xposition, yVal)
                    graphs[n].SetPointError(i, 0, yErr)
                    graphs[n].SetMarkerColor(colours[n])
                    graphs[n].SetLineColor(colours[n])
                    graphs[n].SetMarkerStyle(markers[n])
                leg.AddEntry(graphs[n],
                             '{0} < pT < {1}'.format(ptRange[0],
                                                     ptRange[1]), 'lp')

            # Draw graphs
            can = TCanvas(branch + par + 'can', 'can', 500, 500)
            can.SetGrid()
            can.SetLogy()
            mg = TMultiGraph()
            for g in graphs:
                mg.Add(g, 'p')

            # set plot title
            plotHeader = '{0} from Delphes'.format(parameters[par]['title'])
            plotHeader = ''
            xTitle = '#eta'
            yTitle = '{0} {1}'.format(parameters[par]['label'],
                                      parameters[par]['units'])
            mg.SetTitle('{0};{1};{2}'.format(plotHeader, xTitle, yTitle))
            mg.Draw('a')
            leg.Draw()

            # Change the axis limits
            mg.GetHistogram().GetXaxis().SetNdivisions(5, 5, 0)
            mgMin = mg.GetHistogram().GetYaxis().GetXmin()
            mgMax = mg.GetHistogram().GetYaxis().GetXmax()
            if mgMax / 10 < mgMin or True:
                mg.GetHistogram().GetYaxis().SetRangeUser(
                    mgMin * 0.5, mgMax * 5)  # make space for legend

            can.SaveAs(outputDir + par + '_graphs.pdf')
示例#4
0
def numberOfTracks(ifile, PILEUP, geometry, PT=None):

    can = TCanvas("can", "can", 500, 500)

    # get histograms
    if PT:
        nRecoTracks = ifile.Get("nRecoTracksPt{0}_{1}".format(PT, geometry))
        nRecoTracksMatched = ifile.Get("nRecoTracksMatchedPt{0}_{1}".format(
            PT, geometry))
        nDelphesHits = ifile.Get("nDelphesHitsPt{0}_{1}".format(PT, geometry))
    else:
        nRecoTracks = ifile.Get("nRecoTracks_" + str(geometry))
        nRecoTracksMatched = ifile.Get("nRecoTracksMatched_" + str(geometry))
        nDelphesHits = ifile.Get("nDelphesHits_" + str(geometry))

    # stats
    baseHistogram = nDelphesHits.Clone()

    # styling
    baseHistogram.Draw()
    can.Update()
    ymax2 = gPad.GetUymax()
    xaxis = baseHistogram.GetXaxis()
    yaxis = baseHistogram.GetYaxis()
    xaxis.SetNdivisions(5, 5, 0)
    yaxis.SetTitle("Frequency")
    xaxis.SetTitle("Number of tracks")
    baseHistogram.SetLineColor(colours.blue)
    baseHistogram.SetMarkerSize(0)
    baseHistogram.SetTitle("Triplet spacing {1} mm, Pileup {0}".format(
        PILEUP, geometry))

    x_range = (0, 5000)
    if PILEUP == 0:
        x_range = (0, 500)
        REBIN = 1
    elif PILEUP == 100:
        x_range = (0, 2000)
        REBIN = 1
    elif PILEUP == 200:
        x_range = (1000, 3000)
        REBIN = 10
    else:
        REBIN = 1

    if PT:
        x_range = (0, 500)

    baseHistogram.Rebin(REBIN)
    baseHistogram.Draw(
    )  # draw again to make sure everything taken into account ...

    # Add legend and other plots
    leg = prepareLegend("topRight")
    addLegendEntry(leg, baseHistogram, "Hits")
    addPlot(nRecoTracks, colours.green, REBIN, leg, "Reco")
    addPlot(nRecoTracksMatched, colours.red, REBIN, leg, "Reco matched")
    leg.Draw()

    xaxis.SetRangeUser(x_range[0], x_range[1])
    yaxis.SetRangeUser(0, baseHistogram.GetMaximum() * 1.3)

    if PT:
        can.SaveAs(outputDir +
                   "trackComparrison_pu{0}_geometry{1}_Pt{2}.pdf".format(
                       PILEUP, geometry, PT))
        can.SaveAs(outputDir +
                   "trackComparrison_pu{0}_geometry{1}_Pt{2}.eps".format(
                       PILEUP, geometry, PT))
    else:
        can.SaveAs(
            outputDir +
            "trackComparrison_pu{0}_geometry{1}.pdf".format(PILEUP, geometry))
        can.SaveAs(
            outputDir +
            "trackComparrison_pu{0}_geometry{1}.eps".format(PILEUP, geometry))

    #efficiencyHist = nRecoTracksMatched.Clone()
    #efficiencyHist.Divide(nDelphesHits)
    #efficiency = efficiencyHist.GetMean()
    #efficiencyError = efficiencyHist.GetMeanError()
    #print '{0} pm {1}'.format(efficiency, efficiencyError)

    # Calculate mean efficiency
    efficiency = nRecoTracksMatched.GetMean() / nDelphesHits.GetMean()
    efficiencyError = efficiency * math.sqrt(
        (nRecoTracksMatched.GetMeanError() / nRecoTracksMatched.GetMean())**2 +
        (nDelphesHits.GetMeanError() / nDelphesHits.GetMean())**2)
    #print '{0} pm {1}'.format(efficiency, efficiencyError)

    # Calculate mean fake rate
    nFakesMean = nRecoTracks.GetMean() - nRecoTracksMatched.GetMean()
    nFakesError = math.sqrt(nRecoTracks.GetMeanError()**2 +
                            nRecoTracksMatched.GetMean()**2)

    fakeRate = nFakesMean / (nRecoTracks.GetMean())
    fakeRateError = fakeRate * math.sqrt(
        (nFakesError / nFakesMean)**2 +
        (nRecoTracks.GetMeanError() / nRecoTracks.GetMean()))
    fakeRateError = 0

    return [efficiency, efficiencyError, fakeRate, fakeRateError]
示例#5
0
def fakeRates(ifile, PILEUP, geometries, label):
    '''
    Create plot of fake rate as a function of <label> (e.g. pT) 
    Fake rate = number of fakes / number of reco tracks [in a given pT bin] 
    (i.e. the fraction of reconstructed tracks that are fake)
    '''
    can = TCanvas("can", "can", 500, 500)

    fakeRates = {}
    leg = prepareLegend('topLeft')
    for geometry in geometries:
        nReco = ifile.Get("recoTrack{0}_{1}".format(label, geometry)).Clone()
        nReco.Sumw2()
        nRecoFake = ifile.Get("recoTrack{0}_fake_{1}".format(
            label, geometry)).Clone()
        nRecoFake.Sumw2()

        if label == "Pt":
            REBIN = 10
        elif label == "Eta":
            REBIN = 2

        nReco.Rebin(REBIN)
        nRecoFake.Rebin(REBIN)

        # rebin for variable bin widths
        nReco = rebin_plot(nReco, binsarray)
        nRecoFake = rebin_plot(nRecoFake, binsarray)

        fakeRate = TGraphAsymmErrors(nRecoFake, nReco)
        #fakeRate = nRecoFake.Clone()
        #fakeRate.Divide(nReco)
        fakeRates[geometry] = fakeRate

        xaxis = fakeRate.GetXaxis()
        yaxis = fakeRate.GetYaxis()
        if label == "Pt":
            xaxis.SetRangeUser(0, 100)
            xaxis.SetTitle("Reconstructed Track p_{T} [GeV]")
        elif label == "Eta":
            xaxis.SetRangeUser(-2.5, 2.5)
            xaxis.SetTitle("Reconstructed Track #eta")

        # y-range
        if PILEUP > 700:
            yaxis.SetRangeUser(0, 0.3)
        else:
            yaxis.SetRangeUser(0, 0.05)
        yaxis.SetTitleOffset(1.5)

        yaxis.SetTitle("Fake Rate")
        fakeRate.SetTitle("Pileup {0}".format(PILEUP))

        leg.AddEntry(fakeRate, "{0} mm".format(geometry), "lp")
        fakeRate.SetMarkerColor(cols[geometry])
        fakeRate.SetLineColor(cols[geometry])

        if geometry == 10:
            fakeRate.Draw("APE")
        else:
            fakeRate.Draw("PEsame")

    leg.Draw()
    can.SaveAs(outputDir + "fakeRate_{0}_pu{1}.pdf".format(label, PILEUP))
    can.SaveAs(outputDir + "fakeRate_{0}_pu{1}.eps".format(label, PILEUP))
示例#6
0
def fakeRatePerSpacing(path, geometry, pileups, label="Pt"):
    '''
    Create plot of fake rate as a function of <label> (e.g. pT)
    for a given triplet spacing, varying pileup
    '''
    can = TCanvas("can" + rand_uuid(), "can", 500, 500)
    fakeRates = {}

    leg = prepareLegend('topRight')
    leg = TLegend(0.725, 0.725, .98, .98)
    leg.SetTextSize(TEXT_SIZE)
    leg.SetHeader('ttbar + pileup')

    counter = 0
    for pu in pileups:
        #print 'getting input histograms'
        fName = path + "hits_ttbar_pu{0}_multiGeometry.root".format(pu)
        ifile = TFile.Open(fName)
        nReco = ifile.Get("recoTrack{0}_{1}".format(label, geometry)).Clone()
        nReco.Sumw2()
        nRecoFake = ifile.Get("recoTrack{0}_fake_{1}".format(
            label, geometry)).Clone()
        nRecoFake.Sumw2()

        # rebin and create fake rate
        #print 'rebin'
        nReco = rebin_plot(nReco, binsarray)
        nRecoFake = rebin_plot(nRecoFake, binsarray)
        #print 'create rate'
        fakeRate = TGraphAsymmErrors(nRecoFake, nReco)
        fakeRate.SetName(fakeRate.GetName() + rand_uuid())

        fakeRates[pu] = fakeRate

        #print 'style'
        xaxis = fakeRate.GetXaxis()
        yaxis = fakeRate.GetYaxis()
        yaxis.SetNdivisions(5, 5, 0)
        xaxis.SetRangeUser(0, 100)
        xaxis.SetTitle("Reconstructed Track p_{T} [GeV]")
        yaxis.SetRangeUser(0, 0.05)
        yaxis.SetTitleOffset(1.5)
        yaxis.SetTitle("Fake Rate")
        fakeRate.SetTitle('')
        myText(0.25, 0.9, 'Triplet spacing: 30 mm', TEXT_SIZE)

        # colour
        if counter == 0:
            icol = colours.blue
        elif counter == 1:
            icol = colours.orange
        elif counter == 2:
            icol = colours.red
        fakeRate.SetMarkerColor(icol)
        fakeRate.SetLineColor(icol)

        leg.AddEntry(fakeRate, "#LT#mu#GT = {0}".format(pu), "lp")

        if counter == 0:
            fakeRate.Draw("APE")
        else:
            fakeRate.Draw("PE same")
        #fakeRate.GetHistogram().GetYaxis().SetTitleOffset(1.75)
        fakeRate.GetHistogram().GetYaxis().SetTitleOffset(Y_AXIS_OFFSET)
        counter += 1

    leg.Draw()
    can.SaveAs('fakeRate{0}mm.pdf'.format(geometry))
    can.SaveAs('fakeRate{0}mm.eps'.format(geometry))
示例#7
0
def efficiency(ifile, PILEUP, geometries, label="Pt"):
    '''
    Plot reconstruction efficiency for different triplet spacing
    '''

    can = TCanvas("can", "can", 500, 500)

    leg = prepareLegend("bottomRight")
    #leg = prepareLegend("bottomLeft")
    ratios = {}
    for geometry in geometries:

        #print 'pu, geo', PILEUP, geometry

        # Number of matched tracks in given pT bin
        denominatorLabel = "nHits{0}_{1}".format(label, geometry)
        nHitsPt = ifile.Get(denominatorLabel).Clone()
        nHitsPt.Sumw2()
        #drawAndSave(nHitsPt, "nHitsPt.pdf")

        # Number of true tracks as a function of pT
        #recoTrackPt_true = ifile.Get("recoTrackPt_true_{0}".format(geometry)).Clone()
        numeratorLabel = "recoTrackHit{0}_true_{1}".format(label, geometry)
        recoTrackPt_true = ifile.Get(numeratorLabel).Clone()
        recoTrackPt_true.Sumw2()

        #print denominatorLabel, numeratorLabel
        #drawAndSave(recoTrackPt_true, "recoTrackPt_true.pdf")

        # Rebin
        REBIN = 1
        recoTrackPt_true.Rebin(REBIN)
        nHitsPt.Rebin(REBIN)

        #binInfo(nHitsPt, recoTrackPt_true)

        # Reconstruction efficiency
        UseTGraph = False
        UseTGraph = True
        if UseTGraph:
            recoEfficiency = TGraphAsymmErrors(recoTrackPt_true, nHitsPt)
        else:
            recoEfficiency = recoTrackPt_true.Clone()
            recoEfficiency.Divide(nHitsPt)
        recoEfficiency.SetTitle("Pileup {0}".format(PILEUP))
        recoEfficiency.SetMarkerColor(cols[geometry])
        recoEfficiency.SetLineColor(cols[geometry])
        yaxis = recoEfficiency.GetYaxis()
        xaxis = recoEfficiency.GetXaxis()
        if label == "Pt":
            xaxis.SetRangeUser(0, 50)
            yaxis.SetRangeUser(0.8, 1.1)
            xaxis.SetTitle("Track (hit) p_{T} [GeV]")
        elif label == "EtaPt2":
            xaxis.SetRangeUser(-3, 3)
            xaxis.SetTitle("Track (hit) #eta")
            #yaxis.SetRangeUser(0.8, 1.1)

        yaxis.SetTitle("Reconstruction efficiency")
        ratios[geometry] = recoEfficiency

        if geometry == 10:
            if UseTGraph:
                recoEfficiency.Draw("APEl")
            else:
                recoEfficiency.Draw("PEl")
        else:
            recoEfficiency.Draw("PElsame")

    for geometry in geometries:

        leg.AddEntry(ratios[geometry], "{0} mm".format(geometry), 'lp')

    leg.Draw()
    can.SaveAs(outputDir + "efficiency_{0}_pu{1}.pdf".format(label, PILEUP))
    can.SaveAs(outputDir + "efficiency_{0}_pu{1}.eps".format(label, PILEUP))
示例#8
0
def main():

    pileup = ["py8_pp_minbias_pu0.root"]
    signals = [
        "mg_pp_tth_pu0.root",
        #"mg_pp_tt_nlo_pu0.root",
        "mg_pp_hh_pu0.root",
    ]

    toPlot = {
        #"allTrackEta": {'xrange' : [-10, 10], 'xtitle' : 'Truth Track #eta', 'logy' : 1},
        "track1Eta": {
            'xrange': [-6, 6],
            'xtitle': 'Truth Track 1 #eta',
            'logy': 1
        },
        #"allTrackPt": {'xrange' : [0, 100], 'xtitle' : 'Truth Track p_{T} [GeV]', 'logy' : 1},
        "track1Pt": {
            'xrange': [0, 150],
            'xtitle': 'Truth Track 1 p_{T} [GeV]',
            'logy': 1
        },
        "track2Pt": {
            'xrange': [0, 100],
            'xtitle': 'Truth Track 2 p_{T} [GeV]',
            'logy': 1
        },
        "track3Pt": {
            'xrange': [0, 100],
            'xtitle': 'Truth Track 3 p_{T} [GeV]',
            'logy': 1
        },
        "track4Pt": {
            'xrange': [0, 100],
            'xtitle': 'Truth Track 4 p_{T} [GeV]',
            'logy': 1
        }
    }

    colz = {
        "py8_pp_minbias_pu0.root": {
            'col': colours.blue,
            'leg': 'Minbias'
        },
        "mg_pp_tth_pu0.root": {
            'col': colours.orange,
            'leg': 'ttH'
        },
        "mg_pp_tt_nlo_pu0.root": {
            'col': colours.purple,
            'leg': 'ttbar'
        },
        "mg_pp_hh_pu0.root": {
            'col': colours.red,
            'leg': 'HH'
        }
    }

    # open f*****g files
    files = {}
    for f in signals + pileup:
        files[f] = TFile.Open(STORE + f)

    can = TCanvas("can", "can", 500, 500)
    for plot in toPlot.keys():

        storedPlots = {}
        counter = 0
        leg = prepareLegend('topRight')
        for sig in pileup + signals:

            style = colz[sig]

            fName = STORE + sig
            #print 'opening', fName
            #print 'getting plot', plot
            h = files[sig].Get("TruthTrack_" + plot)
            h.Rebin(2)
            '''
            if sig == 'py8_pp_minbias_pu0.root':
                h.Rebin(10)
            else:
                h.Rebin(2)
            '''
            storedPlots[sig] = h
            h.SetMarkerColor(style['col'])
            h.SetLineColor(style['col'])
            xaxis = h.GetXaxis()
            yaxis = h.GetYaxis()
            xaxis.SetRangeUser(*toPlot[plot]['xrange'])
            xaxis.SetTitle(toPlot[plot]['xtitle'])
            yaxis.SetTitle('Frequency')
            print yaxis.GetXmin(), h.GetMinimum()
            #yaxis.SetRangeUser(yaxis.GetXmin(), yaxis.GetXmax()*1.1)  # increase y range by 10%
            h.SetMaximum(h.GetMaximum() * 4)
            h.SetMinimum(1e-3)
            leg.AddEntry(h, style['leg'], 'lp')

            myText(0.2, 0.8, '#sqrt{s}=100 TeV', TEXT_SIZE)

            can.SetLogy(toPlot[plot]['logy'])

            if counter == 0:
                h.Draw('hist e2')
            else:
                h.Draw('hist e2 same')
            counter += 1
        leg.Draw()
        can.SaveAs("particleProperties/" + plot + '.pdf')
        can.SaveAs("particleProperties/" + plot + '.eps')
        '''
        counter = 0
        for sig in signals:
            print type(storedPlots[sig])
            if counter == 0:
                storedPlots[sig].Draw()
            else:
                storedPlots[sig].Draw('same')
        '''

    print ''
示例#9
0
def main():

    trackParameters = ['z0res']  # variableMap.keys() testing
    tripletSpacings = [20, 25, 30, 35, 40, 50]  # Layer spacings to consider
    barrelLayers = [1, 2, 3, 4, 5]  # Triplet in barrel layer?
    region = 'triplet'  # could be tracker, outer, inner
    scattering = "withMS"

    # Make canvas and style
    newCan = TCanvas('can', 'can', 800, 600)
    newCan.cd()
    newCan.SetLogy()
    newCan.SetGrid()

    #barrelLayers = [1]
    #tripletSpacings = [50]

    # make plots for each tracker layout
    for variable in trackParameters:
        for layer in barrelLayers:
            for spacing in tripletSpacings:

                # open the ROOT File, get the canvas
                path = RESULTS_PATH + '/results_FCCtriplet_{0}barrel{1}mm/'.format(
                    layer, spacing)
                fName = "{0}_{1}_{2}_Pt000".format(
                    variable, region,
                    scattering)  # Note also can have P000 (for momentum)
                f = TFile.Open(path + fName + '.root')
                tempCan = f.Get(fName)

                # Extract possible momentum values from list of primitives
                primList = tempCan.GetListOfPrimitives()
                primNames = [x.GetName() for x in primList]
                momentumValues = [
                    float(x.split('_')[-1]) for x in primNames if 'eta' in x
                ]
                print momentumValues

                puGraphs = []
                fracGraphs = []

                leg = prepareLegend('topRight')
                leg.SetHeader('Track p_{T} [GeV]')

                for prim in primList:
                    if is_profile(prim):

                        # For each primitive (TProfile) make two new plots:
                        # One for effective pileup, and another for fraction of tracks unambiguously assigned to the PV
                        # TODO: incorporate timing resolution?

                        # Extract existing plot information
                        mColor = prim.GetMarkerColor()
                        mStyle = prim.GetMarkerStyle()
                        mSize = prim.GetMarkerSize() / 2.0

                        graphData = extractBinInfo(prim)
                        pprint(graphData)

                        puGraphs.append(TGraphErrors())
                        puGraphs[-1].SetMarkerColor(mColor)
                        puGraphs[-1].SetMarkerStyle(mStyle)
                        puGraphs[-1].SetMarkerSize(mSize)
                        puGraphs[-1].SetLineColor(mColor)

                        fracGraphs.append(TGraphErrors())
                        fracGraphs[-1].SetMarkerColor(mColor)
                        fracGraphs[-1].SetMarkerStyle(mStyle)
                        fracGraphs[-1].SetMarkerSize(mSize)
                        fracGraphs[-1].SetLineColor(mColor)

                        trackPt = prim.GetName().split('_')[-1]
                        leg.AddEntry(puGraphs[-1], trackPt, 'lp')

                        counter = 0
                        for ibin in range(1, prim.GetNbinsX() + 1):
                            resolution = graphData[ibin]['yvalue']
                            error = graphData[ibin]['error']
                            eta = graphData[ibin]['xvalue']

                            effPU = resolution / Z_VERTEX_SPACING
                            effPUerr = error / Z_VERTEX_SPACING

                            puGraphs[-1].SetPoint(ibin, eta, effPU)
                            puGraphs[-1].SetPointError(ibin, 0, effPUerr)

                            try:
                                fracTracks = 1.0 / effPU
                                fracTracksErr = effPUerr
                                fracGraphs[-1].SetPoint(
                                    counter, eta, fracTracks)
                                counter += 1
                                #fracGraphs[-1].SetPointError(ibin, 0, fracTracksErr)
                            except ZeroDivisionError:
                                continue  # don't add point if 0

                        puGraphs[-1].Draw(
                            'AP'
                        )  # due to the mysteries of ROOTs drawing, one needs to do this first, for no reason
                        fracGraphs[-1].Draw('AP')

                        newCan.SaveAs(prim.GetName() + '.pdf')

                # declare multigraphs
                effectivePU = TMultiGraph()
                fractionTracks = TMultiGraph()

                # Add graphs to multigraph
                for g in puGraphs:
                    effectivePU.Add(g, 'p')

                for g in fracGraphs:
                    fractionTracks.Add(g, 'lp')

                # Drawing for fraction of tracks plot
                newCan.SetLogy(0)
                fractionTracks.SetTitle(
                    'Fracton of tracks being unambiguously assigned to the PV @95% CL: #sigma_{z}^{Gauss}=75 mm <#mu>=1000; #eta;Fraction'
                )
                fractionTracks.Draw('a')
                leg.Draw()
                fractionTracks.GetHistogram().GetXaxis().SetRangeUser(
                    0,
                    4)  # won't be respected since no pointes here. Thanks ROOT
                newCan.SaveAs('plots/fracTracks_{0}barrel{1}mm.pdf'.format(
                    layer, spacing))

                # Drawing for effective pileup plot
                newCan.SetLogy(1)
                location = 'L={0}, S={1}'.format(layer, spacing)
                effectivePU.SetTitle(
                    'Effective pile-up@ 95% CL: #sigma_{z}^{Gauss}=75 mm <#mu>=1000 '
                    + location + ';#eta;Effective pile-up')
                effectivePU.Draw('a')
                newCan.Update()
                effectivePU.GetHistogram().GetXaxis().SetRangeUser(0, 4)
                effectivePU.Draw('a')
                leg.Draw()
                effectivePU.GetHistogram().GetXaxis().SetRangeUser(0, 4)
                newCan.SaveAs('plots/effPu_{0}barrel{1}mm.pdf'.format(
                    layer, spacing))

                f.Close()
示例#10
0
def main():

    ifile = TFile.Open(
        '/Users/Will/Documents/fcc/trackerSW/delphes/output_ttbar_mu1000.root')
    colourDef = Colours()

    truthTrackPt = ifile.Get('truthTrack100')
    truthTrackPt.Rebin(REBIN)
    #truthTrackPt = TH1D('tracks', '', 100, 0, 100)
    '''
    for bin in range(truthTrackPt_1000.GetNbinsX()):
        if bin > 100: continue
        truthTrackPt.SetBinContent(bin, truthTrackPt_1000.GetBinContent(bin))
    truthTrackPt_1000.GetXaxis().SetRangeUser(0,200)
    truthTrackPt_1000.Draw()
    truthTrackPt.SetLineColor(kGreen)
    truthTrackPt.Draw('same')
    can.SaveAs('test.pdf')
    '''
    can = TCanvas('can', 'can', 500, 500)

    line = TF1('line', '1', 0, 100)
    line.SetLineColor(kGray)

    tGraphs = {}

    leg = prepareLegend('bottomRight', [0.7, 0.15, 0.9, 0.35])

    for i in range(0, 6):
        ptCut = (i + 1) * 5
        hName = 'truthTrackPt{0}'.format(ptCut)
        print hName
        ptAfterCut = ifile.Get(hName)
        ptAfterCut.SetLineColor(kRed)
        ptAfterCut.Rebin(REBIN)

        can.SetLogy()
        truthTrackPt.Draw()
        ptAfterCut.Draw('same')
        can.SaveAs(OUTPUT_DIR + 'tracksPt{0}.pdf'.format(ptCut))

        # to make turn on to TGraphAsymmErrors(numerator, denominator)
        ratio = TGraphAsymmErrors(ptAfterCut, truthTrackPt)

        can.SetLogy(0)
        ratio.Draw('AP')
        line.Draw('same')
        xaxis = ratio.GetXaxis()
        xaxis.SetRangeUser(0, ptCut * 3)
        xaxis.SetTitle('Truth track p_{T} [GeV]')
        yaxis = ratio.GetYaxis()
        yaxis.SetTitle('Efficiency')

        can.SaveAs(OUTPUT_DIR + 'turnOnPt{0}.pdf'.format(ptCut))

        tGraphs[ptCut] = ratio

    # now draw series of TGraphs
    ptCuts = [5, 10, 15, 20]
    colours = [
        colourDef.blue, colourDef.red, colourDef.orange, colourDef.purple
    ]
    for i, cut in enumerate(ptCuts):
        gr = tGraphs[cut]
        gr.SetLineColor(colours[i])
        gr.SetMarkerColor(colours[i])
        leg.AddEntry(gr, 'p_{T} > ' + str(cut) + ' GeV')
        if i == 0:
            gr.Draw('APl')
            gr.SetMinimum(0)
            gr.GetXaxis().SetRangeUser(0, 45)
            line.Draw('same')
            gr.Draw('Psame')
        else:
            gr.Draw('Plsame')
    leg.Draw()

    can.SaveAs(OUTPUT_DIR + 'trackTurnOn.pdf')
def main(verbose):

    branchesToCompare = [
        ('TruthTrack', 'TracksFromHit30', 'truth'),
        ('Track', 'SmearedTracksFromHits', 'smeared'),
        ('PBMatchedTracks', 'PBMatchedHitTracks', 'PBmatched'),
    ]

    plots = ['track1Pt', 'track2Pt', 'track3Pt', 'track4Pt']

    for branchPair in branchesToCompare:

        for plot in plots:
            can = TCanvas("can" + plot + branchPair[0], "can", 500, 500)
            rightmargin = 0.1
            leftmargin = 0.2

            ## Define upper pad
            upperPad = TPad("upperPad", "upperPad", 0, 0.3, 1, 1)
            PLOT_MARGINS_WITH_RATIO = (0.125, 0.05, 0.025, 0.1)
            upperPad.SetMargin(*PLOT_MARGINS_WITH_RATIO)
            upperPad.Draw()

            ## Define lower pad
            lowerPad = TPad("lowerPad", "lowerPad", 0, 0, 1, 0.3)
            lowerPad.SetTopMargin(0)
            lowerPad.Draw()
            PLOT_RATIO_MARGINS = (0.125, 0.05, 0.325, 0.05)
            lowerPad.SetMargin(*PLOT_RATIO_MARGINS)

            # general plot settings
            RATIO_Y_TITLE = 'Ratio'
            xTitle = plot + ' [GeV]'
            yTitle = 'Frequency'
            xRange = [0, 100]

            # Extract histograms
            sample = 'mg_pp_hh'
            pileup = 0
            iFileName = '/atlas/data4/userdata/wfawcett/delphes/results/fromLHE/{0}_pu{1}.root'.format(
                sample, pileup)
            iFile = TFile.Open(iFileName, "READ")
            h0 = iFile.Get("{0}_{1}".format(branchPair[0], 'track1Pt'))
            h1 = iFile.Get("{0}_{1}".format(branchPair[1], 'track1Pt'))
            REBIN = 2
            h0.Rebin(REBIN)
            h1.Rebin(REBIN)

            # histogram marker styling
            h0.SetLineColor(9)
            h0.SetMarkerStyle(22)
            h0.SetMarkerColor(9)

            h1.SetLineColor(2)
            h1.SetMarkerColor(2)
            h1.SetMarkerStyle(20)

            # histogram axis styling
            x_axis = h0.GetXaxis()
            y_axis = h0.GetYaxis()

            x_axis.SetTitle(xTitle)
            # Get rid of title in case of ratio
            x_axis.SetLabelOffset(999)
            x_axis.SetTitleOffset(999)

            y_axis.SetTitle(yTitle)
            x_axis.SetRangeUser(xRange[0], xRange[1])

            #legend
            leg = prepareLegend('topRight')
            leg.AddEntry(h0, branchPair[0], 'lp')
            leg.AddEntry(h1, branchPair[1], 'lp')

            # Drawing
            upperPad.cd()
            h0.Draw('hits')
            h1.Draw('same')
            leg.Draw()

            # lower pad
            can.cd()
            lowerPad.cd()
            ratio = plt.ratio_histogram(h0, h1, RATIO_Y_TITLE)
            ratio.SetLineColor(1)
            ratio.SetMarkerColor(1)
            ratio_y_axis = ratio.GetYaxis()
            ratio_x_axis = ratio.GetXaxis()

            ratio_x_axis.SetTitleSize(0.13)
            PLOT_RATIO_Y_AXIS_TITLE_OFFSET_RATIO = 0.425
            ratio_x_axis.SetTitleOffset(PLOT_RATIO_Y_AXIS_TITLE_OFFSET_RATIO)
            ratio_x_axis.SetLabelOffset(0.01)
            ratio_x_axis.SetTitleOffset(1)
            ratio_x_axis.SetLabelSize(0.12)

            PLOT_RATIO_Y_AXIS_LABEL_SIZE = 0.12
            ratio_y_axis.SetTitleSize(PLOT_RATIO_Y_AXIS_LABEL_SIZE)
            ratio_y_axis.SetLabelSize(PLOT_RATIO_Y_AXIS_LABEL_SIZE)
            ratio_y_axis.SetTitleOffset(PLOT_RATIO_Y_AXIS_TITLE_OFFSET_RATIO)
            ratio_y_axis.SetNdivisions(5, 5, 0)

            ratio_y_axis.SetRangeUser(0.5, 1.5)
            ratio.Draw()

            can.SaveAs('branchComparrison/{0}_{1}.pdf'.format(
                branchPair[2], plot))
            '''
示例#12
0
def main(verbose):

    BDTMode = False
    DeltaKappaMode = not BDTMode

    #pileups = range(0, 1100, 100)
    pileups = [100, 200, 1000]

    spacings = [
        "Tracks10",
        "Tracks20",
        "Tracks30",
        "Tracks40",
        "Tracks50",
    ]

    colourMap = {
        "Tracks10": colours.blue,
        "Tracks20": colours.orange,
        "Tracks30": colours.red,
        "Tracks40": colours.green,
        "Tracks50": colours.grey
    }

    bdtCuts = [
        -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5,
        0.6, 0.7, 0.8, 0.9
    ]
    deltaKappaCuts = range(20, 301, 25)
    deltaKappaCuts = [
        float(x) / 100000.0 for x in range(25, 201, 25)
    ]  # would limit to 301, but already a harsher cut is implemented

    if BDTMode:
        cutList = bdtCuts
    else:
        cutList = deltaKappaCuts

    for PILEUP in pileups:

        can = TCanvas("can" + rand_uuid(), "can", 500, 500)
        theGraphs = {}
        leg = prepareLegend("bottomLeft")
        for spacing in spacings:
            print 'Drawing for spacing', spacing
            counter = 0
            theGraphs[spacing] = TGraph()
            theGraphs[spacing].SetMarkerColor(colourMap[spacing])
            theGraphs[spacing].SetLineColor(colourMap[spacing])
            theGraphs[spacing].SetMaximum(1)
            theGraphs[spacing].SetMinimum(0.995)
            theGraphs[spacing].SetMarkerStyle(20)
            leg.AddEntry(theGraphs[spacing], spacing, 'lp')
            print "Cut\t<efficiency>\t1-<fake rate>"
            for cut in cutList:

                if BDTMode:
                    jFileName = "/atlas/data4/userdata/wfawcett/delphes/results/processedTracks_ROCscan_BDTspecific_{0}/hits_ttbar_pu{1}_multiGeometry.json".format(
                        cut, PILEUP)
                else:
                    jFileName = "/atlas/data4/userdata/wfawcett/delphes/results/processedTracks_ROCscan_deltaKappa_{0}/hits_ttbar_pu{1}_multiGeometry.json".format(
                        cut, PILEUP)
                #print 'reading', jFileName

                # load json file
                with open(jFileName) as data_file:
                    trackDict = json.load(data_file)

                # want to plot efficiency and fake rejection for tracks with pT > 2
                trackInfo = trackDict[spacing]

                # number of tracks surviving
                nFakesPt2 = float(trackInfo["FakeSurviving"]["Pt2"])
                nTruesPt2 = float(trackInfo["TrueSurviving"]["Pt2"])

                # fake rate is the fraction of (surviving) tracks that are fakes
                averageFakeRate = nFakesPt2 / (nFakesPt2 + nTruesPt2)

                # Average efficiency is fraction of true tracks surviving
                nTrueOriginalPt2 = float(trackInfo["TrueOriginal"]["Pt2"])
                averageEfficiency = nTruesPt2 / nTrueOriginalPt2

                print '{0} \t {1:.4f} \t {2:.4f}'.format(
                    cut, averageEfficiency, 1 - averageFakeRate)

                theGraphs[spacing].SetPoint(counter, averageEfficiency,
                                            1 - averageFakeRate)
                counter += 1

        #___________________________________________________________
        mg = TMultiGraph()
        for spacing in spacings:
            mg.Add(theGraphs[spacing], 'lp')
        if BDTMode:
            mg.SetTitle(
                "BDT pileup={0};Average efficiency;1 - Fake Rate".format(
                    PILEUP))
        if DeltaKappaMode:
            mg.SetTitle(
                "|#Delta#kappa| pileup={0};Average efficiency;1 - Fake Rate".
                format(PILEUP))
        mg.Draw('a')
        leg.Draw()

        if BDTMode:
            can.SaveAs("BDT_ROC_pu{0}.pdf".format(PILEUP))
        if DeltaKappaMode:
            can.SaveAs("Dk_ROC_pu{0}.pdf".format(PILEUP))