def __draw_stack(self, regions, th1d_dict, output_name):

        canvas = TCanvas("canvas", 'A basic canvas', 1000, 600)
        stack = THStack("stack", "stack")
        leg = Plotting.Create_Legend(0.60, 0.60, 0.95, 0.95)

        for region in regions:
            hist = th1d_dict[region]

            hist.SetLineColor(1)
            hist.SetLineWidth(1)
            hist.SetMarkerColor(self.__get_colour(region))
            hist.SetMarkerStyle(0)
            hist.SetFillColor(self.__get_colour(region))

            leg.AddEntry(hist, self.__get_label(region), "f")
            stack.Add(hist)

            del hist

        stack.Draw("HIST")
        stack.GetYaxis().SetTitle("Events")
        stack.GetXaxis().SetTitle("True #it{E_{T}^{miss}} [GeV]")
        leg.Draw()
        canvas.Print(output_name)
Пример #2
0
    def getStack(self, lumi, name, var, nbin, xmin, xmax, cut, options,
                 xlabel):

        hs = THStack(name, "")

        for b in self.blocks:

            AuxName = "auxStack_block_" + name + "_" + b.name
            haux = b.getTH1F(lumi, AuxName, var, nbin, xmin, xmax, cut,
                             options, xlabel)
            haux.SetFillColor(b.color)
            hs.Add(haux)
            del haux

        can_aux = TCanvas("can_%s_%s" % (name, b.name))
        can_aux.cd()
        hs.Draw()

        del can_aux

        if xmax != xmin:
            hs.GetXaxis().SetTitle(xlabel)
            b = int((xmax - xmin) / nbin)
            ylabel = "Events / " + str(b) + " GeV"
        else:
            ylabel = "# events"

        hs.GetYaxis().SetTitle(ylabel)
        return hs
Пример #3
0
def Stack(can, reverse=False):
    if can.GetPrimitive('pad_top'):
        return Stack(can.GetPrimitive('pad_top'), reverse=reverse)

    from ROOT import TH1, THStack
    stack = THStack('stack', 'stack')
    xaxislabel, yaxislabel = '', ''
    binlabels = []
    if reverse:
        the_primitives = reversed(can.GetListOfPrimitives())
    else:
        the_primitives = can.GetListOfPrimitives()
    for i in the_primitives:
        if issubclass(type(i), TH1):
            stack.Add(i)
            if not xaxislabel: xaxislabel = i.GetXaxis().GetTitle()
            if not yaxislabel: yaxislabel = i.GetYaxis().GetTitle()
            if not binlabels and i.GetXaxis().GetBinLabel(1):
                for j in range(i.GetNbinsX()):
                    binlabels.append(i.GetXaxis().GetBinLabel(j + 1))
    can.Clear()
    tobject_collector.append(stack)
    can.cd()
    stack.Draw('hist')
    stack.GetXaxis().SetTitle(xaxislabel)
    stack.GetYaxis().SetTitle(yaxislabel)
    if binlabels:
        for i in range(stack.GetXaxis().GetNbins()):
            stack.GetXaxis().SetBinLabel(i + 1, binlabels[i])
    can.Modified()
    can.Update()
    can.RedrawAxis()
    return
Пример #4
0
def plot_hist_diff(histlist1, histlist2, labellist, log, overflow, filename,
                   options):
    canv = TCanvas("c1", "c1", 800, 600)
    canv.SetTopMargin(10)
    canv.SetRightMargin(100)
    if log: gPad.SetLogy()
    histstack = THStack("stack", histlist1[0].GetTitle())
    legend = TLegend(0.76, 0.88 - 0.08 * len(histlist1), 0.91, 0.88, '', 'NDC')
    colorlist = [4, 8, 2, 6, 1]

    if options: options += " NOSTACK"
    else: options = "NOSTACK"

    maximum = 0
    for i in range(len(histlist1)):
        entries = histlist1[i].GetEntries()
        bad_entries = histlist2[i].GetEntries()
        histlist1[i].SetLineColorAlpha(colorlist[i], 0.65)
        histlist1[i].SetLineWidth(3)

        if entries: histlist1[i].Scale(1. / entries)
        if bad_entries: histlist2[i].Scale(1. / bad_entries)
        histlist1[i].Add(histlist2[i], -1.)

        nbins = histlist1[i].GetNbinsX()
        legend.AddEntry(
            histlist1[i], "#splitline{" + labellist[i] +
            "}{#splitline{%d total jets}{%d bad jets}}" %
            (entries, bad_entries), "l")

        if overflow:
            histlist1[i].SetBinContent(
                nbins, histlist1[i].GetBinContent(nbins) +
                histlist1[i].GetBinContent(nbins + 1))  #overflow
            histlist1[i].SetBinContent(
                1, histlist1[i].GetBinContent(0) +
                histlist1[i].GetBinContent(1))  #underflow

        if histlist1[i].GetMaximum() > maximum:
            maximum = histlist1[i].GetMaximum()
        histstack.Add(histlist1[i])
        #if i == 0: histlist[i].Draw(options)
        #else: histlist[i].Draw(same+options)

    histstack.SetMaximum(maximum * 1.4)
    histstack.Draw(options)
    histstack.GetXaxis().SetTitle(histlist1[0].GetXaxis().GetTitle())
    histstack.GetYaxis().SetTitle(histlist1[0].GetYaxis().GetTitle())

    legend.SetTextSize(0.02)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.Draw("SAME")
    canv.SaveAs(filename)
    if log: gPad.Clear()
    canv.Clear()
    del canv
Пример #5
0
def plotstuff2(cut1,cut2,cutname):
    events.Draw("eleClT-posClT>>h1(200,-10,10)",cut1,"goff")
    events.Draw("eleClT-posClT>>h2(200,-10,10)",cut2,"goff")

    hs = THStack("hs",cutname);
    hs.Add(gDirectory.Get("h1"))
    hs.Add(gDirectory.Get("h2"))
    hs.Draw("nostack")
    leg = TLegend(0.6,0.75,0.9,0.9)
    leg.AddEntry(gDirectory.Get("h1"),"after base cuts")
    leg.AddEntry(gDirectory.Get("h2"),"after vertexing cuts")
    leg.Draw()
    gDirectory.Get("h1").SetLineColor(1)
    gDirectory.Get("h2").SetLineColor(2)
    hs.GetXaxis().SetTitle("tEle-tPos [ns]")
    hs.GetYaxis().SetTitle("events/(0.1 ns)")
    c.Print(sys.argv[1]+".pdf")
Пример #6
0
def histo_creation(lumi2017_param, variable_param, binHist_param,
                   minHist_param, maxHist_param, titleX_param, titleY_param):

    histo = []
    legend = TLegend(0.5, 0.5, 0.9, 0.9)
    canvas = TCanvas()

    if (lumi2017_param):
        legend.SetHeader("41.53 fb-1", "C")
        canvas.SetName(variable_param + "2017")
    else:
        legend.SetHeader("35.9 fb-1", "C")
        canvas.SetName(variable_param + "2016")

    for i in range(len(MC_sample)):
        foo = TH1F("essaie{}".format(i), "essaie{}".format(i), binHist_param,
                   minHist_param, maxHist_param)
        rootfile[i].Get('events').Project("essaie{}".format(i), variable_param,
                                          "weight")
        histo.append(foo)
        histo[i].SetFillColor(color[i])
        histo[i].Scale(luminosity2017 * 1000 * cross_sec[i] / eventsN0[i])
        if (not lumi2017_param):
            histo[i].Scale(lumiRatio)
        print(histo[i].GetEntries() * lumiRatio * luminosity2017 * 1000 *
              cross_sec[i] / eventsN0[i])
        histo[i].Draw()
        legend.AddEntry(histo[i], MC_name[i], "f")

    stack = THStack(variable_param, "")
    for i in range(len(MC_sample)):
        stack.Add(histo[len(MC_sample) - (i + 1)])
    stack.Draw("HIST")
    stack.GetXaxis().SetTitle(titleX_param)
    stack.GetYaxis().SetTitle(titleY_param)
    legend.Draw()

    if (lumi2017_param):
        canvas.SaveAs(localisation + "/results/MC_" + variable_param +
                      "2017.png")
    else:
        canvas.SaveAs(localisation + "/results/MC_" + variable_param +
                      "2016.png")

    canvas.Write()
Пример #7
0
def plot_bar(histlist, axislabels, labels, norm, log, filename, options):
    canv = TCanvas("c1", "c1", 800, 600)
    canv.SetTopMargin(10)
    canv.SetRightMargin(100)
    if log: gPad.SetLogy()
    histstack = THStack("stack", histlist[0].GetTitle())
    if labels:
        legend = TLegend(0.76, 0.88 - 0.08 * len(histlist), 0.91, 0.88, '',
                         'NDC')
    colorlist = [4, 8, 2, 6, 1]

    if options: options += " NOSTACK"
    else: options = "NOSTACK"

    maximum = 0
    for i in range(len(histlist)):
        histlist[i].SetLineColorAlpha(colorlist[i], 0.65)
        histlist[i].SetLineWidth(3)
        entries = histlist[i].GetEntries()

        if entries and norm: histlist[i].Scale(1. / entries)
        if histlist[i].GetMaximum() > maximum:
            maximum = histlist[i].GetMaximum()
        if labels: legend.AddEntry(histlist[i], labels[i], "l")
        histstack.Add(histlist[i])

    histstack.SetMaximum(maximum * 1.4)
    histstack.Draw(options)
    histstack.GetXaxis().SetTitle(histlist[0].GetXaxis().GetTitle())
    histstack.GetYaxis().SetTitle(histlist[0].GetYaxis().GetTitle())
    histstack.GetXaxis().SetNdivisions(len(axislabels))
    histstack.GetXaxis().CenterLabels(True)
    for i, label in enumerate(axislabels):
        histstack.GetXaxis().ChangeLabel(i + 1, -1, -1, -1, -1, -1, str(label))

    if labels:
        legend.SetTextSize(0.02)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.Draw("SAME")
    canv.SaveAs(filename)
    if log: gPad.Clear()
    canv.Clear()
    del canv
Пример #8
0
def timing(data, leg_entries):

    """ Plot different timing delays after receiving the trigger. """

    stack = THStack('stack', 'Counts per BX')
    leg = TLegend(.8, .5, 1., .9)
    for idx, list in enumerate(data):
        h = TH1F('', '', 100, 0, 220)
        h.SetFillColor(idx+2)
        leg.AddEntry(h, leg_entries[idx], 'f')
        for val in list:
            h.Fill(val)
        stack.Add(h)
    canvas = TCanvas()
    stack.Draw()
    stack.GetXaxis().SetTitle('BX')
    stack.GetYaxis().SetTitle('Counts')
    leg.Draw()
    canvas.SaveAs('timing.pdf')
Пример #9
0
def plotstuff3(cuts,cutname):
    hs = THStack("hs",cutname);
    hs.Add(gDirectory.Get("h1"))
    leg = TLegend(0.6,0.75,0.9,0.9)
    events.Draw("eleClT-posClT>>h0(200,-10,10)",cuts[0],"goff")
    leg.AddEntry(gDirectory.Get("h0"),"after base cuts")
    hs.Add(gDirectory.Get("h0"))
    gDirectory.Get("h0").SetLineColor(1)
    #gDirectory.Get("h1").SetTitle(cutname)
    for i in range(1,len(cuts)):
        events.Draw("eleClT-posClT>>h{0}(100,-10,10)".format(i),makeCutString(cuts[0:i+1]),"goff")
        leg.AddEntry(gDirectory.Get("h{0}".format(i)),"after {0} cut".format(cutnames[i]))
        hs.Add(gDirectory.Get("h{0}".format(i)))
        gDirectory.Get("h{0}".format(i)).SetLineColor(i+1)

    hs.Draw("nostack")
    leg.Draw()
    hs.GetXaxis().SetTitle("tEle-tPos [ns]")
    hs.GetYaxis().SetTitle("events/(0.1 ns)")
    c.Print(sys.argv[1]+".pdf")
Пример #10
0
def plotstuff(cut1,cut2,cut3,cutname):
    events.Draw("eleClT-posClT>>h1(200,-10,10)",cut1,"goff")
    events.Draw("eleClT-posClT>>h2(200,-10,10)",cut2,"goff")
    events.Draw("eleClT-posClT>>h3(200,-10,10)",cut3,"goff")

    hs = THStack("hs","Effect of "+cutname+" cut");
    hs.Add(gDirectory.Get("h1"))
    hs.Add(gDirectory.Get("h2"))
    hs.Add(gDirectory.Get("h3"))
    hs.Draw("nostack")
    leg = TLegend(0.6,0.75,0.9,0.9)
    leg.AddEntry(gDirectory.Get("h1"),"passed all but this cut")
    leg.AddEntry(gDirectory.Get("h2"),"passed all cuts")
    leg.AddEntry(gDirectory.Get("h3"),"failed this cut")
    leg.Draw()
    gDirectory.Get("h1").SetLineColor(1)
    gDirectory.Get("h2").SetLineColor(4)
    gDirectory.Get("h3").SetLineColor(2)
    hs.GetXaxis().SetTitle("tEle-tPos [ns]")
    hs.GetYaxis().SetTitle("events/(0.1 ns)")
    c.Print(sys.argv[1]+".pdf")
Пример #11
0
def Stack(can,reverse=False) :
    if can.GetPrimitive('pad_top') :
        return Stack(can.GetPrimitive('pad_top'),reverse=reverse)
    
    from ROOT import TH1,THStack
    stack = THStack('stack','stack')
    xaxislabel,yaxislabel = '',''
    binlabels = []
    if reverse :
        the_primitives = reversed(can.GetListOfPrimitives())
    else :
        the_primitives = can.GetListOfPrimitives()
    for i in the_primitives :
        if issubclass(type(i),TH1) :
            stack.Add(i)
            if not xaxislabel : xaxislabel = i.GetXaxis().GetTitle()
            if not yaxislabel : yaxislabel = i.GetYaxis().GetTitle()
            if not binlabels and i.GetXaxis().GetBinLabel(1) :
                for j in range(i.GetNbinsX()) :
                    binlabels.append(i.GetXaxis().GetBinLabel(j+1))
    # The original objects are cleared from the histogram:
    can.Clear()
    tobject_collector.append(stack)

    # Set draw option of underlying histograms for automatically nice legends
    for hist in stack.GetHists() :
        hist.SetOption('f')

    can.cd()
    stack.Draw('hist')
    stack.GetXaxis().SetTitle(xaxislabel)
    stack.GetYaxis().SetTitle(yaxislabel)
    if binlabels :
        for i in range(stack.GetXaxis().GetNbins()) :
            stack.GetXaxis().SetBinLabel(i+1,binlabels[i])
    can.RedrawAxis()
    can.Modified()
    can.Update()
    return
Пример #12
0
    def ClusterSizeOneTrouble(self):
        RootDirectory = 'FTClusterMonitor'
        for files in self.ListOfFiles:
            tfile = TFile.Open(files)
            OutFileMantisse = files[:files.find(
                '-histos')] + "/" + RootDirectory + "_" + time.strftime(
                    '%y-%m-%d_%H-%M', time.localtime())
            self.CreateDir(OutFileMantisse)
            tdir = tfile.GetDirectory(RootDirectory)
            for type in {"x_position", "Channel"}:
                All = tdir.Get("Cluster_" + type + "_resolution_1Ch")
                Cell0 = tdir.Get("Cluster_" + type + "_resolution_1Ch_Cell0")
                Cell127 = tdir.Get("Cluster_" + type +
                                   "_resolution_1Ch_Cell127")
                Cell63 = tdir.Get("Cluster_" + type + "_resolution_1Ch_Cell63")
                Cell64 = tdir.Get("Cluster_" + type + "_resolution_1Ch_Cell64")
                CellNeighbour = tdir.Get(
                    "Cluster_" + type + "_resolution_1Ch_WithNeighbouringCell")

                All.SetLineColor(4)
                Cell0.SetLineColor(2)
                Cell127.SetLineColor(7)
                Cell63.SetLineColor(6)
                Cell64.SetLineColor(40)
                CellNeighbour.SetLineColor(28)
                # Standard drawing
                ClusterMoniSizeOneTroublecvs = TCanvas(
                    "ClusterSizeOneTroublecvs", "ClusterSizeOneTrouble")
                ClusterMoniSizeOneTroublecvs.SetGrid()
                ClusterMoniSizeOneTroublecvs.cd()
                All.Draw("H")
                Cell0.Draw("HSAME")
                Cell127.Draw("HSAME")
                Cell63.Draw("HSAME")
                Cell64.Draw("HSAME")
                CellNeighbour.Draw("HSAME")
                Leg = TLegend(0.11, 0.7, 0.4, 0.89)
                Leg.AddEntry(All, "All Cells", "l")
                Leg.AddEntry(Cell63, "Cell 63", "l")
                Leg.AddEntry(Cell64, "Cell 64", "l")
                Leg.AddEntry(Cell0, "Cell 0", "l")
                Leg.AddEntry(Cell127, "Cell 127", "l")
                Leg.AddEntry(CellNeighbour, "Cells with left/right neighbour",
                             "l")
                Leg.Draw()
                ClusterMoniSizeOneTroublecvs.SaveAs(
                    OutFileMantisse + "/" + (OutFileMantisse.split('/')[0]) +
                    "_" + All.GetName() + self.OutFileType)

                # Stack drawing
                Cell0.SetFillColor(2)
                Cell127.SetFillColor(7)
                Cell63.SetFillColor(6)
                Cell64.SetFillColor(40)
                CellNeighbour.SetFillColor(28)
                HistoStack = THStack("HistoStack", "Stacked 1D histograms")
                HistoStack.Add(Cell63)
                HistoStack.Add(Cell64)
                HistoStack.Add(Cell0)
                HistoStack.Add(Cell127)
                HistoStack.Add(CellNeighbour)

                ClusterMoniSizeOneTroubleStackcvs = TCanvas(
                    "ClusterSizeOneTroubleStackcvs",
                    "ClusterSizeOneTroubleStack")
                ClusterMoniSizeOneTroubleStackcvs.SetGrid()
                ClusterMoniSizeOneTroubleStackcvs.cd()
                HistoStack.Draw("H")
                HistoStack.GetXaxis().SetTitle(All.GetXaxis().GetTitle())
                HistoStack.GetYaxis().SetTitle(All.GetYaxis().GetTitle())
                #ClusterMoniSizeOneTroubleStackcvs.Update()
                All.Draw("HSAME")
                LegStack = TLegend(0.11, 0.7, 0.4, 0.89)
                LegStack.AddEntry(All, "All Cells", "l")
                LegStack.AddEntry(Cell63, "Cell 63", "f")
                LegStack.AddEntry(Cell64, "Cell 64", "f")
                LegStack.AddEntry(Cell0, "Cell 0", "l=f")
                LegStack.AddEntry(Cell127, "Cell 127", "f")
                LegStack.AddEntry(CellNeighbour,
                                  "Cells with left/right neighbour", "f")
                LegStack.Draw()
                ClusterMoniSizeOneTroubleStackcvs.SaveAs(
                    OutFileMantisse + "/" + (OutFileMantisse.split('/')[0]) +
                    "_" + All.GetName() + "_Stack" + self.OutFileType)

            # Details on cells with neighbours
            Cell1to4 = tdir.Get("Cluster_Channel_resolution_1Ch_Cell1to4")
            Cell59to62 = tdir.Get("Cluster_Channel_resolution_1Ch_Cell59to62")
            Cell65to68 = tdir.Get("Cluster_Channel_resolution_1Ch_Cell65to68")
            Cell122to126 = tdir.Get(
                "Cluster_Channel_resolution_1Ch_Cell122to126")
            CellAllOthers = tdir.Get(
                "Cluster_Channel_resolution_1Ch_AllOtherNeighbors")
            Cell1to4.SetLineColor(2)
            Cell1to4.SetFillColor(2)
            Cell59to62.SetLineColor(3)
            Cell59to62.SetFillColor(3)
            Cell65to68.SetLineColor(4)
            Cell65to68.SetFillColor(4)
            Cell122to126.SetLineColor(5)
            Cell122to126.SetFillColor(5)
            CellAllOthers.SetLineColor(6)
            CellAllOthers.SetFillColor(6)
            NeighbourStack = THStack("NeighbourStack", "Stacked 1D histograms")
            NeighbourStack.Add(Cell1to4)
            NeighbourStack.Add(Cell59to62)
            NeighbourStack.Add(Cell65to68)
            NeighbourStack.Add(Cell122to126)
            NeighbourStack.Add(CellAllOthers)

            ClusterMoniSizeOneTroubleNeighbourhoodcvs = TCanvas(
                "ClusterSizeOneTroubleNeighbourhoodcvs",
                "ClusterSizeOneTroubleNeighbourhood")
            ClusterMoniSizeOneTroubleNeighbourhoodcvs.SetGrid()
            ClusterMoniSizeOneTroubleNeighbourhoodcvs.cd()
            NeighbourStack.Draw("nostack")
            NeighbourStack.GetXaxis().SetTitle(Cell1to4.GetXaxis().GetTitle())
            NeighbourStack.GetYaxis().SetTitle(Cell1to4.GetYaxis().GetTitle())
            CellNeighbour.Draw("SAME")
            ClusterMoniSizeOneTroubleNeighbourhoodcvs.SaveAs(
                OutFileMantisse + "/" + (OutFileMantisse.split('/')[0]) +
                "_NeighboringStudy_Stack" + self.OutFileType)

            # Details on cells with/without Cluster size=4 neighbours
            #CellWithCl4Neighbour = tdir.Get("Cluster_Channel_resolution_1Ch_Cell1to4")
            CellWithCl4Neighbour = tdir.Get(
                "Cluster_Channel_resolution_1Ch_withSize4neigh")
            #CellWithoutCl4Neighbour = tdir.Get("Cluster_Channel_resolution_1Ch_Cell1to4")
            CellWithoutCl4Neighbour = tdir.Get(
                "Cluster_Channel_resolution_1Ch_withoutSize4neigh")

            CellWithCl4Neighbour.SetLineColor(2)
            CellWithCl4Neighbour.SetFillColor(2)
            CellWithoutCl4Neighbour.SetLineColor(3)
            CellWithoutCl4Neighbour.SetFillColor(3)
            Clus4NeighbourStack = THStack("Clus4NeighbourStack",
                                          "St histograms")
            Clus4NeighbourStack.Add(CellWithCl4Neighbour)
            Clus4NeighbourStack.Add(CellWithoutCl4Neighbour)
            Clus4TroubleNeighbourhoodcvs = TCanvas(
                "Clus4TroubleNeighbourhoodcvs", "Clus4TroubleNeighbourhoodcvs")
            Clus4TroubleNeighbourhoodcvs.SetGrid()
            Clus4TroubleNeighbourhoodcvs.cd()
            Clus4NeighbourStack.Draw("H")
            Clus4NeighbourStack.GetXaxis().SetTitle(
                CellWithCl4Neighbour.GetXaxis().GetTitle())
            Clus4NeighbourStack.GetYaxis().SetTitle(
                CellWithCl4Neighbour.GetYaxis().GetTitle())
            All.Draw("HSAME")
            LegClus4Size = TLegend(0.11, 0.7, 0.4, 0.89)
            LegClus4Size.AddEntry(All, "All Cells", "l")
            LegClus4Size.AddEntry(CellWithCl4Neighbour,
                                  "With size 4 neighbour ", "f")
            LegClus4Size.AddEntry(CellWithoutCl4Neighbour,
                                  "Without size 4 neighbour ", "f")
            LegClus4Size.Draw()
            Clus4TroubleNeighbourhoodcvs.SaveAs(
                OutFileMantisse + "/" + (OutFileMantisse.split('/')[0]) +
                "_CluS4NeighboringStudy_Stack" + self.OutFileType)
Пример #13
0
def main():

    extension = "pdf"

    luminosity = 44307.4
    ymin = 0
    ymax = 0.024

    data_set_names = [
        (["SZee_all_susy_2l_0jets.root",
          "SZmumu_all_susy_2l_0jets.root"], "Z#rightarrowll", 860 + 0, 23),
        (["ZZ_1in3_susy_2l_0jets.root"], "ZZ#rightarrowll#nu#nu", 416 + 3, 43),
        (["WZ_1in3_susy_2l_0jets.root"], "WZ#rightarrowl#null", 416 - 8, 33),
        (["WW_1in3_susy_2l_0jets.root"], "WW#rightarrowl#nul#nu", 416 + 0, 20),
        ([
            "ttbar_1in3_susy_2l_0jets.root", "top_1in3_susy_2l_0jets.root",
            "antitop_1in3_susy_2l_0jets.root"
        ], "Top", 800 + 4, 21),
    ]

    DATA_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Data", "SR_SUSY")

    ## Creating the plots
    gROOT.SetStyle("ATLAS")
    gROOT.ForceStyle()
    gStyle.SetErrorX(0.5)
    canvas = TCanvas("canvas", 'A basic canvas', 800, 600)
    # canvas.SetLogy()

    ## Adding in the legend
    leg = Plotting.Create_Legend(0.60, 0.60, 0.95, 0.95, ncols=1)

    ## Creating the stack
    stack = THStack("stack", "stack")
    stack.SetMinimum(ymin)
    stack.SetMaximum(ymax)

    ## Cycling through the different datasets
    for datasets, label, colour, style in data_set_names:

        ## Creating the total histogram which will be filled
        myhist = TH1D(label, label, 50, 0, 150)
        myhist.SetStats(True)
        myhist.StatOverflows(True)

        for dataset in datasets:

            ## The root file is opened
            rootfile_name = os.path.join(DATA_dir, dataset)
            print(rootfile_name)
            root_file = TFile.Open(rootfile_name, 'read')
            tree = root_file.Get("mt2_Truth")

            ## Creating the current histogram which will be filled
            thishist = TH1D(label, label, 50, 0, 150)
            thishist.SetStats(True)
            thishist.StatOverflows(True)

            ## Drawing the tree and saving the hist to the matrix
            execution = "mt2>>{}".format(label)
            tree.Draw(execution, "", "goff")

            thishist.SetDirectory(0)
            myhist.Add(thishist)

            ## We are dont with the file
            root_file.Close()
            del root_file

        ## Changing the properties of the histogram
        myhist.Scale(1 / myhist.Integral("width"))

        myhist.SetLineColor(colour)
        myhist.SetMarkerColor(colour)
        myhist.SetMarkerStyle(style)
        myhist.SetMarkerSize(1.5)

        ## Adding the legend entry
        leg.AddEntry(myhist, label, "p")

        ## Adding the object to the stack
        stack.Add(myhist)
        del myhist

    ## Drawing the stack on the currrent canvas
    stack.Draw("NOSTACK HIST P")
    leg.Draw()

    ## Setting axis labels
    stack.GetXaxis().SetTitle("m_{T2} (True #it{E}_{T}^{miss}) [GeV]")
    stack.GetYaxis().SetTitle("Normalised Distributions")

    ## Moving axis tick marks
    stack.GetYaxis().SetMaxDigits(3)
    stack.GetXaxis().SetLabelOffset(0.017)

    ## Drawing all text
    left = 0.2
    size = 1.0
    shift = 0.06
    pos = 0.88
    Plotting.Draw_ATLASLabel(left, pos, "Simulation", scale=1.0)
    pos -= shift
    Plotting.Draw_Text(left, pos, "work in progress", scale=size)
    pos -= shift
    Plotting.Draw_Lumi(left, pos, 0, scale=size)
    pos -= shift

    ## Updating the canvas
    canvas.Update()

    out_file = "true_strans.{}".format(extension)
    canvas.Print(out_file)

    del canvas

    return 0
errorband.SetMarkerSize(0)

legend.AddEntry(rebinnedData, "Data", 'pe')
legend.AddEntry(errorband, "Uncertainty", "f")

for ih in rebinnedHist:
    legend.AddEntry(rebinnedHist[ih], ih, 'f')

pad1.cd()

stack.Draw('HIST')
rebinnedData.Draw('E,X0,SAME')
legend.Draw("same")
stack.GetXaxis().SetTitle('')
stack.GetXaxis().SetLabelSize(0)
stack.GetYaxis().SetLabelSize(gStyle.GetLabelSize() /
                              (1. - padRatio + padOverlap))
stack.GetYaxis().SetTitleSize(gStyle.GetTitleSize() /
                              (1. - padRatio + padOverlap))
stack.GetYaxis().SetTitleOffset(gStyle.GetTitleYOffset() *
                                (1. - padRatio + padOverlap))
#stack.SetTitle(';;<Events/GeV>')# '%rebin)

#CMS_lumi.channelText = (channelText+"\\n"+regionText)
#if postfitPlots: CMS_lumi.channelText =channelText+"\\n "+regionText+"\\n "+chi2Text

CMS_lumi.channelText = "#splitline{%s}{%s}" % (channelText, regionText)
if postfitPlots:
    CMS_lumi.channelText = "#splitline{%s}{%s}" % (channelText + ";" +
                                                   regionText, chi2Text)

CMS_lumi.writeChannelText = True
Пример #15
0
chic0.Project('fromchic0', 'raw_ge')
chic1.Project('fromchic1', 'raw_ge')
chic2.Project('fromchic2', 'raw_ge')

fromchic0.Scale(214404 / 9997)
fromchic1.Scale(214404 / 10399)
fromchic2.Scale(214404 / 10177)

hs.Add(fromchic0)
hs.Add(fromchic1)
hs.Add(fromchic2)

mbc.cd()
hs.Draw()
hs.GetXaxis().SetTitle('E_{#gamma} (GeV)')
hs.GetYaxis().SetTitle(ytitle)
hs.GetYaxis().SetTitleOffset(1.5)

#f1 = TFile('run/chic2incl/hist_inclusiveMC/chic2incl_psip_mc_event_merged_ncostag.root')
#h_E = f1.Get('h_gam1_E')
#h_E.Draw('same')

legend = TLegend(0.5, 0.6, 0.72, 0.8)
legend.AddEntry('fromchic0', 'E_{#gamma} in process chic0')
legend.AddEntry('fromchic1', 'E_{#gamma} in process chic0')
legend.AddEntry('fromchic2', 'E_{#gamma} in process chic0')

#legend.SetNColums(1)
legend.SetBorderSize(0)
legend.SetFillColor(0)
legend.Draw()
Пример #16
0
	def plotFractionsOfBxId(self):
		##BX right plotting pt
		canvasBxRightPt = TCanvas("cBxRightPt","cBxRightPt",1200,1200)
		canvasBxRightPt.cd().SetLeftMargin(0.15)
		hBxRightPt = self.fileHandler.getHistogram('BxRightGen_Pt').Clone()
		setPlotStyle()
		hBxRightPt.Rebin(50)
		hBxRightPt.GetXaxis().SetRangeUser(0,200)
		hBxRightPt.GetYaxis().SetTitle("normalized Entries / 5 GeV")
		hBxRightPt.GetXaxis().SetTitle("p_{T} Gen")
		hBxRightPt.GetYaxis().SetTitleOffset(2)
		hBxRightPt.SetTitle("Events with right BX ID vs. p_{T}")
		hBxRightPt.SetStats(0)
		hBxRightPt.SetLineWidth(2)
		hBxRightPt.Scale(1/hBxRightPt.Integral())
		hBxRightPt.Draw()
		label = getLabelCmsPrivateSimulation()
		label.Draw()
		self.storeCanvas(canvasBxRightPt,"bxRightPt")
		
		##BX wrong plotting pt
		canvasBxWrongPt = TCanvas("cBxWrongPt","cBxWrongPt",1200,1200)
		canvasBxWrongPt.cd().SetLeftMargin(0.15)
		hBxWrongPt = self.fileHandler.getHistogram('BxWrongGen_Pt').Clone()
		setPlotStyle()
		hBxWrongPt.Rebin(50)
		hBxWrongPt.GetXaxis().SetRangeUser(0,200)
		hBxWrongPt.GetYaxis().SetTitle("normalized Entries / 5 GeV")
		hBxWrongPt.GetXaxis().SetTitle("p_{T} Gen")
		hBxWrongPt.GetYaxis().SetTitleOffset(2)
		hBxWrongPt.SetTitle("Events with wrong BX ID vs. p_{T}")
		hBxWrongPt.SetStats(0)
		hBxWrongPt.SetLineWidth(2)
		hBxWrongPt.Scale(1/hBxWrongPt.Integral())
		hBxWrongPt.DrawCopy()
		label = getLabelCmsPrivateSimulation()
		label.Draw()
		self.storeCanvas(canvasBxWrongPt,"bxWrongPt")

		#Plot the histogram stack
		canvasStack = TCanvas("cStacked","cStacked",1200,1200)
		canvasStack.cd().SetLeftMargin(0.15)
		hWrong = self.fileHandler.getHistogram('BxWrongGen_Pt')
		hRight = self.fileHandler.getHistogram('BxRightGen_Pt')
		hRightFraction = TH1D('hRightFraction','',100,0,500)
		hWrongFraction = TH1D('hWrongFraction','',100,0,500)
		#hWrong.Rebin(50)
		#hRight.Rebin(50)
		#Fill the histograms with the bin wise fractions
		for i in range(0,hRight.GetNbinsX()):
			nRight = hRight.GetBinContent(i+1)
			nWrong = hWrong.GetBinContent(i+1)
			if(nRight + nWrong == 0):
				continue
			hRightFraction.SetBinContent(i+1,nRight/(nRight+nWrong))
			hWrongFraction.SetBinContent(i+1,nWrong/(nRight+nWrong))
		
		#Create the stack
		stack = THStack("hstack","Fractions of events for BX ID correct and wrong")
		nRight = hRight.Integral()
		nWrong = hWrong.Integral()
		hRightFraction.SetLineColor(colorRwthDarkBlue)
		hRightFraction.SetFillColor(colorRwthDarkBlue)
		hRightFraction.SetFillStyle(3002)
		hWrongFraction.SetLineColor(colorRwthMagenta)
		hWrongFraction.SetFillColor(colorRwthMagenta)
		hWrongFraction.SetFillStyle(3002)
		stack.Add(hRightFraction)
		stack.Add(hWrongFraction)
		stack.Draw()
		stack.GetXaxis().SetRangeUser(0.5,201)
		stack.GetYaxis().SetTitle('rel. fraction / 5 GeV')
		stack.GetYaxis().SetTitleOffset(2)
		stack.GetXaxis().SetTitle('p_{T} Gen')
		stack.SetMinimum(0.9)
		stack.SetMaximum(1)
		legend = TLegend(0.6,0.75,0.9,0.9)
		legend.AddEntry(hRightFraction,"BX ID right","f")
		legend.AddEntry(hWrongFraction,"BX ID wrong","f")
		legend.Draw()
		label = getLabelCmsPrivateSimulation()
		label.Draw()
		canvasStack.Update()
		self.storeCanvas(canvasStack,"bxStacked")
Пример #17
0
def SaveHisto1D(HIST,
                suffix,
                output,
                snorm=1,
                ratio=0,
                poisson=True,
                logy=False,
                isVal=False):

    # only data and mc
    # SUFFIX = 2016_ss_lep1_pt

    bkgsum = 'BkgSum_%s' % (suffix)
    HIST[bkgsum] = HIST['DATA_%s' % (suffix)].Clone("BkgSum") if 'DATA_%s' % (
        suffix) in HIST else HIST['MC_%s' % (suffix)].Clone("BkgSum")
    HIST[bkgsum].Reset("MICES")
    HIST[bkgsum].SetFillStyle(3003)
    HIST[bkgsum].SetFillColor(1)
    HIST[bkgsum].SetMarkerStyle(0)

    HIST[bkgsum].Add(HIST['MC_%s' % (suffix)])

    HIST['DATA_%s' % (suffix)].SetMarkerStyle(20)
    HIST['DATA_%s' % (suffix)].SetMarkerSize(1.25)
    HIST['DATA_%s' % (suffix)].SetFillColor(418)
    HIST['DATA_%s' % (suffix)].SetFillStyle(1001)
    HIST['DATA_%s' % (suffix)].SetLineColor(1)
    HIST['DATA_%s' % (suffix)].SetLineStyle(1)
    HIST['DATA_%s' % (suffix)].SetLineWidth(2)

    HIST['MC_%s' % (suffix)].SetFillColor(418)
    HIST['MC_%s' % (suffix)].SetFillStyle(1001)
    HIST['MC_%s' % (suffix)].SetLineColor(418)
    HIST['MC_%s' % (suffix)].SetLineStyle(1)
    HIST['MC_%s' % (suffix)].SetLineWidth(2)

    for i, s in enumerate(HIST):
        addOverflow(HIST[s], False)  # Add overflow

    #Stack
    bkg = THStack(
        'bkg', ";" + HIST[bkgsum].GetXaxis().GetTitle() + ";" +
        HIST[bkgsum].GetYaxis().GetTitle())

    bkg.Add(HIST['MC_%s' % (suffix)])  # ADD ALL BKG

    #Legend
    n = len(HIST)
    leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetTextSize(0.03)
    leg.AddEntry(HIST['DATA_%s' % (suffix)],
                 'Data [%.1f]' % (HIST['DATA_%s' % (suffix)].Integral()), "pl")
    leg.AddEntry(HIST['MC_%s' % (suffix)],
                 'DY [%.1f]' % (HIST['MC_%s' % (suffix)].Integral()), "f")

    #if isFake: leg.AddEntry(HIST['FAKE_%s' %(suffix)], 'Fake [%.1f]' %(HIST['FAKE_%s' %(suffix)].Integral()), "f")

    leg.AddEntry(HIST[bkgsum], 'BkgSum [%.1f]' % (HIST[bkgsum].Integral()),
                 "f")
    c1 = TCanvas("c1",
                 HIST.values()[-1].GetXaxis().GetTitle(), 800,
                 800 if ratio else 600)

    #Ratio pad
    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)

    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.06)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if logy:
        c1.GetPad(bool(ratio)).SetLogy()

    #Draw
    bkg.Draw("HIST")  # stack
    HIST[bkgsum].Draw("SAME, E2")  # sum of bkg
    HIST['DATA_%s' % (suffix)].Draw("SAME, PE")  # data

    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1)  #1.075

    bkg.SetMaximum((6.0 if logy else 1.5) * max(
        bkg.GetMaximum(),
        HIST['DATA_%s' %
             (suffix)].GetBinContent(HIST['DATA_%s' %
                                          (suffix)].GetMaximumBin()) +
        HIST['DATA_%s' %
             (suffix)].GetBinError(HIST['DATA_%s' %
                                        (suffix)].GetMaximumBin())))
    bkg.SetMinimum(
        max(
            min(HIST[bkgsum].GetBinContent(HIST[bkgsum].GetMinimumBin(
            )), HIST['DATA_%s' %
                     (suffix)].GetMinimum()), 5.e-1) if logy else 0.)

    #bkg.SetMinimum(1.0)

    leg.Draw()

    setHistStyle(bkg, 1.2 if ratio else 1.1)
    setHistStyle(HIST[bkgsum], 1.2 if ratio else 1.1)

    ##########################
    if ratio:
        c1.cd(2)
        err = HIST[bkgsum].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if HIST[bkgsum].GetBinContent(i) > 0:
                err.SetBinError(
                    i, HIST[bkgsum].GetBinError(i) /
                    HIST[bkgsum].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        errLine.SetLineColor(1)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")

        if 'DATA_%s' % (suffix) in HIST:
            res = HIST['DATA_%s' % (suffix)].Clone("Residues")
            for i in range(0, res.GetNbinsX() + 1):
                if HIST[bkgsum].GetBinContent(i) > 0:
                    res.SetBinContent(
                        i,
                        res.GetBinContent(i) / HIST[bkgsum].GetBinContent(i))
                    res.SetBinError(
                        i,
                        res.GetBinError(i) / HIST[bkgsum].GetBinContent(i))
            setBotStyle(res)
            res.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(HIST['DATA_%s' % (suffix)], HIST[bkgsum])
                drawKolmogorov(HIST['DATA_%s' % (suffix)], HIST[bkgsum])
                #drawRelativeYield(HIST['DATA_%s' %(suffix)], HIST[bkgsum])
        else:
            res = None
    c1.cd(1)
    if '2016' in output:
        drawCMS("35.87", "Object Study")
    elif '2017' in output:
        drawCMS("41.53", "Object Study")
    elif '2018' in output:
        drawCMS("59.74", "Object Study")

    if 'os' in suffix:
        drawRegion('Opposite Sign')
    elif 'ss' in suffix:
        drawRegion('Same Sign')

    c1.Update()

    c1.Print('%s/hstack_%s.png' % (output, suffix))
Пример #18
0
def createCompoundPlots(detector, plot):
    """Produce the requested plot for the specified detector.

       Function that will plot the requested @plot for the specified
       @detector. The specified detector could either be a real
       detector or a compound one. The list of available plots are the
       keys of plots dictionary (imported from plot_utils.

    """

    theDirname = 'Images'
    if not checkFile_(theDirname):
        os.mkdir(theDirname)

    goodToGo, theDetectorFilename = paramsGood_(detector, plot)
    if not goodToGo:
        return

    theDetectorFile = TFile(theDetectorFilename)
    #

    # get TProfiles
    prof_X0_elements = OrderedDict()
    hist_X0_elements = OrderedDict()
    for label, [num, color, leg] in hist_label_to_num.iteritems():
        #print label, num, color, leg
        prof_X0_elements[label] = theDetectorFile.Get(
            "%d" % (num + plots[plot].plotNumber))
        hist_X0_elements[label] = prof_X0_elements[label].ProjectionX()
        hist_X0_elements[label].SetFillColor(color)
        hist_X0_elements[label].SetLineColor(kBlack)

    files = []
    if detector in COMPOUNDS.keys():
        for subDetector in COMPOUNDS[detector][1:]:
            subDetectorFilename = "matbdg_%s.root" % subDetector

            # open file
            if not checkFile_(subDetectorFilename):
                continue

            subDetectorFile = TFile(subDetectorFilename)
            files.append(subDetectorFile)
            print("*** Open file... %s" % subDetectorFilename)

            # subdetector profiles
            for label, [num, color, leg] in hist_label_to_num.iteritems():
                prof_X0_elements[label] = subDetectorFile.Get(
                    "%d" % (num + plots[plot].plotNumber))
                hist_X0_elements[label].Add(
                    prof_X0_elements[label].ProjectionX(
                        "B_%s" % prof_X0_elements[label].GetName()), +1.000)

    # stack
    stackTitle = "Material Budget %s;%s;%s" % (detector, plots[plot].abscissa,
                                               plots[plot].ordinate)
    stack_X0 = THStack("stack_X0", stackTitle)
    for label, [num, color, leg] in hist_label_to_num.iteritems():
        stack_X0.Add(hist_X0_elements[label])

    # canvas
    canname = "MBCan_1D_%s_%s" % (detector, plot)
    can = TCanvas(canname, canname, 800, 800)
    can.Range(0, 0, 25, 25)
    can.SetFillColor(kWhite)
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(1)

    # Draw
    stack_X0.Draw("HIST")
    stack_X0.GetYaxis().SetTitleOffset(1.15)

    # Legenda
    theLegend = TLegend(0.40, 0.65, 0.60, 0.89)
    if plot == "x_vs_phi" or plot == "l_vs_phi":
        theLegend = TLegend(0.65, 0.30, 0.89, 0.70)
    if plot == "x_vs_R" or plot == "l_vs_R":
        theLegend = TLegend(0.75, 0.60, 0.95, 0.90)

    for label, [num, color, leg] in hist_label_to_num.iteritems():
        theLegend.AddEntry(hist_X0_elements[label], leg, "f")
    theLegend.Draw()

    # Store
    can.Update()
    can.SaveAs("%s/%s_%s.pdf" % (theDirname, detector, plot))
    can.SaveAs("%s/%s_%s.png" % (theDirname, detector, plot))

    #Let's also save the total accumulated budget vs eta since muon id relies
    #on adequate calorimeter thickness
    if plot == "x_vs_eta" or plot == "l_vs_eta":
        canname = "MBCan_1D_%s_%s_total" % (detector, plot)
        can2 = TCanvas(canname, canname, 800, 800)
        can2.Range(0, 0, 25, 25)
        can2.SetFillColor(kWhite)
        gStyle.SetOptStat(0)
        gStyle.SetOptTitle(0)
        #title = TPaveLabel(.11,.95,.35,.99,"Total accumulated material budget","brndc")
        stack_X0.GetStack().Last().GetXaxis().SetRangeUser(0., 3.)
        stack_X0.GetStack().Last().Draw()
        stack_X0.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zplus.pdf" % (theDirname, detector, plot))
        can2.SaveAs("%s/%s_%s_total_Zplus.png" % (theDirname, detector, plot))
        stack_X0.GetStack().Last().GetXaxis().SetRangeUser(-3., 0.)
        stack_X0.GetStack().Last().Draw()
        stack_X0.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zminus.pdf" % (theDirname, detector, plot))
        can2.SaveAs("%s/%s_%s_total_Zminus.png" % (theDirname, detector, plot))
Пример #19
0
        cc = TCanvas(var, var, 800, 750)
        #        cc.SetLogy()
        pad1 = TPad("p1", "p1", 0, 0.25, 1, 1, 0, 0)
        pad1.SetMargin(0.15, 0.03, 0, 0.01)
        pad2 = TPad("p2", "p2", 0, 0, 1, 0.25, 0, 0)
        pad2.SetMargin(0.15, 0.03, 0.3, 0.01)
        pad2.SetGrid()
        pad1.Draw()
        pad2.Draw()

        pad1.cd()
        pad1.SetLogy()
        hs.SetMinimum(0.1)
        hs.Draw("HIST")
        #        hs.GetXaxis().SetTitle(TITLE[var])
        hs.GetYaxis().SetTitle("Events")
        hs.GetYaxis().SetTitleOffset(0.8)
        hs.GetYaxis().SetTitleSize(0.05)
        data_hist.Draw("same" "LPE")
        sig_hist.Draw("same" "LPE")
        leg.Draw()
        tex1.Draw()
        tex2.Draw()
        tex3.Draw()

        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetOptTitle(0)
        pad2.cd()
        ratio_hist.SetMarkerColor(4)
        ratio_hist.SetMarkerSize(1)
        ratio_hist.SetMarkerStyle(ROOT.kFullCircle)
posX_ = 0
posY_ = 1 - t - relPosY * (1 - t - b)
latex.SetTextFont(cmsTextFont)
latex.SetTextSize(0.8 * cmsTextSize * t)
latex.SetTextAlign(align_)

extraTextSize = extraOverCmsTextSize * cmsTextSize
latex.SetTextFont(extraTextFont)
latex.SetTextAlign(align_)
latex.SetTextSize(0.8 * extraTextSize * t)

hs.SetMaximum(1.6 * hs.GetMaximum())

fPads1.cd()
hs.Draw("HIST")
hs.GetYaxis().SetTitle("Events/bin")
hs.GetYaxis().SetTitleSize(0.04)
hs.GetYaxis().SetTickLength(0.02)
hs.GetYaxis().SetTitleOffset(1.2)
hs.GetXaxis().SetTitleOffset(1.3)
hs.GetXaxis().SetLabelSize(0.0)
hs.GetXaxis().SetTitle("M_{jj} [GeV]")

bin_width_signal = ['500', '600', '700', '1000', 'inf']
bin_width_control = ['200', '300', '400', '500']
hs.Print("all")
x1 = array('d', (4, 4))
y1 = array('d', (0, 1.1 * hs.GetMaximum()))
g1 = TGraph(2, x1, y1)
g1.SetLineColor(1)
g1.SetLineStyle(2)
	tmp_histogram_sublist[-1].SetLineColor(kBlack)
	tmp_histogram_sublist[-1].SetMarkerColor(flavour_color)
	#tmp_histogram_sublist[-1].SetStats(kTRUE)
	#tmp_histogram_sublist[-1].Draw()
	#tmp_canvas_single.Write()
	#tmp_canvas_single.SaveAs(histogram_name+"_"+flavour_name+'_Canvas.pdf')
	tmp_stack.Add(tmp_histogram_sublist[-1])
	tmp_legend.AddEntry(tmp_histogram_sublist[-1],flavour_name,'f')
      tmp_process_sublist.append(tmp_histogram_sublist)
      stack_process_sublist.append(tmp_stack) 
      tmp_canvas=TCanvas(histogram_name+'_'+process_name.split('.')[-1]+'_'+'CanvasStack','')
      #tmp_canvas.cd()
      #tmp_histogram_sublist[-1].Draw('histo')
      tmp_stack.Draw('histo')
      tmp_stack.GetXaxis().SetTitle(histogram_xaxis)
      tmp_stack.GetYaxis().SetTitle(histogram_yaxis)
      tmp_stack.SetTitle(histogram_description)
      tmp_legend.Draw()
      #tmp_canvas.BuildLegend(0.2,0.2,0.8,0.8)#tmp_legend.Draw()
      #autolegend=tmp_canvas.BuildLegend()
      stackcanvas_process_sublist.append(tmp_canvas)
 #     outfile.Cd()
      if histogram_name in ["subTrackNPixelHits","subTrackMomentum","subTrackJetDistVal","subTrackDecayLenVal","subTrackSip3dVal","subTrackSip3dSig","subJetNSecondaryVertices","subCSV"]:
	tmp_canvas.SetLogy()
      tmp_canvas.Write()
      if histogram_name in ["subTrackNPixelHits","subTrackMomentum","subTrackJetDistVal","subTrackDecayLenVal","subTrackSip3dVal","subTrackSip3dSig","subFlightDistance3dSig","subVertexMassJTC","subJetNSecondaryVertices","subVertexNTracks","subCSV"]:
	tmp_canvas.SaveAs(histogram_name+'_'+process_name.split('.')[-1]+'_'+'CanvasStack.pdf')
      #tmp_stack.Write()
    input_histos.append(tmp_process_sublist)
    output_histos.append(stack_process_sublist)
    output_canvases.append(stackcanvas_process_sublist)
Пример #22
0
def plotStack():
    inputfile = TFile(filename, "read")
    if inputfile.IsZombie():
        print("inputfile is Zombie")
        sys.exit()

    # loop over features
    for feature, values in features.items():
        file = open(
            "%s%s_%s_isNorm%s_wtStat%s_isBlind%s.txt" %
            (outputdir, feature, plotname, normalization, showStats, blind),
            "w")

        file.write(
            "\\begin{table}[]\n\\resizebox{!}{.33\\paperheight}{\n \\begin{tabular}{|l|l|l|}\n\\hline\nProcess & Yield & Entries \\\\ \\hline \n"
        )
        # set up legend
        legend = TLegend(0.2, 0.6, 0.7, 0.88)
        legend.SetHeader("%i  %s" % (year, region))
        legend.SetNColumns(4)
        legend.SetBorderSize(0)

        c, pad1, pad2 = createCanvasPads()

        hstack = THStack("hstack", "hstack")
        hstack.SetTitle(
            "#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary}                                                            %i at %.2f fb^{-1}(13TeV)}"
            % (year, luminosity[year]))

        histName = "TTH_" + feature  # assuming TTH is always there
        if not inputfile.GetListOfKeys().Contains(histName):
            print("%s doesn't have histogram %s, please use another hist " %
                  (inputfile, histName))
            sys.exit()

        h0 = inputfile.Get(histName)

        h_totalsig = h0.Clone("h_totalsig")
        h_totalsig.SetDirectory(0)
        h_totalsig.Reset()
        h_totalsig.SetMarkerStyle(20)
        h_totalsig.Sumw2()

        h_totalbkg = h0.Clone("h_totalbkg")
        h_totalbkg.SetDirectory(0)
        h_totalbkg.Reset()
        h_totalbkg.SetMarkerStyle(20)
        h_totalbkg.Sumw2()

        h_totalmc = h0.Clone("h_totalmc")
        h_totalmc.SetDirectory(0)
        h_totalmc.Reset()
        h_totalmc.SetLineColor(kBlack)
        h_totalmc.SetFillColor(kGray + 3)
        h_totalmc.SetFillStyle(3001)
        h_totalmc.SetTitle("")
        #h_totalmc.SetMinimum(0.8)
        #h_totalmc.SetMaximum(1.35)
        h_totalmc.Sumw2()
        h_totalmc.SetStats(0)

        h_dataobs = h0.Clone("h_dataobs")
        h_dataobs.SetDirectory(0)
        h_dataobs.Reset()
        h_dataobs.SetMarkerStyle(20)

        # loop over samples
        for sample in Samples:
            hist = h_totalmc.Clone(sample)
            hist.SetDirectory(0)
            hist.Reset()
            if sample not in Process:
                print("sample %s is not in Process " % sample)
                continue
            # loop over data:
            if sample == "Data" or sample == "data":
                for p in Process[sample]:
                    if p not in sampleName:
                        print("process %s is not in sampleName " % s)
                        continue
                    hist_name = p + "_" + feature
                    if not inputfile.GetListOfKeys().Contains(hist_name):
                        print("%s doesn't have histogram %s" %
                              (inputfile, hist_name))
                        continue
                    h1 = inputfile.Get(hist_name).Clone(hist_name)
                    h1.SetDirectory(0)
                    h_dataobs.Add(h1)
                    error = Double(0)
                    h1.IntegralAndError(0, h1.GetNbinsX(), error)
                    if not blind:
                        file.write(
                            "%s &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                            (p.replace('_', '\\_'), h1.Integral(), error,
                             h1.GetEntries()))
            # loop over mc
            # loop over signal
            elif sample in Signals:
                for p in Process[sample]:
                    if p not in sampleName:
                        print("process %s is not in sampleName " % s)
                        continue
                    hist_name = p + "_" + feature
                    if not inputfile.GetListOfKeys().Contains(hist_name):
                        print("%s doesn't have histogram %s" %
                              (filename, hist_name))
                        continue
                    h1 = inputfile.Get(hist_name).Clone(hist_name)
                    h1.SetDirectory(0)
                    if p == "FakeSub" and sample == "Fakes":
                        hist.Add(h1, -1)
                        h_totalsig.Add(h1, -1)
                        h_totalmc.Add(h1, -1)
                    else:
                        hist.Add(h1)
                        h_totalsig.Add(h1)
                        h_totalmc.Add(h1)
                    error = Double(0)
                    h1.IntegralAndError(0, h1.GetNbinsX(), error)
                    if h1.Integral() < 0.05 or h1.GetEntries() < 100:
                        file.write(
                            "\\textcolor{red}{%s} &  %.2f +/- %.2f &   %i \\\\ \\hline \n"
                            % (p.replace('_', '\\_'), h1.Integral(), error,
                               h1.GetEntries()))
                    else:
                        file.write(
                            "%s &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                            (p.replace('_', '\\_'), h1.Integral(), error,
                             h1.GetEntries()))
                hist.SetFillColor(Color[sample])
                hist.SetLineColor(kBlack)
                hist.SetFillStyle(Style[sample])
                if sample == "TH" and tH != 1:
                    hist.Scale(tH)
                    hist.SetFillColor(Color[sample])
                    hist.SetLineColor(kBlack)
                    hist.SetFillStyle(Style[sample])
                    hstack.Add(hist)
                    legend.AddEntry(hist, "%s * %i" % (sample, tH), "f")
                else:
                    hstack.Add(hist)
                    legend.AddEntry(hist, sample, "f")

        # create required parts
        # loop over bkg
            else:
                for p in Process[sample]:
                    if p not in sampleName:
                        print("process %s is not in sampleName " % p)
                        continue
                    hist_name = p + "_" + feature
                    if not inputfile.GetListOfKeys().Contains(hist_name):
                        print("%s doesn't have histogram %s" %
                              (filename, hist_name))
                        continue
                    h1 = inputfile.Get(hist_name).Clone(hist_name)
                    h1.SetDirectory(0)
                    if p == "FakeSub" and sample == "Fakes":
                        hist.Add(h1, -1)
                        h_totalmc.Add(h1, -1)
                        h_totalbkg.Add(h1, -1)
                    else:
                        hist.Add(h1)
                        h_totalmc.Add(h1)
                        h_totalbkg.Add(h1)
                    error = Double(0)
                    h1.IntegralAndError(0, h1.GetNbinsX(), error)
                    if h1.Integral() < 0.05 or h1.GetEntries() < 100:
                        file.write(
                            "\\textcolor{red}{%s} &  %.2f +/- %.2f &   %i \\\\ \\hline \n"
                            % (p.replace('_', '\\_'), h1.Integral(), error,
                               h1.GetEntries()))
                    else:
                        file.write(
                            "%s &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                            (p.replace('_', '\\_'), h1.Integral(), error,
                             h1.GetEntries()))
                hist.SetFillColor(Color[sample])
                hist.SetLineColor(kBlack)
                hist.SetFillStyle(Style[sample])
                if sample == "TH" and tH != 1:
                    hist.Scale(tH)
                    hist.SetFillColor(Color[sample])
                    hist.SetLineColor(kBlack)
                    hist.SetFillStyle(Style[sample])
                    hstack.Add(hist)
                    legend.AddEntry(hist, "%s * %i" % (sample, tH), "f")
                else:
                    hstack.Add(hist)
                    legend.AddEntry(hist, sample, "f")

        error = Double(0)
        h_totalsig.IntegralAndError(0, h_totalsig.GetNbinsX(), error)
        file.write("signal &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                   (h_totalsig.Integral(), error, h_totalsig.GetEntries()))

        error = Double(0)
        h_totalbkg.IntegralAndError(0, h_totalbkg.GetNbinsX(), error)
        file.write("bkg &  %.2f +/- %.2f &   %i \\\\ \\hline \n" %
                   (h_totalbkg.Integral(), error, h_totalbkg.GetEntries()))

        # create required parts

        if blind:
            h_sqrtB = createSqrt(h_totalbkg)
            h_MCerr = createTotalMCErr(h_sqrtB, values["xlabel"])
            h_ratio = createRatio(h_totalsig, h_sqrtB, values["xlabel"],
                                  normalization)
        else:
            h_MCerr = createTotalMCErr(h_totalmc, feature)
            h_ratio = createRatio(h_dataobs, h_totalmc, values["xlabel"],
                                  normalization)
            legend.AddEntry(h_dataobs, "observed", "lep")

        legend.AddEntry(h_totalmc, "Uncertainty", "f")

        # draw everything

        pad1.cd()
        if values["logy"] == 1:
            pad1.SetLogy()
        maximum = h_dataobs.GetMaximum()
        upperbound = 2. * maximum
        lowerbound = -maximum / 40.
        if values["logy"] == 1:
            upperbound = 1000 * maximum
            lowerbound = 0.1

        hstack.SetMinimum(lowerbound)
        hstack.SetMaximum(upperbound)
        hstack.Draw("HISTY")
        # Adjust y-axis settings
        y = hstack.GetYaxis()
        y.SetTitle("Events ")
        y.SetTitleSize(25)
        y.SetTitleFont(43)
        y.SetTitleOffset(1.55)
        y.SetLabelFont(43)
        y.SetLabelSize(20)

        nbins = h_ratio.GetNbinsX()
        #hstack.GetXaxis().SetRange(0, nbins+1)
        hstack.GetXaxis().SetRangeUser(values["min"], values["max"])

        h_totalmc.Draw("e2same")
        if not blind:
            h_dataobs.Draw("same")
        legend.Draw("same")

        pad2.cd()
        if blind:
            h_ratio.SetMinimum(0.)
            #maximum = h_ratio.GetMaximum()
            #upperbound = 1.5*maximum
            #h_ratio.SetMaximum(upperbound)
            h_ratio.SetMaximum(3.)
            h_ratio.GetXaxis().SetRangeUser(values["min"], values["max"])
            h_ratio.Draw("")
        else:
            h_MCerr.SetMinimum(0.5)
            h_MCerr.SetMaximum(1.8)
            h_MCerr.GetXaxis().SetRangeUser(values["min"], values["max"])
            h_MCerr.Draw("e2")
            h_ratio.Draw("same")

        c.SaveAs(
            "%s%s_%s_isNorm%s_wtStat%s_isBlind%s_stack.png" %
            (outputdir, feature, plotname, normalization, showStats, blind))
        file.write("\\end{tabular}\n}\n\\end{table}\n")
        file.close()
    inputfile.Close()
Пример #23
0
def Draw_1D_Comp(rootfile_name, var, min, max, WP_list, leg, isTail=False):
    gStyle.SetErrorX(0.5)

    ## The TStack is created with min and max set
    stack = THStack("stack", var.name)
    stack.SetMinimum(min)
    stack.SetMaximum(max)

    for wp in WP_list:

        ## Loading the graph using its name and file location
        graph_name = "{}_{}".format(var.name, wp.name)
        if isTail:
            graph_name += "_cumulative"

        graph = GetGraphFromFile(rootfile_name, graph_name)
        if graph == -1:
            continue

        ## Setting the colors specific to the working point
        graph.SetLineColor(wp.colour)
        graph.SetMarkerColor(wp.colour)
        graph.SetMarkerStyle((wp.marker))

        leg.AddEntry(graph, wp.name, "p")

        width = graph.GetBinWidth(0)

        ## We check if the legend requires values for statistics
        if leg.GetNColumns() == 2:

            ## Calculate the MEAN and RMSE and add to the legend
            mean = graph.GetMean()
            stdev = graph.GetStdDev()
            rms = np.sqrt(mean * mean + stdev * stdev)

            ## Adding the legend entry
            # leg.AddEntry( 0, "{:5.2f}".format(mean), "")
            leg.AddEntry(0, "{:5.2f}".format(rms), "")

        ## Adding the object to the stack
        stack.Add(graph)
        del graph

    ## Checking to see if any graphs were found for this variable
    if stack.GetNhists() == 0:
        print("\n\n\nNo graphs found for working point {}\n\n\n".format(
            wp.name))
        return -1

    ## Drawing the stack on the currrent canvas
    stack.Draw("nostack EP")
    leg.Draw()

    ## Setting axis labels
    if isTail:
        stack.GetXaxis().SetTitle(var.x_label + " threshold " + var.units)
        stack.GetYaxis().SetTitle("#it{f}_{tail}")
    else:
        stack_y_label = "Events per {:.0f} GeV".format(
            width) if width > 1 else "Events per GeV"

        stack.GetXaxis().SetTitle(var.x_label + " " + var.units)
        stack.GetYaxis().SetTitle(stack_y_label)

    ## Moving axis tick marks
    stack.GetYaxis().SetMaxDigits(3)
    stack.GetXaxis().SetLabelOffset(0.017)

    return stack
Пример #24
0
def draw(hist, data, back, sign, snorm=1, ratio=0, poisson=False, log=False):
    # If not present, create BkgSum
    if not 'BkgSum' in hist.keys():
        hist['BkgSum'] = hist['data_obs'].Clone(
            "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
        hist['BkgSum'].Reset("MICES")
        for i, s in enumerate(back):
            hist['BkgSum'].Add(hist[s])
    hist['BkgSum'].SetMarkerStyle(0)

    # Some style
    for i, s in enumerate(data):
        hist[s].SetMarkerStyle(21)
        hist[s].SetMarkerSize(1.25)
    for i, s in enumerate(sign):
        hist[s].SetLineWidth(3)

    for i, s in enumerate(data + back + sign + ['BkgSum']):
        addOverflow(hist[s], False)  # Add overflow

    # Set Poisson error bars
    #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work

    # Poisson error bars for data
    if poisson:
        alpha = 1 - 0.6827
        hist['data_obs'].SetBinErrorOption(TH1.kPoisson)
        data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX())
        data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle())
        data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize())
        res_graph = data_graph.Clone()
        for i in range(hist['data_obs'].GetNbinsX()):
            N = hist['data_obs'].GetBinContent(i + 1)
            B = hist['BkgSum'].GetBinContent(i + 1)
            L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.)
            U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1)
            data_graph.SetPoint(
                i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                N if not N == 0 else -1.e99)
            data_graph.SetPointError(
                i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
                hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L,
                U - N)
            res_graph.SetPoint(i,
                               hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                               N / B if not B == 0 and not N == 0 else -1.e99)
            res_graph.SetPointError(
                i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
                hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
                (N - L) / B if not B == 0 else -1.e99,
                (U - N) / B if not B == 0 else -1.e99)

    # Create stack
    bkg = THStack("Bkg",
                  ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    n = len([x for x in data + back + ['BkgSum'] + sign if samples[x]['plot']])
    for i, s in enumerate(sign):
        if 'sublabel' in samples[s]: n += 1
        if 'subsublabel' in samples[s]: n += 1
    #leg = TLegend(0.68, 0.9-0.05*n, 0.93, 0.9)
    leg = TLegend(0.68 - 0.05, 0.9 - 0.05 * n, 0.93, 0.9)  #DCMS
    leg.SetTextSize(0.03)  #DCMS
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("Signal x-sec=%.0f pb" % (1 * snorm))
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], samples[data[0]]['label'], "ple1")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], samples[s]['label'], "f")
    for i, s in enumerate(sign):
        leg.AddEntry(hist[s], samples[s]['label'], "f")

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[-1].GetXaxis().GetTitle(), 1000,
                 800 if ratio else 700)

    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)
    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.06)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if log:
        c1.GetPad(bool(ratio)).SetLogy()
        #c1.GetPad(bool(ratio)).SetLogx()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    if poisson: data_graph.Draw("SAME, PE")
    elif len(data) > 0: hist['data_obs'].Draw("SAME, PE")
    for i, s in enumerate(sign):
        if samples[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST",
                                   hist[s].Integral() * snorm)  # signals

    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075)

    # Determine range
    if 'data_obs' in hist:
        bkg.SetMaximum((2.5 if log else 1.2) * max(
            bkg.GetMaximum(),
            hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
            hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
        bkg.SetMinimum(
            max(
                min(
                    hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
                    )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.)
    else:
        bkg.SetMaximum(bkg.GetMaximum() * (2.5 if log else 1.2))
        bkg.SetMinimum(5.e-1 if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)

    leg.Draw()
    #drawCMS(LUMI, "Preliminary")
    #drawRegion(channel)
    #drawAnalysis("LL")

    setHistStyle(bkg, 1.2 if ratio else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1)

    if ratio:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(2)
        errLine.SetFillStyle(0)
        errLine.SetLineColor(2)  #L#
        errLine.SetLineStyle(2)  #L#
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if 'data_obs' in hist:
            res = hist['data_obs'].Clone("Residues")
            for i in range(0, res.GetNbinsX() + 1):
                if hist['BkgSum'].GetBinContent(i) > 0:
                    res.SetBinContent(
                        i,
                        res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                    res.SetBinError(
                        i,
                        res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
            setBotStyle(res)
            if poisson: res_graph.Draw("SAME, PE0")
            else: res.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(hist['data_obs'], hist['BkgSum'])
                drawKolmogorov(hist['data_obs'], hist['BkgSum'])
        else:
            res = None
    c1.Update()

    # return list of objects created by the draw() function
    return [
        c1, bkg, leg, err if ratio else None, errLine if ratio else None,
        res if ratio else None, data_graph if poisson else None,
        res_graph if poisson else None
    ]
Пример #25
0
def createPlotsReco_(reco_file, label, debug=False):
    """Cumulative material budget from reconstruction.


       Internal function that will produce a cumulative profile of the
       material budget in the reconstruction starting from the single
       detectors that compose the tracker. It will iterate over all
       existing detectors contained in the sDETS dictionary. The
       function will automatically stop everytime it encounters a
       non-existent detector, until no more detectors are left to
       try. For this reason the keys in the sDETS dictionary can be as
       inclusive as possible.

    """

    cumulative_matbdg = None
    sPREF = ["Original_RadLen_vs_Eta_", "RadLen_vs_Eta_"]

    c = TCanvas("c", "c", 1024, 1024)
    diffs = []
    if not checkFile_(reco_file):
        print("Error: missing file %s" % reco_file)
        raise RuntimeError
    file = TFile(reco_file)
    prefix = "/DQMData/Run 1/Tracking/Run summary/RecoMaterial/"
    for s in sPREF:
        hs = THStack("hs", "")
        histos = []
        for det, color in sDETS.iteritems():
            layer_number = 0
            while True:
                layer_number += 1
                name = "%s%s%s%d" % (prefix, s, det, layer_number)
                prof = file.Get(name)
                # If we miss an object, since we are incrementally
                # searching for consecutive layers, we may safely
                # assume that there are no additional layers and skip
                # to the next detector.
                if not prof:
                    if debug:
                        print("Missing profile %s" % name)
                    break
                else:
                    histos.append(prof.ProjectionX("_px", "hist"))
                    diffs.append(histos[-1])
                    histos[-1].SetFillColor(color + layer_number)
                    histos[-1].SetLineColor(color + layer_number + 1)

        name = "CumulativeRecoMatBdg_%s" % s
        if s == "RadLen_vs_Eta_":
            cumulative_matbdg = TH1D(name, name, histos[0].GetNbinsX(),
                                     histos[0].GetXaxis().GetXmin(),
                                     histos[0].GetXaxis().GetXmax())
            cumulative_matbdg.SetDirectory(0)
        for h in histos:
            hs.Add(h)
            if cumulative_matbdg:
                cumulative_matbdg.Add(h, 1.)
        hs.Draw()
        hs.GetYaxis().SetTitle("RadLen")
        c.Update()
        c.Modified()
        c.SaveAs("%sstacked_%s.png" % (s, label))
    hs = THStack("diff", "")
    for d in range(0, len(diffs) / 2):
        diffs[d + len(diffs) / 2].Add(diffs[d], -1.)
        hs.Add(diffs[d + len(diffs) / 2])
    hs.Draw()
    hs.GetYaxis().SetTitle("RadLen")
    c.Update()
    c.Modified()
    c.SaveAs("RadLen_difference_%s.png" % label)
    return cumulative_matbdg
Пример #26
0
def Direct_Estimator(var, cut, year):
    from root_numpy import root2array, fill_hist, array2root
    import numpy.lib.recfunctions as rfn
    ### Preliminary Operations ###
    treeRead = not cut in [
        "nnqq", "en", "enqq", "mn", "mnqq", "ee", "eeqq", "mm", "mmqq", "em",
        "emqq", "qqqq"
    ]  # Read from tree
    channel = cut
    unit = ''
    if "GeV" in variable[var]['title']: unit = ' GeV'
    isBlind = BLIND and 'SR' in channel
    isAH = False  #'qqqq' in channel or 'hp' in channel or 'lp' in channel
    showSignal = False if 'SB' in cut or 'TR' in cut else True  #'SR' in channel or channel=='qqqq'#or len(channel)==5
    stype = "HVT model B"
    if len(sign) > 0 and 'AZh' in sign[0]: stype = "2HDM"
    elif len(sign) > 0 and 'monoH' in sign[0]: stype = "Z'-2HDM m_{A}=300 GeV"
    if treeRead:
        for k in sorted(alias.keys(), key=len, reverse=True):
            if BTAGGING == 'semimedium':
                if k in cut:
                    cut = cut.replace(k, aliasSM[k])

            else:
                if k in cut:
                    cut = cut.replace(
                        k, alias[k].format(WP=working_points[BTAGGING]))

    print "Plotting from", ("tree" if treeRead else
                            "file"), var, "in", channel, "channel with:"
    print "  cut    :", cut

    if var == 'jj_deltaEta_widejet':
        if "jj_deltaEta_widejet<1.1 && " in cut:
            print
            print "omitting jj_deltaEta_widejet<1.1 cut to draw the deltaEta distribution"
            print
            cut = cut.replace("jj_deltaEta_widejet<1.1 && ", "")
        else:
            print
            print "no 'jj_deltaEta_widejet<1.1 && ' in the cut string detected, so it cannot be ommited explicitly"
            print

    ### Create and fill MC histograms ###
    # Create dict
    file = {}
    tree = {}
    hist = {}

    ### Create and fill MC histograms ###
    for i, s in enumerate(back + sign):
        if True:  #FIXME

            if variable[var]['nbins'] > 0:
                hist[s] = TH1F(
                    s, ";" + variable[var]['title'] + ";Events / ( " + str(
                        (variable[var]['max'] - variable[var]['min']) /
                        variable[var]['nbins']) + unit + " );" +
                    ('log' if variable[var]['log'] else ''),
                    variable[var]['nbins'], variable[var]['min'],
                    variable[var]['max'])
            else:
                hist[s] = TH1F(
                    s, ";" + variable[var]['title'] + ";Events" +
                    ('log' if variable[var]['log'] else ''),
                    len(variable[var]['bins']) - 1,
                    array('f', variable[var]['bins']))
            hist[s].Sumw2()

            for j, ss in enumerate(sample[s]['files']):
                if not 'data' in s:
                    if year == "run2" or year in ss:
                        arr = root2array(
                            NTUPLEDIR + ss + ".root",
                            branches=[
                                var, "jpt_1", "jpt_2", "eventWeightLumi",
                                "TMath::Abs(jflavour_1)==5 && TMath::Abs(jflavour_2)==5",
                                "TMath::Abs(jflavour_1)==5 && TMath::Abs(jflavour_2)!=5",
                                "TMath::Abs(jflavour_1)!=5 && TMath::Abs(jflavour_2)==5",
                                "TMath::Abs(jflavour_1)!=5 && TMath::Abs(jflavour_2)!=5"
                            ],
                            selection=cut if len(cut) > 0 else "")
                        print "imported " + NTUPLEDIR + ss + ".root"
                        arr.dtype.names = [
                            var, "jpt_1", "jpt_2", "eventWeightLumi", "bb",
                            "bq", "qb", "qq"
                        ]
                        MANtag_eff1 = np.array(map(MANtag_eff, arr["jpt_1"]))
                        MANtag_eff2 = np.array(map(MANtag_eff, arr["jpt_2"]))
                        MANtag_mis1 = np.array(map(MANtag_mis, arr["jpt_1"]))
                        MANtag_mis2 = np.array(map(MANtag_mis, arr["jpt_2"]))
                        MANtag_weight = np.multiply(
                            arr["eventWeightLumi"],
                            np.multiply(arr['bb'],
                                        np.multiply(MANtag_eff1, MANtag_eff2))
                            + np.multiply(
                                arr['bq'], np.multiply(MANtag_eff1,
                                                       MANtag_mis2)) +
                            np.multiply(arr['qb'],
                                        np.multiply(MANtag_mis1,
                                                    MANtag_eff2)) +
                            np.multiply(arr['qq'],
                                        np.multiply(MANtag_mis1, MANtag_mis2)))
                        fill_hist(hist[s], arr[var], weights=MANtag_weight)
                        deepCSV_eff1 = np.array(map(deepCSV_eff, arr["jpt_1"]))
                        deepCSV_eff2 = np.array(map(deepCSV_eff, arr["jpt_2"]))
                        deepCSV_mis1 = np.array(map(deepCSV_mis, arr["jpt_1"]))
                        deepCSV_mis2 = np.array(map(deepCSV_mis, arr["jpt_2"]))
                        deepCSV_weight = np.multiply(
                            arr["eventWeightLumi"],
                            np.multiply(
                                arr['bb'],
                                np.multiply(deepCSV_eff1, deepCSV_eff2)) +
                            np.multiply(
                                arr['bq'],
                                np.multiply(deepCSV_eff1, deepCSV_mis2)) +
                            np.multiply(
                                arr['qb'],
                                np.multiply(deepCSV_mis1, deepCSV_eff2)) +
                            np.multiply(
                                arr['qq'],
                                np.multiply(deepCSV_mis1, deepCSV_mis2)))

                        if var == "jj_mass_widejet" and options.save and not "data" in ss:
                            arr = rfn.append_fields(arr,
                                                    "MANtag_weight",
                                                    MANtag_weight,
                                                    usemask=False)
                            arr = rfn.append_fields(arr,
                                                    "deepCSV_weight",
                                                    deepCSV_weight,
                                                    usemask=False)
                            array2root(arr,
                                       NTUPLEDIR + "MANtag/" + ss + "_" +
                                       BTAGGING + ".root",
                                       treename="tree",
                                       mode='recreate')
                            print "saved as", NTUPLEDIR + "MANtag/" + ss + "_" + BTAGGING + ".root"
                        arr = None

        hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0)
        hist[s].SetFillColor(sample[s]['fillcolor'])
        hist[s].SetFillStyle(sample[s]['fillstyle'])
        hist[s].SetLineColor(sample[s]['linecolor'])
        hist[s].SetLineStyle(sample[s]['linestyle'])

    if channel.endswith('TR') and channel.replace('TR', '') in topSF:
        hist['TTbarSL'].Scale(topSF[channel.replace('TR', '')][0])
        hist['ST'].Scale(topSF[channel.replace('TR', '')][0])

    hist['BkgSum'] = hist['data_obs'].Clone(
        "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
    hist['BkgSum'].Reset("MICES")
    hist['BkgSum'].SetFillStyle(3003)
    hist['BkgSum'].SetFillColor(1)
    for i, s in enumerate(back):
        hist['BkgSum'].Add(hist[s])

    # Create data and Bkg sum histograms
    if options.blind or 'SR' in channel:
        hist['data_obs'] = hist['BkgSum'].Clone("data_obs")
        hist['data_obs'].Reset("MICES")
    # Set histogram style
    hist['data_obs'].SetMarkerStyle(20)
    hist['data_obs'].SetMarkerSize(1.25)

    for i, s in enumerate(back + sign + ['BkgSum']):
        addOverflow(hist[s], False)  # Add overflow
    for i, s in enumerate(sign):
        hist[s].SetLineWidth(3)
    for i, s in enumerate(sign):
        sample[s][
            'plot'] = True  #sample[s]['plot'] and s.startswith(channel[:2])

    if isAH:
        for i, s in enumerate(back):
            hist[s].SetFillStyle(3005)
            hist[s].SetLineWidth(2)
        #for i, s in enumerate(sign):
        #    hist[s].SetFillStyle(0)
        if not var == "Events":
            sfnorm = hist[data[0]].Integral() / hist['BkgSum'].Integral()
            print "Applying SF:", sfnorm
            for i, s in enumerate(back + ['BkgSum']):
                hist[s].Scale(sfnorm)
        if BLIND and var.endswith("Mass"):
            for i, s in enumerate(data + back + ['BkgSum']):
                first, last = hist[s].FindBin(65), hist[s].FindBin(135)
                for j in range(first, last):
                    hist[s].SetBinContent(j, -1.e-4)
        if BLIND and var.endswith("Tau21"):
            for i, s in enumerate(data):
                first, last = hist[s].FindBin(0), hist[s].FindBin(0.6)
                for j in range(first, last):
                    hist[s].SetBinContent(j, -1.e-4)

    # Create stack
    if variable[var]['nbins'] > 0:
        bkg = THStack(
            "Bkg",
            ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events / ( " + str(
                (variable[var]['max'] - variable[var]['min']) /
                variable[var]['nbins']) + unit + " )")
    else:
        bkg = THStack("Bkg",
                      ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events; ")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    leg = TLegend(0.65, 0.6, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    if showSignal:
        for i, s in enumerate(sign):
            if sample[s]['plot']:
                leg.AddEntry(hist[s], sample[s]['label'], "fl")

    leg.SetY1(0.9 - leg.GetNRows() * 0.05)

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if RATIO else 600)

    if RATIO:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), RATIO)
        setBotPad(c1.GetPad(2), RATIO)
    c1.cd(1)
    c1.GetPad(bool(RATIO)).SetTopMargin(0.06)
    c1.GetPad(bool(RATIO)).SetRightMargin(0.05)
    c1.GetPad(bool(RATIO)).SetTicks(1, 1)

    log = variable[var]['log']  #"log" in hist['BkgSum'].GetZaxis().GetTitle()
    if log: c1.GetPad(bool(RATIO)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    if not isBlind and len(data) > 0: hist['data_obs'].Draw("SAME, PE")  # data
    if 'sync' in hist: hist['sync'].Draw("SAME, PE")
    #data_graph.Draw("SAME, PE")
    if showSignal:
        smagn = 1.  #if treeRead else 1.e2 #if log else 1.e2
        for i, s in enumerate(sign):
            #        if sample[s]['plot']:
            hist[s].Scale(smagn)
            hist[s].Draw(
                "SAME, HIST"
            )  # signals Normalized, hist[s].Integral()*sample[s]['weight']
        textS = drawText(0.80, 0.9 - leg.GetNRows() * 0.05 - 0.02,
                         stype + " (x%d)" % smagn, True)
    #bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075)
    bkg.GetYaxis().SetTitleOffset(0.9)
    #bkg.GetYaxis().SetTitleOffset(2.)
    bkg.SetMaximum((5. if log else 1.25) * max(
        bkg.GetMaximum(),
        hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25)
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        #bkg.GetYaxis().SetMoreLogLabels(True)
    bkg.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max'])

    #if log: bkg.SetMinimum(1)
    leg.Draw()
    #drawCMS(LUMI[year], "Preliminary")
    drawCMS(LUMI[year], "Work in Progress", suppressCMS=True)
    drawRegion('XVH' + channel, True)
    drawAnalysis(channel)

    setHistStyle(bkg, 1.2 if RATIO else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1)

    if RATIO:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / MC")
        err.GetYaxis().SetTitleOffset(0.9)

        err.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max'])
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        res = hist['data_obs'].Clone("Residues")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                res.SetBinContent(
                    i,
                    res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                res.SetBinError(
                    i,
                    res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
        if 'sync' in hist:
            res.SetMarkerColor(2)
            res.SetMarkerStyle(31)
            res.Reset()
            for i in range(0, res.GetNbinsX() + 1):
                x = hist['data_obs'].GetXaxis().GetBinCenter(i)
                if hist['sync'].GetBinContent(hist['sync'].FindBin(x)) > 0:
                    res.SetBinContent(
                        i, hist['data_obs'].GetBinContent(
                            hist['data_obs'].FindBin(x)) /
                        hist['sync'].GetBinContent(hist['sync'].FindBin(x)))
                    res.SetBinError(
                        i, hist['data_obs'].GetBinError(
                            hist['data_obs'].FindBin(x)) /
                        hist['sync'].GetBinContent(hist['sync'].FindBin(x)))
        setBotStyle(res)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if not isBlind and len(data) > 0:
            res.Draw("SAME, PE0")
            #res_graph.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(hist['data_obs'], hist['BkgSum'])
                drawStat(hist['data_obs'], hist['BkgSum'])

    c1.Update()

    if gROOT.IsBatch():
        if channel == "": channel = "nocut"
        varname = var.replace('.', '_').replace('()', '')
        if not os.path.exists("plots/" + channel):
            os.makedirs("plots/" + channel)
        suffix = ''
        if "b" in channel or 'mu' in channel: suffix += "_" + BTAGGING
        c1.Print("plots/MANtag_study/" + channel + "/" + varname + "_" + year +
                 suffix + ".png")
        c1.Print("plots/MANtag_study/" + channel + "/" + varname + "_" + year +
                 suffix + ".pdf")

    # Print table
    printTable(hist, sign)
Пример #27
0
def createPlots_(plot, compounddetectorname):
    """Cumulative material budget from simulation.
    
       Internal function that will produce a cumulative profile of the
       material budget inferred from the simulation starting from the
       single detectors that compose the tracker. It will iterate over
       all existing detectors contained in the DETECTORS
       dictionary. The function will automatically skip non-existent
       detectors.

    """

    theDirname = "Figures"

    hist_X0_detectors = OrderedDict()
    if plot not in plots.keys():
        print("Error: chosen plot name not known %s" % plot)
        return

    # We need to keep the file content alive for the lifetime of the
    # full function....
    subDetectorFiles = []

    hist_X0_elements = OrderedDict()
    prof_X0_elements = OrderedDict()
    for subDetector, color in DETECTORS.iteritems():
        subDetectorFilename = "matbdg_%s.root" % subDetector
        if not checkFile_(subDetectorFilename):
            print("Error opening file: %s" % subDetectorFilename)
            continue

        subDetectorFiles.append(TFile(subDetectorFilename))
        subDetectorFile = subDetectorFiles[-1]
        print("Opening file: %s" % subDetectorFilename)
        prof_X0_XXX = subDetectorFile.Get("%d" % plots[plot].plotNumber)

        hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionX()

        # category profiles
        for label, [num, color, leg] in hist_label_to_num.iteritems():
            prof_X0_elements[label] = subDetectorFile.Get(
                "%d" % (num + plots[plot].plotNumber))
            hist_X0_elements[label] = assignOrAddIfExists_(
                hist_X0_elements.setdefault(label, None),
                prof_X0_elements[label])

    cumulative_matbdg = TH1D(
        "CumulativeSimulMatBdg", "CumulativeSimulMatBdg",
        hist_X0_detectors["BeamPipe"].GetNbinsX(),
        hist_X0_detectors["BeamPipe"].GetXaxis().GetXmin(),
        hist_X0_detectors["BeamPipe"].GetXaxis().GetXmax())
    cumulative_matbdg.SetDirectory(0)

    # colors
    for det, color in DETECTORS.iteritems():
        setColorIfExists_(hist_X0_detectors, det, color)

    for label, [num, color, leg] in hist_label_to_num.iteritems():
        hist_X0_elements[label].SetFillColor(color)

    # First Plot: BeamPipe + Tracker + ECAL + HCal + HGCal + MB + MGNT
    # stack
    stackTitle_SubDetectors = "Material Budget;%s;%s" % (plots[plot].abscissa,
                                                         plots[plot].ordinate)
    stack_X0_SubDetectors = THStack("stack_X0", stackTitle_SubDetectors)
    for det, histo in hist_X0_detectors.iteritems():
        stack_X0_SubDetectors.Add(histo)
        cumulative_matbdg.Add(histo, 1)

    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors", 800,
                               800)
    #can_SubDetectors.Range(0,0,25,25)
    can_SubDetectors.SetFillColor(kWhite)

    # Draw
    stack_X0_SubDetectors.SetMinimum(plots[plot].ymin)
    stack_X0_SubDetectors.SetMaximum(plots[plot].ymax)
    stack_X0_SubDetectors.Draw("HIST")
    #stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax)

    # Legenda
    theLegend_SubDetectors = TLegend(0.130, 0.7, 0.93,
                                     0.90)  #(0.180,0.8,0.98,0.90)
    theLegend_SubDetectors.SetNColumns(2)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in hist_X0_detectors.iteritems():
        theLegend_SubDetectors.AddEntry(histo, det, "f")

    theLegend_SubDetectors.Draw()

    # text
    text_SubDetectors = TPaveText(0.130, 0.627, 0.352, 0.687,
                                  "NDC")  #(0.180,0.727,0.402,0.787,"NDC")
    text_SubDetectors.SetFillColor(0)
    text_SubDetectors.SetBorderSize(0)
    text_SubDetectors.AddText("CMS Simulation")
    text_SubDetectors.SetTextAlign(11)
    text_SubDetectors.Draw()

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.pdf" %
                            (theDirname, compounddetectorname, plot))
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.png" %
                            (theDirname, compounddetectorname, plot))
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.root" %
                            (theDirname, compounddetectorname, plot))

    if plot == "x_vs_eta" or plot == "l_vs_eta":
        canname = "MBCan_1D_%s_%s_total" % (compounddetectorname, plot)
        can2 = TCanvas(canname, canname, 800, 800)
        can2.Range(0, 0, 25, 25)
        can2.SetFillColor(kWhite)
        gStyle.SetOptStat(0)
        gStyle.SetOptTitle(0)
        #title = TPaveLabel(.11,.95,.35,.99,"Total accumulated material budget","brndc")
        stack_X0_SubDetectors.GetStack().Last().SetMarkerStyle(34)
        stack_X0_SubDetectors.GetStack().Last().GetXaxis().SetRangeUser(
            1.0, 3.5)
        stack_X0_SubDetectors.GetStack().Last().Draw()
        stack_X0_SubDetectors.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zplus.pdf" %
                    (theDirname, compounddetectorname, plot))
        can2.SaveAs("%s/%s_%s_total_Zplus.png" %
                    (theDirname, compounddetectorname, plot))
        stack_X0_SubDetectors.GetStack().Last().GetXaxis().SetRangeUser(
            -3.5, -1.0)
        stack_X0_SubDetectors.GetStack().Last().Draw()
        stack_X0_SubDetectors.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zminus.pdf" %
                    (theDirname, compounddetectorname, plot))
        can2.SaveAs("%s/%s_%s_total_Zminus.png" %
                    (theDirname, compounddetectorname, plot))

        #Also print them to give them exact numbers
        etavalues = []
        matbudginX0 = []
        matbudginIntLen = []
        for binx in range(
                0,
                stack_X0_SubDetectors.GetStack().Last().GetXaxis().GetNbins()):
            bincontent = stack_X0_SubDetectors.GetStack().Last().GetBinContent(
                binx)
            if bincontent == 0: continue
            etavalues.append(
                stack_X0_SubDetectors.GetStack().Last().GetBinCenter(binx))
            if plot == "x_vs_eta":
                matbudginX0.append(bincontent)
                d1 = {'Eta': etavalues, 'MatBudInX0': matbudginX0}
                df1 = pd.DataFrame(data=d1).round(2)
                df1.to_csv(
                    r'/afs/cern.ch/work/a/apsallid/CMS/PFCalStudies/CMS-HGCAL/matbudV10fromVertexToBackofHGCal/CMSSW_11_0_X_2019-06-04-2300/src/Validation/Geometry/test/EtavsMatBudinXo.txt',
                    sep=' ',
                    index=False,
                    header=False)
                #print df1
            if plot == "l_vs_eta":
                matbudginIntLen.append(bincontent)
                d2 = {'Eta': etavalues, 'MatBudInIntLen': matbudginIntLen}
                df2 = pd.DataFrame(data=d2).round(2)
                df2.to_csv(
                    r'/afs/cern.ch/work/a/apsallid/CMS/PFCalStudies/CMS-HGCAL/matbudV10fromVertexToBackofHGCal/CMSSW_11_0_X_2019-06-04-2300/src/Validation/Geometry/test/EtavsMatBudInIntLen.txt',
                    sep=' ',
                    index=False,
                    header=False)
                #print df2

    return cumulative_matbdg
Пример #28
0
def DeepCSV_pt_distribution(
        year):  ## everything below is jsut copy&past from above
    from root_numpy import root2array, fill_hist, array2root
    import numpy.lib.recfunctions as rfn
    from aliases import alias_deepCSV, WP_deepCSV
    ### Preliminary Operations ###
    treeRead = True
    var = 'jpt_1'
    channel = 'preselection'
    cut = alias_deepCSV['preselection']
    unit = ''
    if "GeV" in variable[var]['title']: unit = ' GeV'
    isBlind = BLIND and 'SR' in channel
    isAH = False
    showSignal = True
    stype = "HVT model B"
    if len(sign) > 0 and 'AZh' in sign[0]: stype = "2HDM"
    elif len(sign) > 0 and 'monoH' in sign[0]: stype = "Z'-2HDM m_{A}=300 GeV"
    if treeRead:
        for k in sorted(alias_deepCSV.keys(), key=len, reverse=True):
            if k in cut:
                cut = cut.replace(
                    k, alias_deepCSV[k].format(WP=WP_deepCSV[BTAGGING][year]))

    print "Plotting from", ("tree" if treeRead else
                            "file"), var, "in", channel, "channel with:"
    print "  cut    :", cut

    ### Create and fill MC histograms ###
    # Create dict
    file = {}
    tree = {}
    hist = {}
    N_signal_tot = 0.
    N_signal_tag = 0.

    ### Create and fill MC histograms ###
    for i, s in enumerate(back + sign):

        if variable[var]['nbins'] > 0:
            hist[s] = TH1F(
                s, ";jet p_{T};Events / ( " + str(
                    (variable[var]['max'] - variable[var]['min']) /
                    variable[var]['nbins']) + unit + " );" +
                ('log' if variable[var]['log'] else ''),
                variable[var]['nbins'], variable[var]['min'],
                variable[var]['max'])
        else:
            hist[s] = TH1F(
                s,
                ";jet p_{T};Events" + ('log' if variable[var]['log'] else ''),
                len(variable[var]['bins']) - 1,
                array('f', variable[var]['bins']))
        hist[s].Sumw2()

        for j, ss in enumerate(sample[s]['files']):
            if not 'data' in s:
                if year == "run2" or year in ss:
                    arr = root2array(NTUPLEDIR + ss + ".root",
                                     branches=["jpt_1", "eventWeightLumi"],
                                     selection=cut + " && jdeepCSV_1>" +
                                     str(WP_deepCSV[BTAGGING][year]))
                    if 'signal' in ss.lower():
                        N_signal_tag += len(arr['jpt_1'][arr['jpt_1'] > 3500])
                    print "imported " + NTUPLEDIR + ss + ".root"
                    fill_hist(hist[s],
                              arr["jpt_1"],
                              weights=arr["eventWeightLumi"])
                    arr = None

                    arr = root2array(NTUPLEDIR + ss + ".root",
                                     branches=["jpt_2", "eventWeightLumi"],
                                     selection=cut + " && jdeepCSV_2>" +
                                     str(WP_deepCSV[BTAGGING][year]))
                    print "imported " + NTUPLEDIR + ss + ".root"
                    if 'signal' in ss.lower():
                        N_signal_tag += len(arr['jpt_2'][arr['jpt_2'] > 3500])
                    fill_hist(hist[s],
                              arr["jpt_2"],
                              weights=arr["eventWeightLumi"])
                    arr = None

                    if 'signal' in ss.lower():
                        arr = root2array(NTUPLEDIR + ss + ".root",
                                         branches=["jpt_1", "eventWeightLumi"],
                                         selection=cut)
                        N_signal_tot += len(arr['jpt_1'][arr['jpt_1'] > 3500])
                        arr = None

                        arr = root2array(NTUPLEDIR + ss + ".root",
                                         branches=["jpt_2", "eventWeightLumi"],
                                         selection=cut)
                        N_signal_tot += len(arr['jpt_2'][arr['jpt_2'] > 3500])
                        arr = None

        hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0)
        hist[s].SetFillColor(sample[s]['fillcolor'])
        hist[s].SetFillStyle(sample[s]['fillstyle'])
        hist[s].SetLineColor(sample[s]['linecolor'])
        hist[s].SetLineStyle(sample[s]['linestyle'])

    if channel.endswith('TR') and channel.replace('TR', '') in topSF:
        hist['TTbarSL'].Scale(topSF[channel.replace('TR', '')][0])
        hist['ST'].Scale(topSF[channel.replace('TR', '')][0])

    hist['BkgSum'] = hist['data_obs'].Clone(
        "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
    hist['BkgSum'].Reset("MICES")
    hist['BkgSum'].SetFillStyle(3003)
    hist['BkgSum'].SetFillColor(1)
    for i, s in enumerate(back):
        hist['BkgSum'].Add(hist[s])

    # Create data and Bkg sum histograms
    if options.blind or 'SR' in channel:
        hist['data_obs'] = hist['BkgSum'].Clone("data_obs")
        hist['data_obs'].Reset("MICES")
    # Set histogram style
    hist['data_obs'].SetMarkerStyle(20)
    hist['data_obs'].SetMarkerSize(1.25)

    for i, s in enumerate(back + sign + ['BkgSum']):
        addOverflow(hist[s], False)  # Add overflow
    for i, s in enumerate(sign):
        hist[s].SetLineWidth(3)
    for i, s in enumerate(sign):
        sample[s][
            'plot'] = True  #sample[s]['plot'] and s.startswith(channel[:2])

    if isAH:
        for i, s in enumerate(back):
            hist[s].SetFillStyle(3005)
            hist[s].SetLineWidth(2)
        #for i, s in enumerate(sign):
        #    hist[s].SetFillStyle(0)
        if not var == "Events":
            sfnorm = hist[data[0]].Integral() / hist['BkgSum'].Integral()
            print "Applying SF:", sfnorm
            for i, s in enumerate(back + ['BkgSum']):
                hist[s].Scale(sfnorm)
        if BLIND and var.endswith("Mass"):
            for i, s in enumerate(data + back + ['BkgSum']):
                first, last = hist[s].FindBin(65), hist[s].FindBin(135)
                for j in range(first, last):
                    hist[s].SetBinContent(j, -1.e-4)
        if BLIND and var.endswith("Tau21"):
            for i, s in enumerate(data):
                first, last = hist[s].FindBin(0), hist[s].FindBin(0.6)
                for j in range(first, last):
                    hist[s].SetBinContent(j, -1.e-4)

    # Create stack
    if variable[var]['nbins'] > 0:
        bkg = THStack(
            "Bkg",
            ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events / ( " + str(
                (variable[var]['max'] - variable[var]['min']) /
                variable[var]['nbins']) + unit + " )")
    else:
        bkg = THStack("Bkg",
                      ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events; ")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    leg = TLegend(0.65, 0.6, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    if showSignal:
        for i, s in enumerate(sign):
            if sample[s]['plot']:
                leg.AddEntry(hist[s], sample[s]['label'], "fl")

    leg.SetY1(0.9 - leg.GetNRows() * 0.05)

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if RATIO else 600)

    if RATIO:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), RATIO)
        setBotPad(c1.GetPad(2), RATIO)
    c1.cd(1)
    c1.GetPad(bool(RATIO)).SetTopMargin(0.06)
    c1.GetPad(bool(RATIO)).SetRightMargin(0.05)
    c1.GetPad(bool(RATIO)).SetTicks(1, 1)

    log = variable[var]['log']  #"log" in hist['BkgSum'].GetZaxis().GetTitle()
    if log: c1.GetPad(bool(RATIO)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    if not isBlind and len(data) > 0: hist['data_obs'].Draw("SAME, PE")  # data
    if 'sync' in hist: hist['sync'].Draw("SAME, PE")
    #data_graph.Draw("SAME, PE")
    if showSignal:
        smagn = 1.  #if treeRead else 1.e2 #if log else 1.e2
        for i, s in enumerate(sign):
            #        if sample[s]['plot']:
            hist[s].Scale(smagn)
            hist[s].Draw(
                "SAME, HIST"
            )  # signals Normalized, hist[s].Integral()*sample[s]['weight']
        textS = drawText(0.80, 0.9 - leg.GetNRows() * 0.05 - 0.02,
                         stype + " (x%d)" % smagn, True)
    #bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075)
    bkg.GetYaxis().SetTitleOffset(0.9)
    #bkg.GetYaxis().SetTitleOffset(2.)
    bkg.SetMaximum((5. if log else 1.25) * max(
        bkg.GetMaximum(),
        hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25)
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        #bkg.GetYaxis().SetMoreLogLabels(True)
    bkg.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max'])

    #if log: bkg.SetMinimum(1)
    leg.Draw()
    #drawCMS(LUMI[year], "Preliminary")
    drawCMS(LUMI[year], "", suppressCMS=True)
    drawRegion('XVH' + channel, True)
    drawAnalysis(channel)

    setHistStyle(bkg, 1.2 if RATIO else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1)

    if RATIO:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / MC")
        err.GetYaxis().SetTitleOffset(0.9)

        err.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max'])
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        res = hist['data_obs'].Clone("Residues")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                res.SetBinContent(
                    i,
                    res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                res.SetBinError(
                    i,
                    res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
        if 'sync' in hist:
            res.SetMarkerColor(2)
            res.SetMarkerStyle(31)
            res.Reset()
            for i in range(0, res.GetNbinsX() + 1):
                x = hist['data_obs'].GetXaxis().GetBinCenter(i)
                if hist['sync'].GetBinContent(hist['sync'].FindBin(x)) > 0:
                    res.SetBinContent(
                        i, hist['data_obs'].GetBinContent(
                            hist['data_obs'].FindBin(x)) /
                        hist['sync'].GetBinContent(hist['sync'].FindBin(x)))
                    res.SetBinError(
                        i, hist['data_obs'].GetBinError(
                            hist['data_obs'].FindBin(x)) /
                        hist['sync'].GetBinContent(hist['sync'].FindBin(x)))
        setBotStyle(res)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if not isBlind and len(data) > 0:
            res.Draw("SAME, PE0")
            #res_graph.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(hist['data_obs'], hist['BkgSum'])
                drawStat(hist['data_obs'], hist['BkgSum'])

    c1.Update()

    if gROOT.IsBatch():
        if channel == "": channel = "nocut"
        varname = var.replace('.', '_').replace('()', '')
        if not os.path.exists("plots/" + channel):
            os.makedirs("plots/" + channel)
        suffix = ''
        if "b" in channel or 'mu' in channel: suffix += "_" + BTAGGING
        c1.Print("plots/MANtag_study/deepCSV_plots/pt_" + year + suffix +
                 ".png")
        c1.Print("plots/MANtag_study/deepCSV_plots/pt_" + year + suffix +
                 ".pdf")

    # Print table
    printTable(hist, sign)

    print 'deepCSV efficiency:', N_signal_tag / N_signal_tot
Пример #29
0
    pad1.cd()

    hs.SetMaximum(1.6 * max(hs.GetMaximum(), LepBDTDATA_list[i].GetMaximum()))
    LepBDTDATA_list[i].SetMaximum(
        1.6 * max(hs.GetMaximum(), LepBDTDATA_list[i].GetMaximum()))
    hs.SetMinimum(10)  #EF for ele BDT

    hs.Draw("histo")
    LepBDTDATA_list[i].Draw("sameEP")

    hs.SetTitle("")
    hs.GetXaxis().SetTitle("BDT score")
    hs.GetXaxis().SetRangeUser(0.75, 1)  #EF for ele BDT
    hs.GetXaxis().SetLabelFont(43)
    hs.GetXaxis().SetLabelSize(15)
    hs.GetYaxis().SetTitleSize(20)
    hs.GetYaxis().SetTitleFont(43)
    hs.GetYaxis().SetTitleOffset(1.8)
    hs.GetYaxis().SetLabelFont(43)
    hs.GetYaxis().SetLabelSize(15)
    hs.GetYaxis().SetTitle("Events")

    gStyle.SetOptStat(0)
    pad1.SetLogy()

    # legend
    legend = TLegend(0.1, 0.75, 0.3, 0.9)  #left alignment
    #legend = TLegend(0.7,0.75,0.9,0.9) #right alignment
    legend.AddEntry(LepBDTDATA_list[i], "Data", "p")
    legend.AddEntry(LepBDTMCDY_list[i], "DY MC", "f")
    legend.AddEntry(LepBDTMCTTbar_list[i], "t#bar{t} MC", "f")
Пример #30
0
def createCompoundPlots(detector, plot, geometry):
    """Produce the requested plot for the specified detector.

       Function that will plot the requested @plot for the specified
       @detector. The specified detector could either be a real
       detector or a compound one. The list of available plots are the
       keys of plots dictionary (imported from plot_utils.

    """
    setTDRStyle()
    
    theDirname = 'Images'
    if not checkFile_(theDirname):
        os.mkdir(theDirname)

    goodToGo, theDetectorFilename = paramsGood_(detector, plot, geometry)
    if not goodToGo:
        return

    hist_X0_elements = OrderedDict()

    # stack
    stackTitle = "%s;%s;%s" % (detector,
                                               plots[plot].abscissa,
                                               plots[plot].ordinate)
    stack_X0 = THStack("stack_X0", stackTitle);
    theLegend = TLegend(0.50, 0.70, 0.70, 0.90);

    def setRanges(h):
        legendSpace = 1. + 0.3 # 30%
        minY = h.GetYaxis().GetXmin()
        maxY = h.GetBinContent(h.GetMaximumBin()) * legendSpace
        h.GetYaxis().SetRangeUser(minY, maxY)

    for label, [num, color, leg] in six.iteritems(hist_label_to_num):
        # We don't want the sum to be added as part of the stack
        if label is 'SUM':
            continue
        hist_X0_elements[label] = get1DHisto_(detector,
                                              num + plots[plot].plotNumber,
                                              geometry)
        hist_X0_elements[label].SetFillColor(color)
        hist_X0_elements[label].SetLineColor(kBlack)
        stack_X0.Add(hist_X0_elements[label])
        if hist_X0_elements[label].Integral() > 0.: theLegend.AddEntry(hist_X0_elements[label], leg, "f")

    # canvas
    canname = "MBCan_1D_%s_%s"  % (detector, plot)
    can = TCanvas(canname, canname, 800, 800)
    can.Range(0,0,25,25)
    gStyle.SetOptTitle(0)

    # Draw
    setRanges(stack_X0.GetStack().Last())
    stack_X0.Draw("HIST");
    stack_X0.GetXaxis().SetLabelSize(0.035)
    stack_X0.GetYaxis().SetLabelSize(0.035)
    theLegend.Draw();

    cmsMark = TLatex()
    cmsMark.SetNDC();
    cmsMark.SetTextAngle(0);
    cmsMark.SetTextColor(kBlack);    
    cmsMark.SetTextFont(61)
    cmsMark.SetTextSize(5e-2)
    cmsMark.SetTextAlign(11)
    cmsMark.DrawLatex(0.16,0.86,"CMS")

    simuMark = TLatex()
    simuMark.SetNDC();
    simuMark.SetTextAngle(0);
    simuMark.SetTextColor(kBlack);    
    simuMark.SetTextSize(3e-2)
    simuMark.SetTextAlign(11)
    simuMark.DrawLatex(0.16,0.82,"#font[52]{Simulation Internal}")
 
    # Store
    can.Update();
    can.SaveAs( "%s/%s_%s_%s.pdf" 
                % (theDirname, detector, plot, geometry))
    can.SaveAs( "%s/%s_%s_%s.png" 
                % (theDirname, detector, plot, geometry))